Welcome to MailBee.NET Objects v12.0

This document contains an overview and class reference of MailBee.NET Objects library. Its main goal is to provide you with all required information on how to enable your applications to send, receive, and manage e-mail using MailBee.NET Objects library.

  • Sales, Licensing, and Support
  • Using MailBee.NET Objects in Your Projects
  • Using License Keys
  • Troubleshooting
  • Sample Application Projects (Visual Studio 2005/2008/2010/2012/2013/2015/2017/2019)
  • Xamarin / .NET Core / .NET Standard Edition
  • UWP Edition (Universal Windows, UAP 10.0)
  • Developer's Guide
  • Assembly Reference

You can also browse MailBee.NET Objects Online Samples Directory for more samples.

NOTE Due to a bug in Visual Studio 2012, some MailBee.NET samples may not work when being run under debugger (causing System.AccessViolationException). Running without debugging or upgrading to a later Visual Studio version eliminates the problem.

Send feedback to AfterLogic

Copyright © 2006-2019 AfterLogic Corporation. All rights reserved.


Using MailBee.NET Objects in Your Projects

The following steps demonstrate how to add a reference to MailBee.NET Objects libraries in your applications.

Referencing MailBee.NET Objects library

There are multiple ways for this, NuGet Package Manager is the easiest option.

In Visual Studio via Package Manager Console

Run this command:

Install-Package MailBee.NET

The latest version of MailBee.NET Objects assembly appears in your project.

If your app makes use of Ews component, then run:

Install-Package MailBee.NET.EWS

EWS functionality is supported for .NET 3.5/4.0/4.5+ and .NET Standard 2.0 (.NET Core 2.0+).

If your app makes use of HtmlToPdf class (PDF functionality), then run:

Install-Package MailBee.NET.PDF

PDF functionality is supported for .NET 2.0/3.5/4.0/4.5+ (.NET Framework only, .NET Core is not supported).

In Visual Studio via Add Reference

If NuGet is not an option..

Multiple versions of MailBee.NET.dll are shipped with the product, and get installed in various sub-folders of "C:\Program Files (x86)\MailBee.NET Objects" common folder:

  • Generic version 2.0\MailBee.NET.dll (for .NET Framework 2.0 or higher, Client Profile compatible). Can be used with higher versions of .NET Framework as well. Ews component is not supported by this version (.NET Framework 3.5+ is required).
  • 3.5\MailBee.NET.dll - .NET Framework 3.5 version. Adds support of Ews component.
  • 4.0\MailBee.NET.dll - .NET Framework 4.0 version. Featureset is almost the same as of 3.5 version.
  • 4.5\MailBee.NET.dll - the version optimized for .NET Framework 4.5 or higher (supports more features such as async/await methods).
  • netstandard1.3\MailBee.NET.dll - .NET Core 1.0/1.1 version. Based on 4.5 version but has significant limitations. See .NET Core Edition topic for details.
  • netstandard2.0\MailBee.NET.dll - .NET Core 2.0+ version (also supports modern UWP applications). Based on 4.5 version with a few limitations. See .NET Core Edition topic for details.
  • uap10\MailBee.NET.dll - UWP (Universal Windows) version. Intended for Windows targets older than Windows 10 Fall Creators Update). See UWP Edition (Universal Windows, UAP 10.0) topic for details.

In case if your app uses Ews component, you'll also need to add a reference to MailBee.NET.EWS.dll (available for .NET 3.5/4.0/4.5+ and .NET Standard 2.0), and Microsoft.Exchange.WebServices.dll (or Microsoft.Exchange.WebServices.NETStandard.dll for .NET Standard 2.0).

In case if your app uses Pdf component, you'll also need to add a reference to MailBee.NET.PDF.dll (available for .NET 2.0/3.5/4.0/4.5), and iTextSharp.dll. There is no PDF support for .NET Standard / .NET Core. Note that MailBee.NET installer won't install the PDF-related DLLs unless you tick the correponding checkbox during the installation process.

In the steps below, it's assumed your Visual Studio project is named EmailApp.

  1. In the Solution Explorer, right-click the project name (EmailApp), and select Add Reference command in the context menu.
  2. In the appeared Add Reference dialog, find MailBee.NET Objects for your .NET Framework version (in case if you installed multiple versions). You may need to enlarge this dialog window to see file paths of the dlls because .NET Framework version of each dll is stored in the path, e.g. "C:\Program Files (x86)\MailBee.NET Objects\4.5\MailBee.NET.dll").
  3. Alternatively, if you have a newer version of MailBee.NET.dll (more recent than the one which came with the installer) or the version you're looking for is not in the list, you can click Browse button and manually locate MailBee.NET.dll file. Then double-click the reference to add it into the list and click OK. Now MailBee.NET Objects library gets referenced from your application.
  4. In the properties of the reference added, make sure Copy Local setting is True.

In newer versions of Visual Studio, path to the dll is not shown by default so you may need to hover mouse cursor over to see the path (and determine the version). In this case, it's .NET 4.5+ version of MailBee.NET.dll:

Again, this is only important if you have multiple MailBee.NET entries here (for different .NET Framework versions).

In the steps above, we uploaded a copy of MailBee.NET.dll into the project folder and referenced this copy. The original MailBee.NET.dll is no longer needed. The application can be easily XCOPY deployed using this method.

You can find the detailed guide on how to reference MailBee.NET.dll at Import namespaces and set license key article (the article belongs to "IMAP and POP3" guide but the approach remains the same for all MailBee.NET components).

In non-Visual Studio environment

To reference MailBee.NET Objects library in non-Visual Studio application, you should manually upload MailBee.NET.dll file into the /bin folder under the root folder of your application. If there is no /bin folder, you should create it first.

The application referencing MailBee.NET Objects library in such a way can take advantage of XCOPY deployment.

Importing MailBee namespaces

Once MailBee.NET Objects library is referenced from your application, the next step is to import namespaces declared in the library, into your application.

In the code below, we import all the available namespaces. You may keep only those declarations of namespaces which are actually used by your application.

Place the lines below at the top of your code file:

  • C#
  • VB
using MailBee;
using MailBee.DnsMX;
using MailBee.Mime;
using MailBee.EwsMail;
using MailBee.SmtpMail;
using MailBee.Pop3Mail;
using MailBee.ImapMail;
using MailBee.Security;
using MailBee.AntiSpam;
using MailBee.AddressCheck;
using MailBee.Outlook;
using MailBee.Pdf;

Imports MailBee
Imports MailBee.DnsMX
Imports MailBee.Mime
Imports MailBee.EwsMail
Imports MailBee.SmtpMail
Imports MailBee.Pop3Mail
Imports MailBee.ImapMail
Imports MailBee.Security
Imports MailBee.AntiSpam
Imports MailBee.AddressCheck
Imports MailBee.Outlook
Imports MailBee.Pdf

Depending on your MailBee.NET edition, some namespaces may not be available (e.g. PDF component is not available in .NET Core and UWP).

Assigning the license key

To unlock the product in trial or permanent mode, you need to assign the license key. The license key can be specified in config file (app.config, web.config, or machine.config), in Windows registry (SaveKey and SaveKeyGui utilities can place the license key into the registry), or in static (Shared in Visual Basic) MailBee.Global.LicenseKey property. See Using License Keys topic on how to obtain and specify the license key.

Usage example

Now you can use MailBee.NET Objects classes in your application. In this sample, we send a simple e-mail message with a single line of code.

  • C#
  • VB
Smtp.QuickSend("from@me.com", "to@you.com", "Hello", "How are you?");

Smtp.QuickSend("from@me.com", "to@you.com", "Hello", "How are you?")

Send feedback to AfterLogic


Using License Keys

Trial license key

During downloading MailBee.NET Objects package, you can get a trial license key which allows you to evaluate MailBee.NET Objects in fully-functional mode for a period of 30 days. You can also get the trial key using Get a Trial Key tool in MailBee.NET Start Menu launcher.

Permanent license key

When you purchase a license for MailBee.NET Objects library or any individual part of this library (such as MailBee.NET POP3), you receive a permanent license key which allows you to use the licensed components for an unlimited period of time.

There are no trial or permanent versions of MailBee.NET Objects library. Single version of the package is used in both trial and permanent mode. The status of whether the library is working in trial or permanent mode is fully controlled by the license key.

Assigning the license key

With .NET Framework, you can use ANY method of the listed below, to specify the license key. With .NET Core and UWP, setting the key directly in code is the only option.

The license key (either trial or permanent) needs to be specified in the config file (such as app.config, web.config, machine.config), or in the static (Shared in Visual Basic) MailBee.Global.LicenseKey property, or directly in the constructor of the component you're instantiating. Setting the license key in the config file is the preferred method (unless you need to redistribute the application and thus hide the license key from the end user).

  1. Setting the license key in the config file (app.config, web.config, machine.config):

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!-- License key for MailBee.NET -->
    <!-- Note that MN120-0123456789ABCDEF-0123 is not a real key. Use your key instead. -->
    <add key="MailBee.Global.LicenseKey" value="MN120-0123456789ABCDEF-0123"/>
  </appSettings>
</configuration>

You should NOT attempt to specify the license key in appname.exe.config file created by Visual Studio in Debug or Release folder of the project. Visual Studio overwrites this file during rebuilding the project.

  1. Setting the license key using LicenseKey property (you should set this property before creating any instances of the licensed component):

    MailBee.Global.LicenseKey = "MN120-0123456789ABCDEF-0123";

    If you redistribute the application to third-parties without the source code, embedding the key in the code may be the preferred method of hiding the license key from end users.

  2. Setting the license key and creating an instance at the same time:

    • C#
    • VB
    MailBee.ImapMail.Imap imapComponent = new Imap("MN120-0123456789ABCDEF-0123");

    Dim imapComponent As New MailBee.ImapMail.Imap("MN120-0123456789ABCDEF-0123")

    In fact, #3 is a shorthand form of the previous method.

    1. Placing the license key into Windows registry (the license key will be saved in the registry in an encoded form, thus you can also use this method in case if you need to redistribute the application).

      To put the license key into the registry, you can use SaveKey or SaveKeyGui utilities which are located in MailBee.NET Objects installation folder. You can quickly start SaveKeyGui utility by clicking "Save License Key to Registry" item in MailBee.NET Start Menu.

      SaveKeyGui provides friendly interface to the user while SaveKey console application is intended to be used by installation programs. If you need to put the license key into Windows registry programmatically, call SaveKey utility with parameters. To learn how to use this utility, run it in a command-line not specifying any parameters.

      SaveKey utility also has an option to put the license key in machine.config file (although it's not recommended to use this option since the machine.config file will be reformatted).

      Note 1 You should use "Run as Administrator" option under Windows Vista and above in order to use SaveKey and SaveKeyGui utilities.

      Note 2 Make sure your application has the permission to read Windows registry (by default, ASP.NET applications may have some limitations on reading the registry under certain Trust levels).

      Note 3 When using MailBee.NET.dll for .NET 2.0 or .NET 3.5 (but not MailBee.NET.dll for .NET 4.0 and 4.5) on a 64-bit platform, make sure Visual Studio uses AnyCPU or x64 configuration of your application (in case of Mixed Platforms, examine the particular configuration for the project which uses MailBee.NET.dll). If MailBee.NET.dll is used in x86 (32-bit) project on a 64-bit system, it may be unable to find the license key in the registry. This is because 32-bit app on 64-bit Windows sees a different registry (Wow6432Node). Although SaveKeyGui and SaveKey apps may workaround this, it's not guaranteed to work in 100% of cases.

    Note 3 applies to MailBee.NET.dll for .NET 2.0 and 3.5 only (usually used with Visual Studio 2008 or earlier, .NET 2.0/3.0/3.5). Starting from .NET 4.0, CLR enables 32-bit applications to "see" 64-bit registry. Thus, MailBee.NET.dll for .NET 4.0 and .NET 4.5 can find the license key regardless of 32-bit/64-bit configuration issues. However, permission issues may still apply (such as ASP.NET restrictions mentioned above).

    This screenshot shows x86 configuration in red ("don't use me"). If for some reason you need to use x86 mode on 64-bit Windows for your application, consider upgrading to .NET 4.0+ or store the license key in both 32-bit and 64-bit registry (-rw option of SaveKey tool). Or, you can set the key in the code, app.config, or web.config file.

    Send feedback to AfterLogic


Sales, Licensing, and Support

Sales

Licenses can be purchased online or through any of our resellers.

Note that you can purchase not only the entire MailBee.NET Objects bundle but individual components as well.

You can find more information about the available payment methods at Ordering Information page.

How to obtain support

AfterLogic provides free technical support for MailBee.NET products before and after the sale:

  • Find answers in Knowledge Base
  • Request Support via online form
  • You are welcome to visit our Online Support Forum
  • Or e-mail your inquires to support@afterlogic.com

Send feedback to AfterLogic


Deployment and redistribution of MailBee.NET Objects with your application

I'm going to distribute my application powered by MailBee.NET Objects. Which files should I include in my package?

  • MailBee.NET.dll is the mandatory file.
  • If your application uses iCal and vCard functionality from ICalVCard.dll, you'll need to redistribute it as well.
  • If you're using MailBee.BounceMail classes, you'll also need to supply bounce definition database which resides in BounceDatabase folder of MailBee.NET Objects installation. This database is a set of XML files. There are other options available: single xdb file or your own storage. See DeliveryStatusParser(byte[]) topic for details.
  • If you're using Ews component, add MailBee.NET.EWS.dll, and Exchange Web Services Managed API library (Microsoft.Exchange.WebServices.dll in case of .NET Framework or Microsoft.Exchange.WebServices.NETStandard.dll in case of .NET Core).
  • If you're using MailBee.Pdf classes, add MailBee.NET.PDF.dll, ITextSharp.dll and HtmlAgilityPack.dll assemblies.

It's not required to register the .DLLs in GAC or anything like that. Just make sure they reside in the application folder, or in /bin folder in case of a web application. Placing in GAC, however, grants an assembly Full Trust level, which may be the desired behavior if you want to give such permissions to MailBee.NET.dll. For instance, to make use of S/MIME functions, Full Trust is required due to the need to make WinAPI calls. In case when the standard Trust Level of the application domain is lower than Full Trust, adding MailBee.NET.dll to GAC will be among possible solutions.

Send feedback to AfterLogic


Sample Application Projects (Visual Studio 2005/2008/2010/2012/2013/2015/2017/2019)

MailBee.NET Objects setup program installs a number of ready-to-use Visual Studio 2005 (.NET 2.0), Visual Studio 2012 (.NET 4.5), Visual Studio 2017 (.NET Core 2.0) sample application projects of desktop applications (WinForms and Console). These projects can also be opened in newer versions of Visual Studio as well, up to Visual Studio 2019.

The setup program also installs large sample project for ASP.NET which comes in Visual Studio 2008 (.NET 2.0/3.5) and Visual Studio 2013 (.NET 4.5) versions. They consist of many individual pages which demonstrate different aspects of the usage of MailBee.NET Objects. Again, you can open them in Visual Studio 2015/2017/2019 as well.

A live working installation of some of these ASP.NET samples is also available online at Live Demos page.

In particular, the sample projects demonstrate how to use MailBee.NET Objects in various scenarios: POP3, IMAP4, SMTP, bulk e-mail address validation. Other sample projects show how to communicate with e-mail servers over secure TLS/SSL connection and how to use S/MIME for e-mail encryption and other security tasks.

Also, there are a number of OAuth 2.0 samples and tutorials for ASP.NET MVC, console and desktop applications which highlight different aspects of using access and refresh tokens with Microsoft and Google providers (Gmail, Outlook.com, Live.com, Hotmail.com). Google Apps Service Accounts are also supported. This functionality is only available for .NET 4.5-4.8, .NET Core 2.0+, and UWP. See .NET Core Edition topic for details.

.NET 4.5 versions of all the samples use async/await methods whenever possible.

Most sample projects come in VB.NET and C# versions (.NET Core projects are C# only).

To access the sample projects, click Browse WinForms Samples or Browse ASP.NET Samples buttons in MailBee.NET Start Menu tool, or just open My Documents\MailBee.NET Objects\Samples folder.

Send feedback to AfterLogic


Online Samples

A number of working ASP.NET demo samples can be tried online at Live Demos page. C# and VB.NET projects of these samples are shipped with the product.

Also, there is a MailBee.NET Objects Online Samples Directory which contains dozens of C# and VB.NET code snippets.

Send feedback to AfterLogic


.NET Core Edition

MailBee.NET library is also available in the version which is compatible with .NET Standard 1.3 and higher (.NET Core 1.0/1.1) and .NET Standard 2.0 and higher (.NET Core 2.0 and higher). It can be used with Xamarin, ASP.NET Core, UWP (Windows 10 Fall Creators Update and newer). Tested with .NET Core 1.0/1.1/2.0/2.1/2.2.

.NET Core 1.0/1.1

.NET Core 1.0/1.1 (.NET Standard 1.3) edition mostly has .NET 4.5 feature set (including async/await methods) with the following limitations:

  • License key can only be set in the code (no Windows Registry, machine.config and so on).
  • No sync versions of many methods, only async/await versions. You may get PlatformNotSupportedException when calling, let's say, Imap.Connect instead of Imap.ConnectAsync (this seems to be an issue with .NET Core 1.0/1.1 only).
  • BounceMail requires .NET Standard 2.0 edition at least.
  • ICalVCard library is not compatible with .NET Core.
  • Mail merge and e-mail address validation over database requires .NET Standard 2.0 edition at least.
  • No RTF-to-HTML conversion during parsing MS-TNEF (winmail.dat), Outlook .MSG and .PST files.
  • No HTML to PDF conversion (MailBee.Pdf component is not supported).
  • No EWS (Exchange Web Services) support.
  • S/MIME can only work on Windows.
  • Direct send without SMTP relay server: no system DNS server autodetection via WMI, config file or Windows Registry. It still works on Windows but may not work on other platforms. The affected method: DnsServerCollection.Autodetect. You can still add DNS servers manually, e.g. by filling Global.DnsServers collection.

.NET Core 2.0 and newer

.NET Core 2.0 (.NET Standard 2.0) edition has much less limitations:

  • No HTML-to-PDF conversion.
  • ICalVCard library not supported (you can use other open-source alternatives like iCal.NET).
  • S/MIME tested on Windows only.

What you need to run MailBee with .NET Core

The MailBee.NET.dll for .NET Core resides in C:\Program Files (x86)\MailBee.NET Objects\.netstandard1.3 folder (...\.netstandard2.0 for .NET Core 2.0). Or, via NuGet, the required .DLL will be installed automatically. Just run this command:

Install-Package MailBee.NET

Install System.Text.Encoding.CodePages package (for .NET Core 2.0+):

Install-Package System.Text.Encoding.CodePages

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) must be called before accessing any MailBee classes. This initializes codepages support in .NET Core runtime.

Filesystem access (paths to locations accessible for reading or writing files) is also platform-specific and can depend on your application settings and permissions. If you just need some place where to save the log file for debugging, System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) folder can be used.

Xamarin examples

The below are some samples of using MailBee.NET Objects in Xamarin. They feature using IMAP component in async manner as well as writing into the log file on the device's filesystem. POP3 and SMTP components can be used in the same manner.

For iOS, the code below is MasterViewController.cs from MasterDetail template. For Android, it's MainActivity.cs from Android Application template. The Xamarin for Visual Studio version used to produce these samples was 4.2.

  • iOS
  • Android
using System;
using System.Drawing;
using System.Collections.Generic;

using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Threading.Tasks;

using CoreGraphics;
using Foundation;
using UIKit;

using MailBee;
using MailBee.ImapMail;

namespace iOsTest
{
    public partial class MasterViewController : UITableViewController
    {
        DataSource dataSource;

        public MasterViewController (IntPtr handle) : base (handle)
        {
            Title = NSBundle.MainBundle.LocalizedString ("Master", "Master");

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
                PreferredContentSize = new CGSize (320f, 600f);
                ClearsSelectionOnViewWillAppear = false;
            }

            // Custom initialization
        }

        public DetailViewController DetailViewController {
            get;
            set;
        }

        async void AddNewItem (object sender, EventArgs args)
        {
            string text;
            try
            {
                // See LicenseKey setting in ViewDidLoad.

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Imap imp = new Imap ();

                // How to work with filesystem (writing the log file).
                imp.Log.Filename = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "log.txt");
                imp.Log.Enabled = true;
                await imp.Log.ClearAsync();

                // See Application Output window in Xamarin for System.Diagnostics.Debug results.
                await imp.ConnectAsync ("mail.server.com");
                await imp.LoginAsync ("user@domain.com", "secret");
                await imp.SelectFolderAsync("Inbox");
                text = imp.MessageCount.ToString();
                await imp.DisconnectAsync();
            }
            catch (MailBeeException e)
            {
                System.Diagnostics.Debug.Print (e.ToString());
                text = e.GetType ().Name;
            }

            dataSource.Objects.Insert (0, text);
            using (var indexPath = NSIndexPath.FromRowSection (0, 0))
                TableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic);
        }

        public override void DidReceiveMemoryWarning ()
        {
            // Releases the view if it doesn't have a superview.
            base.DidReceiveMemoryWarning ();

            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            // Perform any additional setup after loading the view, typically from a nib.
            NavigationItem.LeftBarButtonItem = EditButtonItem;

            var addButton = new UIBarButtonItem (UIBarButtonSystemItem.Add, AddNewItem);
            NavigationItem.RightBarButtonItem = addButton;

            TableView.Source = dataSource = new DataSource (this);

            try
            {
                // See Application Output window in Xamarin for System.Diagnostics.Debug results.
                MailBee.Global.LicenseKey = "MNXXX-XXXXXXXX-XXXX";
            }
            catch (MailBeeException e)
            {
                System.Diagnostics.Debug.Print (e.ToString());
            }
        }

        class DataSource : UITableViewSource
        {
            static readonly NSString CellIdentifier = new NSString ("Cell");
            readonly List<object> objects = new List<object> ();
            readonly MasterViewController controller;

            public DataSource (MasterViewController controller)
            {
                this.controller = controller;
            }

            public IList<object> Objects {
                get { return objects; }
            }

            // Customize the number of sections in the table view.
            public override nint NumberOfSections (UITableView tableView)
            {
                return 1;
            }

            public override nint RowsInSection (UITableView tableview, nint section)
            {
                return objects.Count;
            }

            // Customize the appearance of table view cells.
            public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
            {
                var cell = (UITableViewCell)tableView.DequeueReusableCell (CellIdentifier, indexPath);

                cell.TextLabel.Text = objects [indexPath.Row].ToString ();

                return cell;
            }

            public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath)
            {
                // Return false if you do not want the specified item to be editable.
                return true;
            }

            public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
            {
                if (editingStyle == UITableViewCellEditingStyle.Delete) {
                    // Delete the row from the data source.
                    objects.RemoveAt (indexPath.Row);
                    controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
                } else if (editingStyle == UITableViewCellEditingStyle.Insert) {
                    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
                }
            }

            /*
            // Override to support rearranging the table view.
            public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath)
            {
            }
            */

            /*
            // Override to support conditional rearranging of the table view.
            public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath)
            {
                // Return false if you do not want the item to be re-orderable.
                return true;
            }
            */

            public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
            {
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    controller.DetailViewController.SetDetailItem (objects [indexPath.Row]);
            }
        }

        public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
        {
            if (segue.Identifier == "showDetail") {
                var indexPath = TableView.IndexPathForSelectedRow;
                var item = dataSource.Objects [indexPath.Row];

                ((DetailViewController)segue.DestinationViewController).SetDetailItem (item);
            }
        }
    }
}

using System;
using System.IO;
using System.Text;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using MailBee;
using MailBee.ImapMail;

namespace AndroidTest
{
    [Activity (Label = "AndroidTest", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        Imap imp = null;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            try
            {
                // See Application Output window in Xamarin for System.Diagnostics.Debug results.
                MailBee.Global.LicenseKey = "MNXXX-XXXXXXXX-XXXX";
            }
            catch (MailBeeException e)
            {
                System.Diagnostics.Debug.Print(e.ToString());
            }

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button> (Resource.Id.myButton);

            button.Click += async delegate {
                try
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    Imap imp = new Imap ();

                    // How to work with filesystem (writing the log file).
                    imp.Log.Filename = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "log.txt");
                    imp.Log.Enabled = true;
                    await imp.Log.ClearAsync();

                    // See Application Output window in Xamarin for System.Diagnostics.Debug results.
                    await imp.ConnectAsync ("mail.server.com");
                    await imp.LoginAsync ("user@domain.com", "secret");
                    await imp.SelectFolderAsync ("Inbox");
                    int msgCount = imp.MessageCount;
                    await imp.DisconnectAsync ();
                    button.Text = string.Format ("{0} messages!", msgCount);
                }
                catch (MailBeeException e)
                {
                    System.Diagnostics.Debug.Print(e.ToString());
                    button.Text = e.GetType().Name;
                }
            };
        }
    }
}

Send feedback to AfterLogic


UWP Edition (Universal Windows, UAP 10.0)

With Windows 10 Fall Creators Update and newer, you can use .NET Standard 2.0 version of MailBee.NET Objects (C:\Program Files (x86)\MailBee.NET Objects\netstandard2.0). This is the most recommended approach.

If your UWP app must target an older version of Windows, you can use the special UWP edition of MailBee.NET library. UWP edition mostly has .NET 4.5 feature set (including async/await methods). Still, a number of limitations do exist:

  • License key can only be set in the code (no Windows Registry, machine.config and so on).
  • No sync versions of many methods, only async/await versions. You'll get PlatformNotSupportedException when calling, let's say, Imap.Connect instead of Imap.ConnectAsync.
  • No BounceMail support.
  • No Exchange Web Services (EWS) support.
  • ICalVCard library is not supported.
  • No mail merge and e-mail address validation over database.
  • No RTF-to-HTML conversion during parsing MS-TNEF (winmail.dat), Outlook .MSG and .PST files.
  • No HTML to PDF conversion (MailBee.Pdf component is disabled).
  • Some limitations on working with certificates.
  • Direct send without SMTP relay server: no system DNS server autodetection via WMI, config file or Windows Registry. It still works on Windows but may not work on other platforms. The affected method: DnsServerCollection.Autodetect.

However, in case if you can use the .NET Standard 2.0 version (the Min Target of your UWP project is Windows 10 Fall Creators Update), the only limitations would be the lack of HTML-to-PDF conversion and no ICalVCard library support (you can use other open-source alternatives like iCal.NET).

What you need to run MailBee with UWP (Windows 10 Fall Creators Update or newer)

In Project properties, make sure that Target version and Min version is Windows 10 Fall Creators Update or newer. The MailBee.NET.dll resides in C:\Program Files (x86)\MailBee.NET Objects\netstandard2.0 folder. Or, via NuGet, the required .DLL will be installed automatically:

Install-Package MailBee.NET

The above installs MailBee.NET.dll from lib\uap10.0.16299 folder of the package. This is the same library which resides in lib\netstandard2.0 folder. 16299 denotes Windows 10 Fall Creators Update.

Install System.Text.Encoding.CodePages package:

Install-Package System.Text.Encoding.CodePages

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) must be called before accessing any MailBee classes. This initializes codepages support in the runtime.

What you need to run MailBee with UWP (older Windows)

The MailBee.NET.dll for UWP resides in C:\Program Files (x86)\MailBee.NET Objects\uap10.0 folder. Or, via NuGet, the required .DLL will be installed automatically. Just run this command:

Install-Package MailBee.NET

The above installs MailBee.NET.dll from lib\uap10.0 folder of the package (assuming that Min Target for the project is Windows version older than Fall Creators Update).

You must update Microsoft.NETCore.UniversalWindowsPlatform NuGet package to 5.2.2 (for Visual Studio 2015) or higher version (for Visual Studio 2017).

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) must be called before accessing any MailBee classes. This initializes codepages support in .NET runtime.

Socket support is different in UWP therefore methods like Imap.GetSocket return StreamSocket, not Socket. Socket class was not supported by UWP prior to Windows 10 Fall Creators Update.

You must use SocketCreating event instead of ClientServerCertificates.AutoValidation to configure which SSL certificate errors can be tolerated (useful if you need to connect to a mail server with self-signed certificate). See code snippet in Imap.SocketCreating topic for example. ClientServerCertificates.AutoValidation property is not supported.

In case of Windows 10 Fall Creators Update being Min Target (so that .NET Standard 2.0 version of MailBee.NET.dll is used instead of UWP version), Imap.GetSocket will return Socket (not StreamSocket). And you can use ClientServerCertificates.AutoValidation property.

Filesystem access

Filesystem access in UWP (paths to locations accessible for reading or writing files) is limited to the app's folders like ApplicationData.Current.LocalFolder.Path. If you just need some place where to save the log file for debugging, Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt") path can be used. For example:

msg.Parser.WorkingFolder = ApplicationData.Current.LocalFolder.Path (assuming msg is MailMessage instance).

If your UWP app must load some additional files (let's use the bounce database for BounceMail component as an example), it should store them in Assets folder:

  • Copy file (e.g. bouncedatabase.xdb into Assets folder of the project)
  • In Solution Explorer, include this file into a project and set Build Action to Content
  • In the app code, get the path to the Assets folder:
  • var path = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets")
  • Get the path to the file:
  • string xdbPath = Path.Combine(localizationDirectory.Path, "bouncedatabase.xdb")
  • Load the file contents:
  • byte[] xdb = await File.ReadAllBytesAsync(xdbPath)
  • Initialize BounceMail parser
  • DeliveryStatusParser parser = new DeliveryStatusParser(xdb)

BounceMail is not available in UWP prior to Windows 10 Fall Creators Update.

Capabilities section of Package.appxmanifest must have Internet (Client) and Private Networks (Client & Server) options checked. The latter is needed if you want to connect to localhost mail servers. Otherwise, you may get UnauthorizedAccessException or MailBeeSocketTimeoutException. You may also need more settings (Package Manifest / Declarations / Protocol / Name) in case if you want to add OAuth 2.0 authentication, see OAuth 2.0 for Universal Windows apps guide.

In our tests of Windows authentication, login with SASL NTLM method didn't work with UWP apps while SASL GSSAPI does. See AuthenticationMethods topic for more info on the authentication mechanisms available in MailBee.

UWP example

This is the UWP example for older Windows. In case of Windows 10 Fall Creators Update or newer, see OAuth 2.0 for Universal Windows apps guide.

This C#/VB example logs in your Gmail inbox via OAuth 2.0 and displays the body of the last e-mail, including embedded pictures if any (the pictures will be base64 embedded directly in HTML). The sample also demonstrates logging IMAP session into a file, excepting handling, enabling self-signed certificates (the latter is not needed for Gmail but can be useful if you need to use a local mail server). To make this sample work, do the following:

  • Create Blank App (Universal Windows)
  • Update Microsoft.NETCore.UniversalWindowsPlatform NuGet package to 5.2.2 (or a higher version if you're using Visual Studio 2017).
  • Place Button (named button1) and WebView (named web) controls on the form.
  • Add NuGet references for MailBee.NET, Google.Apis.Oauth2.v2, Microsoft.Bcl.Async (the latter is needed for Google APIs to work). If getting "Package restore failed. Rolling back package changes" error, this means Microsoft.NETCore.UniversalWindowsPlatform is still of 5.1.0 version or lower.
  • Add client_secrets.json file to your Assets folder and set its Build Action to Content. You can download this JSON file from Credentials section of Google Developer Console. Unlike classic .NET Framework, Google APIs for UWP cannot yet consume OAuth 2.0 secrets directly from code, only from this file (more exactly, from URL).
  • Add Click handler for Button1.
  • Replace MainPage.xaml.cs or MainPage.xaml.vb with the code below.
  • Apply your MailBee.NET license key.
  • C#
  • VB
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Popups;
using Windows.Storage;
using Windows.Networking.Sockets;
using Windows.Security.Cryptography.Certificates;
using System.Text;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
using Google.Apis.Services;
using MailBee;
using MailBee.Mime;
using MailBee.ImapMail;

namespace UniApp1
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        static void Imp_SocketCreating(object sender, SocketCreatingEventArgs e)
        {
            // Demonstrate how we can allow self-signed or expired certificates.
            e.NewSocket = new StreamSocket();
            e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
            e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
        }

        private async void button_Click(object sender, RoutedEventArgs e)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            MailBee.Global.LicenseKey = "MN1XX-XXXXXXXX-XXXX";

            Imap imp = new Imap();
            imp.Log.Filename = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");
            imp.Log.Enabled = true;
            await imp.Log.ClearAsync();

            // Request Gmail IMAP/SMTP scope and the e-mail address scope.
            string[] scopes = new string[] { "https://mail.google.com/", Oauth2Service.Scope.UserinfoEmail };

            System.Diagnostics.Debug.WriteLine("Requesting authorization");
            Uri SecretsUri = new Uri("ms-appx:///Assets/client_secret.json", UriKind.Absolute);
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(SecretsUri, scopes, "user", CancellationToken.None);
            System.Diagnostics.Debug.WriteLine("Authorization granted or not required (if the saved access token already available)");

            if (credential.Token.IsExpired(credential.Flow.Clock))
            {
                System.Diagnostics.Debug.WriteLine("The access token has expired, refreshing it");
                if (await credential.RefreshTokenAsync(CancellationToken.None))
                {
                    System.Diagnostics.Debug.WriteLine("The access token is now refreshed");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("The access token has expired but we can't refresh it :(");
                    return;
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("The access token is OK, continue");
            }

            System.Diagnostics.Debug.WriteLine("Requesting the e-mail address of the user from Google");

            // Sometimes, you may also need to set Initializer.ApplicationName property.
            // In our tests, setting just Initializer.HttpClientInitializer was enough for Google.
            Oauth2Service oauthService = new Oauth2Service(
                new BaseClientService.Initializer() { HttpClientInitializer = credential });

            // Userinfo.Get may crash if you run the app under debugger (a bug in Google API).
            // If this happens, use "Start without debugging" instead.
            Userinfoplus userInfo = await oauthService.Userinfo.Get().ExecuteAsync();
            string userEmail = userInfo.Email;
            System.Diagnostics.Debug.WriteLine("E-mail address is " + userEmail);

            // Build XOAUTH2 token. Can be used with Gmail IMAP or SMTP.
            string xoauthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

            try
            {
                await imp.ConnectAsync("imap.gmail.com", 993);
                await imp.LoginAsync(null, xoauthKey, AuthenticationMethods.SaslOAuth2);
                await imp.SelectFolderAsync("Inbox");
                MailMessage msg = await imp.DownloadEntireMessageAsync(imp.MessageCount, false);
                await imp.DisconnectAsync();
                string html = msg.GetHtmlWithBase64EncodedRelatedFiles();
                web.NavigateToString(html);
            }
            catch (MailBeeException ex)
            {
                if (imp.IsConnected)
                {
                    await imp.DisconnectAsync();
                }
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                MessageDialog dialog = new MessageDialog(ex.ToString());
                await dialog.ShowAsync();
            }
        }
    }
}

Imports Windows.UI.Popups
Imports Windows.Storage
Imports Windows.Networking.Sockets
Imports Windows.Security.Cryptography.Certificates
Imports System.Text
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Oauth2.v2
Imports Google.Apis.Oauth2.v2.Data
Imports Google.Apis.Services
Imports MailBee
Imports MailBee.Mime
Imports MailBee.ImapMail

Public NotInheritable Class MainPage
    Inherits Page

    Sub Imp_SocketCreating(sender As Object, e As SocketCreatingEventArgs)
        e.NewSocket = New StreamSocket()
        e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName)
        e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted)
        e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired)
    End Sub

    Private Async Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)

        MailBee.Global.LicenseKey = "MN1XX-XXXXXXXX-XXXX"

        Dim imp As New Imap()

        imp.Log.Filename = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt")
        imp.Log.Enabled = True
        Await imp.Log.ClearAsync()

        ' Request Gmail IMAP/SMTP scope and the e-mail address scope.
        Dim scopes As String() = New String() {"https://mail.google.com/", Oauth2Service.Scope.UserinfoEmail}

        System.Diagnostics.Debug.WriteLine("Requesting authorization")
        Dim SecretsUri As New Uri("ms-appx:///Assets/client_secret.json", UriKind.Absolute)
        Dim credential As UserCredential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(SecretsUri, scopes, "user", CancellationToken.None)
        System.Diagnostics.Debug.WriteLine("Authorization granted or not required (if the saved access token already available)")

        If credential.Token.IsExpired(credential.Flow.Clock) Then
            System.Diagnostics.Debug.WriteLine("The access token has expired, refreshing it")
            If Await credential.RefreshTokenAsync(CancellationToken.None) Then
                System.Diagnostics.Debug.WriteLine("The access token is now refreshed")
            Else
                System.Diagnostics.Debug.WriteLine("The access token has expired but we can't refresh it :(")
                Return
            End If
        Else
            System.Diagnostics.Debug.WriteLine("The access token is OK, continue")
        End If

        System.Diagnostics.Debug.WriteLine("Requesting the e-mail address of the user from Google")

        ' Sometimes, you may also need to set Initializer.ApplicationName property.
        ' In our tests, setting just Initializer.HttpClientInitializer was enough for Google.
        Dim oauthService As New Oauth2Service(New BaseClientService.Initializer() With {
            .HttpClientInitializer = credential
        })

        ' Userinfo.Get may crash if you run the app under debugger (a bug in Google API).
        ' If this happens, use "Start without debugging" instead.
        Dim userInfo As Userinfoplus = Await oauthService.Userinfo.Get().ExecuteAsync()
        Dim userEmail As String = userInfo.Email
        System.Diagnostics.Debug.WriteLine(Convert.ToString("E-mail address is ") & userEmail)

        ' Build XOAUTH2 token. Can be used with Gmail IMAP or SMTP.
        Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

        Dim savedEx As MailBeeException = Nothing ' Unlike C#, we can't await in Catch in VB14 (although this will change in VB17).
        Try
            Await imp.ConnectAsync("imap.gmail.com", 993)
            Await imp.LoginAsync(Nothing, xoauthKey, AuthenticationMethods.SaslOAuth2)
            Await imp.SelectFolderAsync("Inbox")
            Dim msg As MailMessage = Await imp.DownloadEntireMessageAsync(imp.MessageCount, False)
            Await imp.DisconnectAsync()
            Dim html As String = msg.GetHtmlWithBase64EncodedRelatedFiles()
            web.NavigateToString(html)
        Catch ex As MailBeeException
            savedEx = ex
            System.Diagnostics.Debug.WriteLine(ex.ToString())
        End Try
        If imp.IsConnected Then
            Await imp.DisconnectAsync()
        End If
        If savedEx IsNot Nothing Then
            Dim dialog As New MessageDialog(savedEx.ToString())
            Await dialog.ShowAsync()
        End If
    End Sub
End Class

Send feedback to AfterLogic


Xamarin Mono, Android, iOS Editions

MailBee.NET library for Mono has been superseded by .NET Core edition.

Send feedback to AfterLogic


MS Exchange, Office 365, Shared Mailboxes

  • SMTP/IMAP pros, EWS cons
  • EWS pros, SMTP/IMAP cons
  • EWS Managed API
  • Office 365
  • Shared mailbox access

MailBee can work with Exchange (and Office 365 which is powered by Exchange 2016) via both common IMAP/SMTP protocols and proprietary Exchange Web Services (EWS) protocol. MailBee components to use are Imap/Smtp and Ews, respectively.

SMTP/IMAP pros, EWS cons

If your code is supposed to work with different mail servers, not just Exchange, using SMTP/IMAP lets you write code just once. EWS can work with Exchange only.

SMTP/IMAP can be used with .NET Core and UWP apps. EWS support is currently available for classic .NET Framework v3.5-4.7 only (it relies on EWS Managed API Microsoft hasn't ported to .NET Core yet). This will hopefully change soon.

EWS pros, SMTP/IMAP cons

SMTP and especially IMAP services can often be turned off in Exchange. They also operate on ports which are often blocked by firewalls. EWS, on other hand, operates on standard HTTP/HTTPS ports.

SMTP/IMAP support in Exchange is limited. For instance, search of international strings in Exchange's IMAP is not possible, only plain ASCII strings (while IMAP standard in theory allows for using UTF-8 for search queries). Featureset of EWS is much wider. You can even add/remove attachments in mail messages while in IMAP mail messages are immutable.

SMTP/IMAP can be enabled on the Exchange server but disabled for particular user. EWS is usually enabled for most users. See MS Exchange troubleshooting for more details.

EWS Managed API

To use Ews component, you need to install EWS Managed API from Microsoft. You can add it as a reference from C:\Program Files (x86)\MailBee.NET Objects\Microsoft.Exchange.WebServices.dll (Microsoft.Exchange.WebServices.NETStandard.dll in case of .NET Core). Or you can do it with NuGet:

Install-Package MailBee.NET.EWS

EWS is supported in .NET Framework 3.5/4.0/4.5+ and .NET Core 2.0+.

Due to limitations of EWS Managed API libraries, you have to use synchronous methods in case of .NET Framework and asynchronous methods in case of .NET Core.

The detailed example of working with EWS can be found in Ews topic.

Office 365

Office 365 supports both IMAP/SMTP and EWS so it's up to you to decide which option to select (based on pros and cons above). The access details:

  • IMAP host: mail.office365.com port 993 SSL
  • SMTP host: mail.office365.com port 587 STARTTLS
  • EWS URL: https://outlook.office365.com/EWS/Exchange.asmx
  • Login/password: your e-mail address/password

Shared mailbox access

To access shared mailbox's folders in MS Exchange or Office 365 via IMAP, you should log in with YourAccount@domain.com\SharedMailboxAlias username and your account's password. You'll be logged in a shared mailbox instead of your normal account. From that, you can proceed as usually.

With EWS, it's different. You log in normally you and then select a folder in the shared mailbox you want to work with:

  • C#
  • VB
// It's assumed ewsClient is Ews instance, with credentials and server host already set.
FolderId id = new FolderId(WellKnownFolderName.Inbox, "shared-primary-smtp-address@domain.com");

// Demonstrate uploading a message in the folder.
MailBee.Mime.MailMessage msg = new MailBee.Mime.MailMessage();
ewsClient.UploadMessage(id, msg, false);

// Demonstrate getting the folder.
EwsFolder folder = ewsClient.DownloadFolderById(id);

// Demonstrate getting the folder contents.
EwsItemList sentItems = ewsClient.DownloadItems(id, null, false, EwsItemParts.GenericItem);

' It's assumed ewsClient is Ews instance, with credentials and server host already set.
Dim id As New FolderId(WellKnownFolderName.Inbox, "shared-primary-smtp-address@domain.com")

' Demonstrate uploading a message in the folder.
Dim msg As New MailBee.Mime.MailMessage()
ewsClient.UploadMessage(id, msg, False)

' Demonstrate getting the folder.
Dim folder As EwsFolder = ewsClient.DownloadFolderById(id)

' Demonstrate getting the folder contents.
Dim sentItems As EwsItemList = ewsClient.DownloadItems(id, Nothing, False, EwsItemParts.GenericItem)

Important: in IMAP, you specify an alias of a shared mailbox, in EWS - its primary SMTP address. They are often the same but can be different sometimes.

Send feedback to AfterLogic


Troubleshooting

Updating to the latest version

If you encountered a bug, there is a chance it's resolved in the latest version. To check this, remove your existing reference to MailBee.NET and install the latest version by running this command in NuGet package manager console:

Install-Package MailBee.NET

License key issues

  • Make sure the key starts with MN120. In any other case, the key is outdated (such as MN900, etc), or for another product (for instance, MBC900 key is for ActiveX version of MailBee components).
  • Check that the key has not expired. Exception message from MailBee is self-explaining in this regard. It will be something like Imap component not licensed. Trial LicenseKey is expired.
  • Permission can be an issue when using the license key is stored in the registry. For instance, Get a Trial Key tool in MailBee.NET Start Menu puts the key in the registry. ASP.NET apps may not see it if they aren't granted even read-only access to the registry. Consider setting the key in the code, app.config, or web.config (see Using License Keys for details).
  • Another possible issue with the registry is that if your application targets 32-bit (x86) configuration on a 64-bit system, MailBee will be unable to find the license key. This is only possible for MailBee.NET.dll for .NET 2.0 or .NET 3.5. MailBee.NET.dll edition for .NET 4.0 and .NET 4.5 is immune to this issue. See Using License Keys for details, or just specify the key in the code, app.config, or web.config.

E-mail body text unreadable ("?" or unprintable characters, codepage issues)

This happens with .NET Core apps if codepages subsystem is not initialized. To fix, install System.Text.Encoding.CodePages package (for .NET Core 2.0+). In NuGet console:

 Install-Package System.Text.Encoding.CodePages

Also, Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) method must be called before accessing any MailBee class (e.g. in Main method or Form_Load, depending on the application type). This initializes codepages support in .NET Core runtime.

Enabling Safe Mode

By default, MailBee tries to take advantage of extended capabilities offered by mail servers. However, sometimes these extended features might not work properly despite the fact the mail server claims it supports them. The common reason for this is network antivirus, firewall or mail filter which may intercept the traffic between the mail server and the client. If it does not support any features supported by the mail server itself, this may cause problems.

MailBee allows the developer to disable any advanced features. To disable them all at once, set MailBee.Global.SafeMode property to true before creating any instances or calling any methods of MailBee classes.

System.AccessViolationException when being run under debugger

If you experience System.AccessViolationException exceptions in Visual Studio, try to run the app without debugging (Ctrl-F5 instead of normal F5). In this case, upgrading to a newer version of Visual Studio may help. For instance, Visual Studio 2012 Update 3 is prone to this problem while Visual Studio 2013 is fine.

Logging the mail session into a file

Log file can be very useful for debugging any errors which occur during the session between the mail server and the client. Also, if you decided to contact our technical support for resolving the issue, you should also attach the log file. You can enable logging using Log property of any mailer component (including Smtp, Pop3, Imap and Ews).

With Ews, it's also useful to enable .NET Framework tracing of all network activities. See Ews.Log topic for details.

Testing with another e-mail client like Mozilla Thunderbird

Often, the issue may be caused by your network configuration, not by the errors in the code. You should also try to do the same with another POP3/IMAP/SMTP client. For instance, if you can't send a message, try to do the same with Thunderbird. But be sure to send from the same computer where you're using MailBee, using the same protocol and account settings (for instance, if the SMTP authentication is not used in MailBee, disable it in Thunderbird as well).

Even if the problem still does not get reproduced with Thunderbird, make sure your antivirus or firewall software (if any) does not treat popular e-mail clients in a special way. For instance, many security programs put the most popular email programs on white list while unknown programs may get blocked.

Also, please note that you should test using plain POP3/IMAP/SMTP clients, not those which can work via proprietary protocols (Microsoft Office Outlook is an example). Microsoft Office Outlook can communicate with mail servers manufactured by Microsoft (such as Exchange) using internal protocols which are not supported by other software. Windows Live Mail is another example. With such e-mail clients, you should check what type of connection you're using. It must be IMAP or POP3 for incoming e-mail and SMTP for outbound. Or, you can stick with Thunderbird.

Accessing mail via SSL

Most mail services nowadays support only SSL/TLS connections with mail servers. In such cases, you should use SslMode property to enable SSL connections and use the appropriate SSL port number. Some servers allow you to use regular (not SSL) ports but change the regular connection into secure one during the already established connection with the mail server. This is called STARTTLS and such option can be set as one of values of SslMode property.

You may also need to set the particular SSL/TLS protocol to use. See MailBee.Security.SecurityProtocol topic. Usually, setting server.SslProtocol=MailBee.Security.SecurityProtocol.TlsAuto helps in most scenarios (server is Imap, Pop3 or SmtpServer instance).

Accessing mail on MS Exchange servers

Administrators often enable only MAPI access and no IMAP/POP3/SMTP as MS Outlook clients typically use MAPI and do not need IMAP or SMTP to connect to MS Exchange. Make sure SMTP, IMAP or POP3 are enabled and their respestive ports are opened if you have connectivity problems. Login errors often occur when the Exchange server expects the full login name (domain\jdoe) or even domain\jdoe\alias to be supplied as a login name while you supplied just an account name (jdoe). Another issue with MS Exchange 2007 and above is that plain-text authentication may only work if you're on SSL connection (dedicated port or STARTTLS).

When sending e-mail through Exchange server, it may help to disable CHUNKING extension (especially if Exchange SMTP Tar Pitting is enabled). To disable CHUNKING (so that MailBee won't use BDAT command instead of DATA even if the server states BDAT is supported), use this code:

server.SmtpOptions = ExtendedSmtpOptions.NoChunking

(server is SmtpServer object instance).

For Exchange accounts with Administrator rights, IMAP/SMTP access is usually disabled. Use normal user accounts instead.

Exchange Information Store service must be running. Otherwise, you'll get login errors in IMAP.

With MS Exchange, consider switching to Ews component if possible.

Typical problems

  • Login errors often occur when the mail server expects the full e-mail address (jdoe@domain) to be supplied as a login name while you supplied only an account name (jdoe). Another common error: jdoe was expected while you supplied jdoe@domain.com. Some mail clients automatically try both methods so that you may never know that the login name you always used is, strictly speaking, incorrect (and your mail client actually gets logged in only on a second attempt).
  • Gmail requires the user to enable Less secure apps to let mail clients log in with a password. In case if you don't want to require that from the user, the only option would be using passwordless authentication, OAuth 2.0. See OAuth 2.0 for Google Regular Accounts (installed applications).
  • Web login required and similar errors indicate that the user must log in via web interface first (common for Gmail). This is often the case for web applications which access the user's mailbox from another location and the mail service thinks someone else stole the user's password and is now trying to log in on behalf of that user.
  • Sending to non-local e-mail addresses usually fails if SMTP authentication is not enabled in MailBee. Most mail servers nowadays are configured to prohibit relay to external addresses for non-authenticated clients. See examples in Smtp.Send topic on how to enable SMTP authentication.
  • SSL errors typically occur on attempt to connect to a dedicated TLS/SSL port in StartTLS mode (or to a regular port in dedicated TLS/SSL mode). Changing value of SslMode property (available forSmtpServer, Pop3 and Imap classes) fixes the problem. For instance, if you set Pop3.SslMode to SslStartupMode.UseStartTls and tried to connect to a dedicated TLS/SSL port (995 for S/POP3), you'll be getting exceptions until you change Pop3.SslMode to SslStartupMode.OnConnect.

More troubleshooting tips

  • SMTP (send e-mail) troubleshooting
  • IMAP and POP3 troubleshooting

Send feedback to AfterLogic


Version History

  • 12.0

    • .NET Core 2.0 / .NET Standard 2.0 edition revised and improved, including better support of .NET Core 2.1 and 2.2.
    • .NET Standard 2.0 support in UWP. UWP apps targeting Windows 10 Fall Creators Update and newer can use the fully-functional .NET Standard 2.0 edition of MailBee.NET Objects. Special UWP edition of MailBee.NET Objects which can work with older UWP platform is still there as well.
    • .NET Core 2.0 sample projects and tutorials added (UWP, console and ASP.NET Core). They feature OAuth 2.0 authentication against Google (Gmail.com) and Microsoft (Live.com, Outlook.com, Hotmail.com) providers along with sending and receiving e-mail using these providers.
    • Improved support of Outlook Converter functionality on iOS and Android.
    • EWS is now supported for .NET Core (.NET Core 2.0+ required). However, only async methods are supported (in .NET Framework edition it's quite opposite, only sync method are supported - this is the limitation of the Managed EWS API).
    • EWS and PDF functionality was moved into friend assemblies. Because EWS and PDF are dependent on other libraries, this caused these libraries be included in the project even if they are not actually needed. Now if the app does not use PDF or EWS, the corresponding libraries will never be referenced, neither directly nor indirectly. Separate Nuget packages for MailBee.NET.EWS and MailBee.NET.PDF were added as well.
    • Exception messages now suggest setting SslProtocol to TlsAuto in case if SSL/TLS handshake fails due to unsupported protocol (usually TLS 1.0 in case if the server requires TLS 1.2).
    • More accurate handling of SSL/TLS related exceptions (now throws MailBeeException instead of system-level AuthenticationException).
    • TLS 1.2 is now fully supported in .NET 2.0/3.5 (despite the fact that .NET 2.0/3.5 itself does not support anything better than TLS 1.0).
    • Documentation now highlights that you must install System.Text.Encoding.CodePages NuGet package for .NET Core 2.0+ apps.
    • Added ConfigureAwait(false) in all internal async calls.
    • Memory/performance optimizations on reading .EML data from stream.
    • MailMessage.GetHtmlAndSaveRelatedFiles and other similar methods now support cid:filename-like CIDs.
    • MsgConvert.PreferAddressesFromInternetHeaders property lets you control from which parts of .MSG file to extract the headers (as sometimes the .MSG file can have these values available in multiple locations and these values are not the same).
    • MailMessage.SetDomainKeysSignOnSend property enables automatic DKIM signing when sending the message.
    • Empty headers are now added to the message being sent in case if they are DKIM signed.
    • S/MIME signatures are now time-stamped by default. Smime.TimestampOnSign property lets you turn this off (as it's a time-consuming network operation).
    • S/MIME signatures now include full certificate chain, can be turned off with Smime.IncludeWholeChainOnSign property.
    • Envelope.HasSystemFlag, a helper method to check the envelope for particular IMAP flags.
    • OAuth 2.0 is now supported in EWS, see Ews.SetCredentials(ExchangeCredentials) method.
    • Bounce database updated.
    • Misc. bugfixes to the code and documentation.
    • Also tested with Visual Studio 2019.
    • License keys in a new MN120 format. If you have a valid maintenance contract, contact us to receive your new key. If your contract has already expired, you need to renew it first.

  • 11.2

    • .NET Core 2.0 / .NET Standard 2.0 edition (including BounceMail and mail merge over database support).
    • Support of UWP Release builds.
    • Protected constructors added for all exception classes (required for serialization).
    • Empty MAIL FROM is now allowed for SMTP.
    • No extra CRLF in the end of DATA transmission in SMTP.
    • MAIL FROM now includes SIZE if the SMTP server limits the size of messages being submitted.
    • Short path for SMTP authentication (AUTH method_name initial challenge). Fixes issues with Microsoft's SMTP.
    • Misc. bugfixes and documentation fixes.

  • 11.1

    • New RblFilter class to perform spam filtering using DNS RBLs.
    • Better support of certificates in .NET Core and Xamarin. Can now use client certificates in SSL/TLS connections and DKIM.
    • Imap.SetSeenForEntireMessages is now false by default. This means MailBee won't set SEEN flag when downloading entire messages unless you change this property value.
    • New Global.DnsServers property to override the default list of DNS servers assigned for the current system. Useful if DNS server autodetection is not supported on the current platform (e.g. Xamarin).
    • New TimeStamp.IP property which represents the IP address the message came from.
    • Improved autodetection of inline images in Outlook .MSG files.
    • Misc. bugfixes.

  • 11.0

    • .NET Core edition, .NET Core 1.0/1.1, .NET Standard 1.3 and Xamarin compatible.
    • UWP edition (Universal Windows, UAP 10.0).
    • New Ews component, provides access to MS Exchange server via its native EWS protocol.
    • .NET Framework 3.5 and 4.0 builds in addition to 2.0 and 4.5 builds are now included with the installer and in NuGet package.
    • Much more methods now have async/await versions.
    • MailBee.NET.dll for all .NET versions now has the same name.
    • sha256 signatures in addition to sha1 for all MailBee.NET dlls.
    • IDN domains (e-mail addresses with international domains) support for both sending and parsing.
    • MailMessage.GetHtmlWithBase64EncodedRelatedFiles method to save HTML body with related images being directly embedded in the HTML so that there is no need to save them locally and delete them afterwards.
    • STARTTLS secure connection is now supported in direct send mode. To activate, use mailer.DirectSendDefaults.EnableStartTls = true where mailer is Smtp instance.
    • SecurityProtocol now includes TlsAuto value which you can use to restrict MailBee to use the best supported TLS protocol (up to TLS 1.2). E.g. imapClient.SslProtocol = SecurityProtocol.TlsAuto where imapClient is Imap instance.
    • Imap.GetSpecialFolder method to easily locate folders like Sent Items or Drafts.
    • GetStream method of Imap, Smtp, Pop3 classes now lets you get access to the underlying network Stream.
    • SocketCreating event of Imap, Smtp, Pop3 classes lets you use your own socket initialization. This is especially useful for UWP apps to configure which SSL certificate errors can be tolerated. For instance: Imap.SocketCreating.
    • Outlook 2016 .MSG format support.
    • Support of distribution lists in .PST files.
    • MailMessage.Sender property added.
    • New Logger.DateTimeFormatTimeOnly and Logger.DateTimeFormatFull properties to configure datetime formats in the log file.
    • SmimeResult.SignedCmsResult and SmimeResult.EnvelopedCmsResult properties to give access to SignedCms and EnvelopedCms data of S/MIME messages.
    • Smtp.TransientErrorOccurred event to decide what to do on transient SMTP errors in case if another SMTP server available. The app can either stop trying or try with another SMTP server. The default behavior is to retry in case of relay servers and stop trying in case of MX servers.
    • Bounce database updated.
    • Misc. bugfixes.
    • Also tested with Visual Studio 2017.
    • License keys in a new MN110 format. If you have a valid maintenance contract, contact us to receive your new key. If your contract has already expired, you need to renew it first.

  • 10.0

    • MailBee.NET.45.dll (.NET 4.5 optimized).
    • MailBee.NET.Mono.dll with .NET 4.5 feature set (Xamarin-ready).
    • MailBee.NET.Android.dll with .NET 4.5 feature set (Xamarin-ready). Supports Android 4.4 (KitKat) or higher.
    • MailBee.NET.iOS.dll with .NET 4.5 feature set (Xamarin-ready). Supports iOS 8 or higher.
    • Added async/await methods to Smtp, Imap, Pop3, EmailAddressValidator, AntiSpam.BayesFilter, MailMessage, Attachment, DomainKeys classes (for .NET 4.5 or higher).
    • Bounce parser can read bounce definitions database from a single file or memory (in addition to a set of XML files as before).
    • New ClientServerCertificates.CheckCertificateRevocation property.
    • New DirectSendServerConfig.EnableStartTls property.
    • TLS 1.1 and TLS 1.2 support (new Tls11 and Tls12 values in SecurityProtocol enum).
    • New MsgConvert.MsgIsFromMe property.
    • Html.Processor.Images and .AHRefs collections now clearly marked read-only.
    • Global.PreserveMimePartOrder and Global.UnwrappedLineLengthLimit new properties.
    • MessageParserConfig.WriteUtf8ByteOrderMark property to correctly write UTF-8 encoded HTML files.
    • The default TCP buffer size is now 65536 bytes instead of 8192 bytes (improves network operations performance).
    • Numerous bugfixes and performance optimizations across the library.
    • Revised samples.
    • New documentation look.
    • Tested with Windows 10, Visual Studio 2015, .NET Framework 4.6.
    • License keys in a new MN100 format. If you have a valid maintenance contract, contact us to receive your new key. If your contract has already expired, you need to renew it first.

  • 9.0

    • OAuth 2.0 can now work via Google API Auth Client library which supports all OAuth 2 capabilities provided by Google including Service Accounts. DotNetOpenAuth support is still available. New OAuth2.GetXOAuthKeyStatic method for that.
    • New OAuth 2.0 tutorials for Windows and ASP.NET MVC apps.
    • FIPS 140-2 compatibility enforcement with MailBee.Global.FipsMode property.
    • DKIM signing with strong SHA256 signatures.
    • The assembly is marked with SecurityRules(SecurityRuleSet.Level1) attribute which lets it run in a wider range of security-restricted .NET configurations.
    • Autodetection of SSL settings now works for outlook.com and office365.com (in addition to gmail, yahoo, etc).
    • New AuthenticationOptions.BypassLoginProcedure option for implementing custom non-SASL login procedures (which are not based on SaslMethod class.
    • Smtp.SubmitToPickupFolder now overwrites the file if its filename is specified.
    • Smtp.SubmitToPickupFolder now preserves international characters in x-sender and x-receiver if they are present in e-mail addresses.
    • Imap.SetSeenForEntireMessages property to easily control whether downloading entire messages should set SEEN flag or not (enabled by default).
    • IMAP MOVE extension support (if the server supports MOVE, moving messages no longer involves copying + deleting).
    • IMAP CHILDREN support (FolderFlags.HasChildren and FolderFlags.HasNoChildren flags make it easier to work with large number of nested folders).
    • IMAP SPECIAL-USE extension support (such as new folder flags like FolderFlags.Archive).
    • New TnefParser class to parse standalone winmail.dat files.
    • MailMessage.ImportRelatedFiles now works much faster with HTML-embedded images (like <img src="data:base64block">).
    • AttachmentCollection.Add now adds attachments from URLs when NewAttachmentOptions.PathIsUri flag is set.
    • .EML attachments (having "rfc822/message" content-type) are now added "as-is" by default, no extra base64 encoding applied. This eliminates issues with reading forwarded e-mails in some e-mail clients which cannot decode .EML attachments from base64.
    • E-mail parser can now process e-mails having CR line endings (in addition to standard CRLF and sometimes used LF endings which have already been supported before).
    • Global.FixBadDates property to allow invalid Date values in e-mail messages (often the case when parsing spam e-mails).
    • Auto-detection of an attempt to load Outlook .MSG file as if was .EML MIME file. Earlier the message was initialized with garbage, now MailBee will throw an exception.
    • MsgConvert.PreferRtfBodyToHtml property for fine-tuning .MSG-to-.EML conversions.
    • SASL PLAIN login authentication method now tolerates the response which cannot be decoded from base64.
    • The password of an account on a mail server can now be empty (for instance, some SMTP servers require authentication with non-empty username but empty password).
    • AuthenticationOptions.BypassLoginProcedure flag which lets you call Login method of Imap, Pop3, Smtp class without sending anything to the server. Useful if you're doing your own custom login method which is not SASL compatible (for custom SASL logins, SaslLogin class must be inherited).
    • When Logger.DisableOnException is enabled, UnauthorizedAccessException during logging operations will now also be suppressed (earlier, only IOException was suppressed).
    • Log files now include SSL handshakes.
    • MailBeeException.Message property, when the exception has InnerException, now checks if that InnerException also has InnerException, and includes its text as well. This helps understand the cause of the issue in case of deeply nested exceptions.
    • RSA certificate parsing fix (handles the situation when RSA parameters are 63 bytes in length instead of 64 bytes).
    • Smtp.MessageNotSent event no longer causes ParameterCountMismatch exception.
    • SMTP XTEXT protocol fix (used in requesting a delivery status notification, DSN).
    • Bounce parser bugfixes and new bounce formats.
    • E-mail parser fixes to workaround misc. violations of MIME standard by improperly written composers (unclosed quote characters, etc).
    • MailBee.Html processor fix.
    • Lots of Outlook Converter fixes of .MSG and .PST conversions.
    • TNEF parsing fixes.
    • License keys in a new MN900 format. If you have a valid maintenance contract, contact us to receive your new key. If your contract has already expired, you need to renew it first.
    • NuGet support. To get the latest version of MailBee.NET assembly for your .NET framework, run this command in Package Manager Console:
      Install-Package MailBee.NET
    • MailBee.NET assembly signed with Authenticode digital signature.
    • Revised and improved documentation.

  • 8.0.2

    • Improved bounce parser (bugsfixes, new bounce formats added).
    • Fixed regular expression in e-mail address validator to allow for apostrophes in user names and hyphens in domain names.
    • Fixed S/MIME bug with signed e-mails containing only attachments and no text body.
    • Installer now checks AlwaysInstallElevated registry setting to avoid messing up the installation process in such mode.

  • 8.0.1

    • Great improvements in Integrated Windows Authentication implementation (both managed and unmanaged). NTLM and GSSAPI now work in much more scenarios, with both MS Exchange and IIS SMTP service.

  • 8.0

    • All-new EmailAddressValidator component (in MailBee.AddressCheck namespace). Checks bulks of e-mail addresses for syntax and existence. Available both as part of MailBee.NET Objects bundle and under separate license.
    • Added support of mail merge over System.Data.IDataReader, with a number of samples using MS SQL Server database for mail merge.
    • The default charset for new e-mail messages is now "utf-8" (makes creating international e-mails a bit easier)
    • New Smtp.ValidateEmailAddressSyntax method.
    • Support of OAuth v2.0 with OAuth2 class, for all mail protocols. Confirmed to work with Gmail and its XOAUTH2 extension.
    • Constructor overloads accepting license key added, for all licensed components.
    • Imap.DownloadEnvelopes now accepts bodyPreviewSize=-2 to download entire messages but keep them UNSEEN.
    • Easier to understand exceptions when the license key is invalid but it's still a MailBee key (of an older or ActiveX/COM version).
    • MailBee now sees the license key stored in 64-bit registry even when running in a 32-bit process (only for .NET 4.0+ optimized version). For .NET 2.0/3.5, the documentation updated on how to deal with this situation.
    • Some enhancements to the logging subsystem. Large chunks of data are logged with their beginnings and endings for easier preview, LogNewEntry.ToString method added.
    • Improved IPv6 compatibility.
    • Timeout setting now affects not only socket Read and Write operations but Connect as well, for all mail protocols.
    • Added timeout for how long a single SMTP response can be returned by the server added (utilized automatically), to avoid slow-downs with mail servers which return EHLO response very slowly, such as by a single byte every 10 seconds, resulting in several minutes of total time per response.
    • New MailBeeConnectionException.WasConnected property for more accurate error handling.
    • Improved support of Outlook .MSG and .PST conversions.
    • Improved MIME parser and builder, including the support of international characters (especially in headers and attachment filenames), quoted strings in headers, and more.
    • MimePart.GetRawData method to return the undecoded contents of a MIME part.
    • More bounce formats recognized and a number of bugs fixed in MailBee.BounceMail.
    • In SSL, Name Mismatch certificate error is now detected.
    • Removed MailBee.InternalUse namespace with all the classes which only existed to support MailBee.NET Objects internal infrastructure.
    • Errors during Disconnect are handled more gracefully.
    • Reading files from a network share now made in a more reliable way.
    • Revised documentation (added the detailed guide for using EmailAddressValidator, many topics across Assembly Reference have been extended or clarified, more code snippets added).
    • Revised samples. Amongst improvements, the samples now access C:\Temp instead of C:\ to honor UAC restrictions.
    • Extended and improved MailBee.NET Start Menu launcher.
    • Extended and improved SaveKeyGui and SaveKey tools. Now they can save the license key to both 32-bit and 64-bit registry on 64-bit systems (important for .NET 2.0/3.5 apps which can't see 64-bit registry from 32-bit processes). Also, SaveKey tool can now clear the key from the storage, not just put it there.
    • New large sample project named AddressValidatorDemo. Useful not only for verifying e-mail addresses in bulk, but also for implementing mail merge over database and other multi-threaded, database-oriented and asynchronous operations with MailBee.NET Objects as it highlights many useful techniques not necessarily related to checking e-mail addresses.
    • License keys in a new "MN800-" format. If you have a valid maintenance contract, contact us to receive your new key, or renew the maintenance if your contract has already expired.

  • 7.3

    • New CertificateValidationFlags.NameMismatch flag to detect SSL certificates used for domains other then they are issued for.
    • Support of ' (apostrophe) in filenames.
    • Better support of decoding encoded headers.
    • Improved support of .NET Framework 4.0/4.5.
    • Improved support of Windows 8 in the installer.

  • 7.2

    • New DnsAutodetectOptions.RootServers flag enables direct-send via DNS MX lookup even if it's not possible to obtain DNS servers from the system (uses Google servers).
    • Support of Gmail IMAP extensions to extract Gmail-specific thread ID, message ID, message labels. Lets you perform message search with Google syntax, add and remove message labels.
    • Autodetect of Yahoo SMTP/POP3/IMAP port and SSL mode.
    • Misc. improvements to MIME parser (especially timestamps), DomainKeys/DKIM, Outlook .MSG and .PST parser.

  • 7.1

    • COMPATIBILITY: New property HtmlToPdf.SourceType replaces HtmlToPdf.EnableHtmlToXmlConversion. Now PDF component can also convert plain-text into PDF.
    • COMPATIBILITY: New method HtmlToPdf.ConvertFile replaces HtmlToPdf.ConvertHtmlFile.
    • Significant improvements to the PDF builder. Now PDF output reflects the input HTML much closer. The converter now supports some basis CSS styles.
    • MailBee.NET PDF component is now also available as standalone product with separate installer (useful for those PDF users who don't need any e-mail related functionality in their apps). The component integrated in MailBee.NET.dll is still available as well. Both use the license key of the same format.
    • Misc. improvements to MIME parser, Delivery Status Notification parser, Outlook .MSG and .PST parser, TNEF parser.
    • New sample projects (WinForms demos) for Outlook .MSG conversion and HTML-to-PDF conversion.

  • 7.0.1

    • New MailBee.Global.LicenseKey property to specify the license key for all components at once.
    • Misc. fixes and improvements to the installer and documentation.

  • 7.0

    • New PDF Converter component allows for HTML to PDF conversion. You can use it to create and send PDF documents like invoices, when you have them in HTML format.
    • Now includes MailBee.NET.dll natively compiled for .NET 4.0 (.NET 1.1 and .NET Compact deprecated, .NET 2.0/3.5 is still fully supported).
    • Certificate.SubjectAlternativeName property.
    • Numerous improvements and fixes to Outlook .MSG and .PST conversion, MIME parser and builder.
    • License keys of a new format.

  • 6.10.1

    • AuthenticationOptions.UseLocalDomainAsDefault flag to fine-tune MS Exchange authentication via NTLM and GSSAPI, and other improvements to NTLM/GSSAPI authentication.
    • Numerous improvements and fixes to S/MIME functionality.
    • Revised ASP.NET samples.
    • Documentation improvements (Developer's Guide re-structured, added "Deployment and Redistribution" topic, and other fixes).

  • 6.10

    • Support of OpenID and Hybrid OpenID/OAuth authorization (e.g. your application can check e-mail in Gmail without requiring the user to enter their e-mail address and password).
    • Improved authentication sequence and better support of authentication against MS Exchange server.
    • Support of iCal format (create or parse events, appointments, etc). See iCal and vCard calendars and contacts section in Developer's Guide for details.
    • Complex IMAP search made easier with new ImapUtils methods ToLiteral, AnyOf, AllOf, Not.
    • ImapBodyStructure.SafeFilename property.
    • New IMAP FolderFlags values AllMail and Starred (Gmail-compatible).
    • UidCollection and MessageNumberCollection classes in IMAP now have ToArray and IndexOf methods.
    • MessageParserConfig.GetMessageIDHash method.
    • CertificateStore can now be loaded from byte array.
    • Added Developer's Guides for ICalVCard.dll library, IMAP, POP3, Outlook components ("Getting started" topics for now, more topics coming soon).
    • Brand new collection of ASP.NET samples highlights basic and complex aspects of using MailBee.NET Objects. Samples available for Visual Studio 2008 and 2010, both C# and VB.NET.
    • Misc. fixes to MIME and SSL functionality.
    • As usually, numerous fixes to .PST reader and Outlook .MSG converter.

  • 6.9

    • Added Developer's Guide for SMTP component (140+ topics).
    • Support of vCard format (create, parse, send or display photo, etc). See Attachment.IsVCard property for details.
    • COMPATIBILITY: New improved mechanism of auto-detecting DNS servers and new flags for DnsServerCollection.Autodetect(DnsAutodetectOptions) method. Some flags have been removed from DnsAutodetectOptions enumeration.
    • COMPATIBILITY: Message-ID (such as MailMessage.MessageID) now returns its value enclosed in angle brackets "<>".
    • COMPATIBILITY: The standard argument of EHLO/HELO commands is now the IPv4 address of the local system, not the domain of "From" address. Seems to work better with some servers which check this argument value. Still, it's better to specify it manually with Smtp.DirectSendDefaults.HelloDomain property to the public domain name of the system.
    • New ImportBodyOptions.PreferCharsetFromMetaTag flag. Use it when importing HMTL with international characters.
    • New SmtpMessageRecipientSubmittedEventArgs.AllowRefusedRecipient property allows for manual control of allowance of failed recipients during sending e-mail to multiple recipients.
    • Misc. fixes to MIME, mail merge, and S/MIME functionality.
    • Direct send no longer retries other MXes in case of hard-bounce from the first MX (greatly improves performance when sending to lists with many invalid addresses).
    • As always, numerous fixes to .PST reader and Outlook .MSG converter (including the ability to properly extract S/MIME signed items).
    • Documentation now mentions how to use Global class and its properties (like Global.SafeMode) in Visual Basic where Global is a keyword

  • 6.8

    • New Imap.DownloadEnvelopesEx and Imap.BeginDownloadEnvelopesEx methods let you efficiently download text bodies or attachments of e-mails without downloading entire messages. You can download headers and text bodies of multiple e-mails within a single command.
    • Better handling of Inbox folder when IMAP XLIST is used.
    • Negative indices when referring to a POP3 or IMAP message number. For instance, -1 means "the last e-mail" in the folder.
    • Can get RTF body from TNEF (winmail.dat).
    • Easier to sign and verify DKIM and DomainKeys with MailMessage.DomainKeysSign and MailMessage.DomainKeysVerify methods.
    • Can use mail merge and DKIM/DomainKeys signing together.
    • OAuth no longer interferes with regular authentication if XOAUTH is the only supported SASL method.
    • Numerous fixes to .PST reader and Outlook .MSG converter.
    • New MailMessage.Parser.FixCrLf property to fix e-mails not having the correct CRLF sequence at the end of each body line.

  • 6.7

    • Support of OAuth authorization and XOAUTH authentication (widely used by Google).
    • Much improved HTML-to-RTF converter (used during .EML to Outlook .MSG transformations).
    • NTLM and GSSAPI authentication methods can now extract the domain part from the account name.
    • Envelope.From is no longer empty with MS Exchange 2010 IMAP.
    • Uploading e-mails over IMAP improved.
    • Misc. fixes to MIME parser.

  • 6.6

    • Improved legacy .NET 1.1 and .NET Compact Framework support.
    • New more efficient .PST file reader supports both 32-bit and 64-bit Outlook .PST files.
    • Can access any item in Outlook .PST by its numeric ID.
    • Filesystem-compatible names of Outlook .PST folders.
    • SmtpServer/SmtpServerCollection DnsServer/DnsServerCollection classes made Serializable.
    • Can be used with MailBee.NET Queue companion to send bulk mail to SSL-enabled mail servers.
    • Better tolerates not fully RFC-compatible SMTP servers.
    • Better multi-threaded access to Bayes spam/non-spam databases.

  • 6.5

    • GSSAPI and NTLM authentication rewritten from the ground up, now provides managed implementation for .NET 2.0+ (UnmanagedCode permission is no longer required), supports both Integrated Windows Authentication and explicitly specified credentials for both GSSAPI and NTLM, supports GSSAPI via both Kerberos and NTLM, updated to work with MS Exchange 2007/2010.
    • Rewritten unmanaged GSSAPI and NTLM implementation for .NET 1.1 and .NET Compact Framework. Supports everything managed GSSAPI/NTLM .NET 2.0 implementation does.

    • New TargetName (Service Principal Name) and UserDomain settings for all mailer components (Login and BeginLogin method parameters for POP3/IMAP, SmtpServer object properties for SMTP). These values can be used with GSSAPI and NTLM.

      COMPATIBILITY: If you use Imap.BeginLogin or Pop3.BeginLogin method in your code written for earlier versions of MailBee.NET Objects, insert "null, null" (C#) or "Nothing, Nothing" (VB.NET) in place of the newly added parameters.

    • Simplified authentication procedure (retry with a non-secure method if the secure method fails).
    • New flags in AuthenticationOptions to further fine-tune authentication process.
    • Improved logging for easier trouble-shooting (now large data chunks in the logs are presented as a short preview and the total size of the chunk).
    • Support of IMAP XLIST extension (used by Gmail and many others) enables recognition of special folder flags (Drafts, Sent, Trash, etc).
    • Improved support of IMAP APPEND (Imap.UploadMessage method) when used with MS Exchange 2007/2010.
    • Improved support of IMAP servers which allow message flags containing special characters (such as Zimbra).
    • Memory consumption by Smtp object decreased twice when relaying e-mails from file

    • New parameter doubleFirstDotAtLine for methods which submit to IIS SMTP pickup folder works around the issue of IIS SMTP pickup service which results in loosing dot character when it appears at the first position on a line.

      COMPATIBILITY: If you use Smtp.SubmitJobsToPickupFolder or Smtp.SubmitJobsToPickupFolder method in your code written for earlier versions of MailBee.NET Objects, set the new parameter asfalse if you're submitting to MailBee Message Queue or true if you're using IIS SMTP queue.

    • MailMessage.DateSent property allows you to access "Date Sent" value of converted Outlook .MSG files, or make it appear in the resulting .MSG file if you're doing the opposite conversion (into Outlook .MSG).
    • Miscellaneous bug fixes and improvements of Mime, AntiSpam and Outlook functionality.
    • Miscellaneous documentation improvements (highlights usage with MS Exchange and more).
    • The documentation in Visual Studio 2010 format which can be integrated into IDE.

  • 6.0

    • New FIPS-compatible licensing algorithm makes no use of MD5. This allows using MailBee.NET Objects in FIPS-restricted environments such as many banking and government structures.
    • New Outlook.PstReader class which can read .PST files and streams with PST data, traverse through folders, extract messages, appointments, contacts and other PST items.
    • Great memory savings in all major components: e-mail MIME builder and parser, SMTP/POP3/IMAP protocol implementations. Processing large e-mails takes less time and consumes 3-5 times less memory.
    • Method MailMessage.Clear can now remove just the raw message body (this lets you use memory more efficiently).
    • Pop3.InboxPreloadOptions can now take advantage of Pop3InboxPreloadOptions.List to further optimize memory usage.
    • Outlook Message Converter refactored. Now it's in the new namespace Outlook, easier to use and more flexible, provides more methods and properties, fine-tuned in many places. Old OutlookMsgnamespace is still supported for backward compatibility but it's now deprecated and removed from the documentation.
    • New AddJob overloads in Smtp class to allow submitting send mail jobs from .EML files and user-supplied MailMessage objects. Allows for more flexibility and memory savings. This is accompanied by a new Filename property in MailMessage class which allows you to link filenames submitted to MailBee during creating send mail jobs and MailMessage objects created and loaded by MailBee from that files during sending this mail jobs.
    • Exchange 2010 SMTP workaround to avoid timeouts (Exchange 2010 can delay its responses for more than 30 seconds which is more than default 20 seconds timeout in MailBee).
    • Miscellaneous improvements to importing HTML files with embedded pictures, parsing MIME, .Outlook .MSG and MS-TNEF (winmail.dat) files.
    • MailBee exceptions now bear [Serializable] attribute (useful for error tracking when all exceptions which occur in an application are recorded for further analysis).
    • BounceMail supports a number of new bounced e-mail formats.
    • BounceMail now recognizes MDNs (Message Disposition Notifications). MDNs are similar to DSNs with only difference they are created by mail clients rather than by mail servers (for instance, receipt of an e-mail containing an MDN may indicate that the recipient has actually opened the e-mail in the mail reader program).

  • 5.9

    • Imap component now allows you to make use of namespaces (see Imap.GetNamespaces method).
    • MailBee.NET.dll is now compatible with .NET Framework 3.5/4.0 Client Profile (no references to System.Web).
    • New overload of DomainKeys class to enable using this class in ASP.NET web applications.
    • Improved HTML and URL processing in MailBee.NET.CF.dll (.NET Compact Framework version).
    • Outlook Message Converter can now produce editable (Draft) messages in both Unicode and ANSI modes.
    • Outlook Message Converter now supports custom (supplied by the application) HTML-to-RTF generation mechanisms.
    • Miscellaneous improvements and bugfixes to the DomainKeys and BounceMail functionality. and to the parsing mechanism of MIME, HTML and IMAP responses produced by not fully RFC-compliant mail servers (like AOL).

  • 5.8.5

    • Imap component now allows you to specify your own Socket and LocalEndPoint parameters to fine-tune your connections under heavy load (for instance, when dealing with hundreds of connections). Added new overload for Imap.Connect method and changed Imap.BeginConnect method signature.

      COMPATIBILITY: If you use Imap.BeginConnect method in your code written for earlier versions of MailBee.NET IMAP, insert "null, null" (C#) or "Nothing, Nothing" (VB.NET) in place of the newly added parameters.

    • Improved network streams support under .NET 2.0 and above (eliminates issues with uploading and downloading very large e-mails).
    • SaveKeyToRegistry tool improvements.
    • Miscellaneous documentation improvements.

  • 5.8

    • Outlook Message Converter introduces more overloads which can generate Unicode and 8-bit strings in .MSG files.
    • Also, Outlook Message Converter now extracts more dates from .MSG data, works with streams better than before, provides some level of automatic RTF-to-HTML and HTML-to-RTF conversion. In HTML-to-RTF case, it supports conversion of basic tags. In RTF-to-HTML case, it can just extract "HTML embedded into RTF" from that RTF.
    • MailBee.Security.DomainKeys class now supports DKIM (earlier, only classic DK technology was supported).
    • MailBee can now autodetect SSL mode and port settings when connecting to well-known mail services (like gmail.com or live.com) or ports (like 995 for POP3). If desired, this smart behaviour can be disabled using MailBee.Global.AutodetectPortAndSslMode property.
    • AntiSpam.BayesFilter component can now use streams to load/save database of spam/non-spam tokens (earlier, only files were supported).

  • 5.7

    • Outlook Message Converter introduces new overloads of MsgConvert.MailMessageToMsg method which can generate Unicode and 8-bit strings in .MSG files (earlier, only plain-ASCII 7-bit strings were supported).
    • Also, Outlook Message Converter now extracts embedded .MSG files (recursive conversion) and supports Outlook-specific address formats.
    • New sample project for WinForms C# and VB.NET shows advanced real-world use of AntiSpam, IMAP, POP3 and SSL functionality in a single application (techniques used in this project can be employed in ASP.NET projects as well).

  • 5.6.2

    • MailBee.Mime.TextBodyPart object now has a constructor which allows creating this object from a MailBee.Mime.MimePart (useful for IMAP operations like download the text body without downloading attachments).
    • New license agreement.

  • 5.6.1

    • Outlook Message Converter now extracts HTML body from .MSG files (in addition to plain-text and RTF body).
    • Smtp component now better tolerates unexpected disconnections from the server.

  • 5.6

    • New methods MailMessage.ConvertFromSystemNetMail and MailMessage.ConvertToSystemNetMail for interoperability with System.Net.Mail.MailMessage class (only for .NET 2.0 and above).
    • Support of many new bounced e-mail formats.
    • Outlook Message Converter now extracts RTF body from .MSG files (earlier, only plain-text body was extracted).
    • Better recognition of ESMTP authentication capabilities.
    • "Save License Key To Registry" utility now works with Outlook Message Converter component as well.

  • 5.5

    • New component Outlook Message Converter can convert e-mails between normal RFC822 (.EML) format and Outlook 97-2003 .MSG format (OLE2), load .MSG files and streams into MailMessage objects and save these objects into .MSG files and streams. This component does require a license key.
    • Miscellaneous bug fixes (mostly related to MIME and IMAP UTF-7 encoding).
    • Implemented workaround for MS Exchange 2007 bug with STATUS command response.
    • Minor documentation fixes.

  • 5.0

    • New component BounceMail allows your newsletter applications to track delivery of your e-mails, find invalid e-mail addresses and keep your e-mail address database up-to-date. Can be used together with Smtp.DeliveryNotification functionality. BounceMail component does not require a license key.
    • New Security.DomainKeys class which fully supports DomainKeys anti-spam technology (signing new e-mails and verifying signatures of existing e-mails).
    • .NET Compact Framework support (for Windows Mobile devices).
    • Improved SSL support on .NET 2.0/3.0/3.5 Framework (better performance, Full Trust not required).
    • Smtp class can now return reverse DNS (PTR) and TXT records for the specified domain (can be used for anti-spam protection).
    • Better error reporting of WinAPI SSL functions (now provides textual error description from WinAPI).
    • New methods in several classes of Html namespace.
    • Miscellaneous bug fixes (mostly related to MIME).
    • Minor documentation fixes.

  • 4.0

    • New component AntiSpam.BayesFilter which adds Bayesian filter capability to MailBee.NET Objects.
    • MIME parsing improvements and better UUEncode support.
    • SOCKS4/SOCKS5/HTTP proxy bug fixes.
    • Minor documentation fixes.

  • 3.1

    • New property LocalEndPoint in SmtpServer and DirectSendServerConfig classes allows you bind all outgoing SMTP connections with the specific local IP address and port number (useful for performance tuning if your computer has multiple network adapters).
    • New method Smtp.GetMXHosts can be used to get the list of SMTP MX servers for the specified domain.
    • Miscellaneous bugfixes related to MIME parsing, S/MIME, and DNS.
    • Minor documentation fixes.

  • 3.0

    • New Smime component and many other classes in Security namespace related to S/MIME and SSL certificate support. Requires its own license key (like Smtp, Pop3 and Imap components do). The license is, however, included in MailBee.NET Objects bundle.
    • New Processor component and related classes in new Html namespace. Can be used to examine and manipulate DOM (Document Object Model) of HTML documents. Does not require a license key.
    • Mail merge over database and bulk mail (mass mailing) capabilities in Smtp class. Multi-threading (up to 60 threads) is fully supported.
    • DNX MX query cache for improved direct send performance.
    • New SmtpServer properties for tuning SMTP server throughput: MaxConnectionCount, MaxSendPerSessionCount, PauseInterval.
    • New events in Smtp class: MergingMessage, MessageNotSent, MessageSubmittedToPickupFolder, SubmittingMessageToPickupFolder.
    • Proxy support for Smtp, Pop3 and Imap components.
    • SSL certificates support for Smtp, Pop3 and Imap components. Requires MailBee.NET Security license key.
    • Ability to keep already downloaded messages if the entire operation of downloading multiple messages failed in the middle (Pop3.LastDownloadedMessages, Imap.LastDownloadedEnvelopes).
    • IMAP IDLE and SORT extensions now supported (Imap.Idle, Imap.SortedSearch and supporting methods).
    • New events in Imap class: Idling, MessageStatus.
    • MessageParserConfig class now includes EncodingDefault and EncodingOverride properties specifying which encoding to use when the message with international characters does not contain the charset information or this information is incorrect.
    • Global class now includes SafeMode property which disables all advanced capabilities - can be used for troubleshooting.
    • Added AuthenticationOptions.PreferSimpleMethods and made some changes to authentication related classes to workaround the common problem of mail servers when certain authentication mode is supported by the server but is not working properly.
    • SaslMethod class for implementing custom SASL methods extended with a number of new properties.
    • COMPATIBILITY: due to naming conflicts, a few classes and class members have been renamed or removed:
      • Smtp.SubmitToQueue renamed to Smtp.SubmitToPickupFolder.
      • MailBeeMimeException removed, descendants renamed to a more general form (e.g. MailBeeMimeIOException renamed to MailBeeIOException).
      • ExtendedSmtpOptions.No8bitAndBinary removed.
    • Smtp.SubmitToPickupFolder and Smtp.SubmitJobsToPickupFolder methods can submit messages to MailBee Message Queue v1.4 and above (because starting from v1.4, MMQ uses IIS SMTP queue format).
    • 64-bit Windows platforms now fully supported.
    • A great number of miscellaneous bug fixes and improvements through the entire MailBee.NET Objects library.
    • Vast changes in the documentation, especially in Mime namespace.
    • New sample projects for SSL and S/MIME. The existing projects have been significantly improved.
    • The installer now provides the option to install MailBee.NET.dll optimized for .NET Framework 2.0 (and above) as well as the generic version which is compatible with all .NET Frameworks starting from 1.1. You can even install both versions (they won't conflict with each other).
    • The installer is now fully compatible with Windows Vista (including UAC and DEP services).

  • 2.0

    • New Imap component and ImapMail namespace.
    • Secure SSL/TLS connections for Pop3, Imap, and Smtp components, and new Security namespace.
    • Windows Intergrated mode of NTLM authentication allows the client to authenticate with the credentials of the currently logged Windows user.
    • Smtp.SubmitToQueue method can send messages to IIS SMTP queue.
    • New overloads for SmtpServerCollection.Add method and SmtpServer() constructor make it easier to specify the authentication method to use.
    • Attachment.GetAttachmentsFromTnef method can extract attachments from MS-TNEF (winmail.dat) files.
    • MimePart.Parse method and Attachment(MimePart) constructor allow creation MIME parts and attachments from MIME data (useful for downloading and processing the specific message attachments via the IMAP4 protocol).
    • MailMessage.UidOnServer and MessageParserConfig.DatesAsUtc new properties.
    • Logger.DisableOnException property allows the application to silently disable logging instead of throwing exception if the log file cannot be created or written to.
    • Most features (except SSL/TLS and Windows Intergrated NTLM authentication) can now be used in web applications running on "High" trust level. To use, SSL/TLS and Windows Intergrated NTLM authentication, "Full" trust level or "High" trust level plus Unmanaged code permission is required. However, this is not a concern if MailBee.NET.dll is in GAC (see below).
    • MailBee.NET Objects installation program now also puts MailBee.NET.dll into GAC (this enables TLS/SSL and Windows Integrated authentication support even in applications running on trust level lower than "Full").
    • Ability to store the license key in Windows registry (this eliminates the need to specify the license key in config files or set it via LicenseKey property of the corresponding component). SaveKey (console application) and SaveKeyGui (WinForms wrapper of SaveKey) are installed into MailBee.NET Objects folder.
    • More informative exception messages.
    • Improved parsing of mail messages (including support of UUEncode and non-MIME messages having attachments embedded directly in the text body).
    • Improved HTML to plain-text conversion.
    • Miscellaneous minor bug fixes.
    • Improvements and bug fixes of the documentation.
    • The VS.NET 2003 and VS.NET 2005 versions of the documentation in HtmlHelp2 format is now available (as a separate download). The HtmlHelp2 documentation fully integrates with Visual Studio, supports Dynamic Help, etc.
    • A number of the sample application projects in VS.NET 2003 format (VS.NET 2005 compatible) is now installed with the product.

  • 1.0

    • The initial release.

Send feedback to AfterLogic


MailBee.NET Objects Developer's Guide

The articles in this section can be your starting point on the way of mail-enabling your application.

Create and send e-mails with SMTP component guide is a comprehensive source of the information on how you can create and send e-mail messages, verify a single e-mail address, make DNS queries, send custom SMTP commands, along with general features like logging, async programming, using in a web application, troubleshooting, and so on.

Verify e-mail addresses with Address Validator guide contains a number of samples along with technical details on how to verify a bulk of e-mail addresses for correct syntax or existence, how to deal with greylisting and temporary failures to avoid false positives or negatives, how to make multiple attempts for better accuracy, and covers some unobvious aspects of multi-threaded address verification.

Getting started with IMAP and POP3 components guide is a quick tour of the e-mail retrieval and parsing features of MailBee.NET Objects. Soon, this guide will be extended with additional articles and samples.

Getting started with Outlook Converter guide provides a brief walk-through of MailBee.NET classes which allow creating and parsing Outlook .MSG messages and Outlook .PST data files without having Outlook installed. It also highlights how to import messages from Outlook using its API or extract messages from there.

iCal and vCard calendars and contacts guide shows how to deal with .VCF files in vCard format and how to use iCal events, including meeting requests, reminders, recurring events, and so on.

OAuth 2.0 in Windows, .NET Core, and ASP.NET MVC apps guide explains how to develop a Windows installed app or ASP.NET MVC app which can check or send e-mail via IMAP/SMTP using OAuth 2.0 authentication. All the samples have been tested with Google and Microsoft services like Gmail and Outlook.com. Google Apps Service accounts are also supported.

Send feedback to AfterLogic


Create and send e-mails with MailBee.NET SMTP component

Here you can find the detailed developer guides on how to create and send e-mail messages with SMTP component of MailBee.NET family.

This section also describes the related tasks like how to verify an e-mail address, make DNS queries, send custom SMTP commands, along with general features like logging, async programming, using in a web application, troubleshooting, and so on.

Getting started guide is a quick tour of the features and usage samples. In particular, its Feature map topic allows you to quickly find the feature you're looking for.

Other guides provide more detailed and comprehensive information and code samples on the particular features.

  • Getting started with SMTP component
    • Introduction
    • Feature map as compared with System.Net.Mail.SmtpClient
    • Import namespaces and set license key
    • Send e-mail in a single line of code
    • Send e-mail to SMTP relay server
    • Send HTML e-mail with attachment
    • Send e-mail with Reply-To and multiple To, CC and BCC recipients
    • Send if server requires SMTP authentication
    • Send if server requires SSL (like Gmail)
    • Send e-mail directly without SMTP relay server
    • Verify e-mail address without sending actual e-mail
    • Exceptions and errors
    • MS Exchange SMTP issues
    • Log file of SMTP conversation
    • Troubleshoot common sending errors and non-delivery
  • Send from ASP.NET web application
    • Requirements and limitations
    • Send simple e-mail in ASP.NET
    • Send e-mail with attachment uploaded from client
  • Compose complex e-mail with multiple parts and attachments
    • Send e-mail with separate HTML and plain-text parts
    • Send e-mail with HTML part and auto-generated plain-text part
    • Send e-mail with attachments from file, stream, memory, another message
    • Send HTML e-mail with embedded pictures
    • Send e-mail created from web page content
    • Create HTML in memory and automatically embed linked resources
    • Create HTML in memory and manually embed linked resources
  • Compose e-mail created from another object or file
    • Send e-mail created from System.Net.Mail.MailMessage
    • Send e-mail created from memory
    • Send e-mail created from file
    • Send e-mail created from serialized XML
    • Send e-mail created from Outlook .MSG message
  • Compose international e-mail
    • Charsets, code pages, encodings, and UTF-8
    • Content-transfer encodings
    • UTF-8 or local language-specific charset?
    • HTML META tag with charset declaration
    • HTML-encoded international characters ("&#xxxx;" sequences)
    • Send plain-text e-mail with Chinese content and "utf-8" or "gb2312" charset
    • Send plain-text e-mail with Windows-1252 headers (German characters in From, Subject, To)
    • Send HTML e-mail with international characters
    • Compose e-mail in right-to-left language like Hebrew
    • Send e-mail with international characters in headers, body, attachment filenames
  • Set From, Reply-To, Return-Path, To, CC, BCC, Priority and other headers in e-mail
    • Introduction
    • Set different From and Return-Path (use "real" sender address different from "From" address)
    • Send to undisclosed recipients (use "real" recipient addresses different from "To", "CC", "BCC" addresses)
    • Set "Request delivery confirmation" and "Request read confirmation" flags
    • Set Reply-To
    • Reply to message and set In-Reply-To and References headers
    • Set Importance, Priority, Sensitivity flags
    • Set custom Date and Message-ID values
    • Add custom headers
  • Mail merge and bulk mail
    • Mail merge in MailBee.NET
    • Bulk mail, explained
    • Error processing in bulk mail operations
    • Send series of e-mails based on template and database
    • Mail merge with post processing
    • Monitor mail merge progress and track successful and failed sendings
    • Submit e-mails generated with mail merge to MailBee.NET Queue
  • Request delivery and reading confirmation
    • Comparison of various methods of requesting delivery and reading confirmations
    • Request delivery and reading confirmation via message headers
    • Request delivery status notification with ESMTP DSN
    • Use ESMTP DSN and message headers together
    • ESMTP DSN in detail
    • Fine-tune ESMTP DSN and assign Tracking ID to e-mail
  • Adjust e-mail to let it pass through spam filters
    • Sign e-mail with DomainKeys and DKIM
    • General suggestions
  • Sign and encrypt e-mail with S/MIME
    • Introduction
    • Sign e-mail with S/MIME to prove authenticity of sender
    • Sign and encrypt e-mail with S/MIME to ensure privacy and security
  • Accepted and refused recipients
    • Introduction
    • Allow or disallow refused (failed) recipients
    • Get successful and failed recipients after sending e-mail
    • Use events to track successful and failed recipients during sending e-mail
  • Direct send without SMTP relay server
    • Send with SMTP relay server, explained
    • Direct send via DNS MX lookup, explained
    • Set DNS servers in code, via auto-detection, or in config file
    • Direct send example
    • Set appropriate Hello message to pass reverse DNS check
    • Direct send vs normal send
    • Validate e-mail address via syntax check and DNS MX lookup
  • Filter spam with DNS queries (MX, SPF, DKIM, reverse DNS)
    • Introduction
    • Get DNS MX records
    • Get SPF or DKIM ADSP records with DNS TXT query
    • Get reverse DNS records with DNS PTR query
    • Use rDNS to check if sender's IP address matches HELO domain
    • Use rDNS query to find out if sender is home computer or Internet server
  • Send multiple individual e-mails or send through multiple servers
    • Introduction
    • Send two e-mails in single session
    • Send two e-mails in single session via SSL or STARTTLS
    • Send bulk e-mail through two SMTP relay servers for increased throughput
    • Send through main SMTP relay server or through fail-over SMTP relay server if main server is down
    • Send through SMTP relay server or use direct send if SMTP relay server is down
    • Submit to MailBee.NET Queue for increased or limited throughput
    • Throttle throughput (limit sending rate)
    • Performance optimization
  • SMTP over SSL (Gmail.com, Live.com, certificates)
    • Features supported
    • Auto-detect SSL settings based on the port and host
    • Connect to dedicated SSL port
    • Connect to regular port and use STARTTLS to activate SSL
    • Advanced STARTTLS
    • Configure SSL protocol (Auto, SSL, TLS)
    • Supply client certificate and check server certificate
    • Validate server certificate selectively
    • Validate server certificate without throwing exception
  • SMTP authentication in detail
    • SMTP authentication explained
    • POP-before-SMTP or ESMTP?
    • Authenticate with POP-before-SMTP
    • ESMTP authentication in more detail
    • Secure authentication
    • Use Integrated Windows Authentication (no username and password required)
    • Use OAuth 2.0 with Gmail, Outlook.com, Live.com or Hotmail.com
    • Fine-tune SMTP authentication process
    • Create your own authentication method
  • Advanced SMTP connections (proxy, extensions, custom hello, commands and ports)
    • Connect via proxy server (SOCKS4, SOCKS5, HTTP)
    • Connect to non-standard SMTP port
    • Set local end point in case of multiple network adapters or firewall
    • Send custom Hello message to server
    • Examine supported ESMTP extensions
    • Disable conflicting ESMTP extensions
    • Send custom command to server
  • SMTP with filesystem, POP3, IMAP (forward from POP3, send to SMTP and IMAP)
    • Introduction
    • Load e-mail from file and send it
    • Send e-mail and save it to Sent Items on IMAP server
    • Send e-mail and save it to file stream
    • Receive e-mail with POP3, forward it as attachment of another e-mail and send with SMTP
    • Receive e-mail with IMAP, reply to it and send via SMTP
  • Use events to control MailBee.NET execution and monitor SMTP activities
    • Introduction
    • Monitor progress of SMTP session with events
    • Change e-mail message during sending
    • Cancel sending process
  • Handle exceptions and errors
    • Introduction
    • Error codes and localization of error messages
    • Connection-level and protocol-level exceptions
    • Final errors, warnings, and ErrorOccurred event
    • Exceptions and async methods
    • TestSend example
  • Asynchronous methods of Smtp class
    • Introduction
    • Send single e-mail asynchronously
    • Send multiple e-mails asynchronously
  • Log files and memory logs in detail
    • Logger settings and options
    • Synchronize access to log file of multiple instances of Smtp class
    • LogNewEntry event

Send feedback to AfterLogic


Getting started with SMTP component

  • Introduction
  • Feature map as compared with System.Net.Mail.SmtpClient
  • Import namespaces and set license key
  • Send e-mail in a single line of code
  • Send e-mail to SMTP relay server
  • Send HTML e-mail with attachment
  • Send e-mail with Reply-To and multiple To, CC and BCC recipients
  • Send if server requires SMTP authentication
  • Send if server requires SSL
  • Send to e-mail address with international domain (IDN)
  • Send e-mail directly without SMTP relay server
  • Verify e-mail address without sending actual e-mail
  • Exceptions and errors
  • MS Exchange SMTP issues
  • Log file of SMTP conversation
  • Troubleshoot common sending errors and non-delivery

Introduction

To create and send e-mails, you can use MailBee.NET SMTP component. That's how it happens:

  • You set the message properties like To/From/Subject headers and the body text, add attachments, etc.
  • SMTP component creates MIME representation of the e-mail. MIME (RFC2822) is the standard format for e-mail interchange in the Internet and between applications.
  • SMTP component sends the MIME data to your relay server using SMTP data transfer protocol. The relay server then should deliver the message to its intended recipients.

There are lots of other options, however. Just to name a few:

  • Load the message to be sent from another source (like an XML file or memory).
  • Use the classes of MIME component to build complex e-mails.
  • Use mail merge over database to produce and send a series of e-mails based on a common template.
  • Submit the resulting e-mail to an e-mail pickup service for background delivery, or send directly to intended recipients without an SMTP relay server.
  • Upload the e-mail to an IMAP server, save it into a file or memory (not using SMTP component at all).

In the diagram below, you can find what you can feed to MailBee.NET classes on input and which options you have in order to save or send the resulting e-mail.

You can also enable various options and apply a number of transformations to the message being composed. For instance:

  • Automatically attach images referenced in the HTML body and generate its plain-text version.
  • Sign the message with DKIM and DomainKeys.
  • Encrypt and sign the message with S/MIME.
  • Request the delivery confirmation.

Now, let's assume the message has been composed and you're about to send it through your SMTP relay server (the most common scenario). A few tips here:

  • You can track the operation progress with events.
  • You can enable logging SMTP session into a file for troubleshooting or other purposes.
  • You may need to unblock SMTP port on MailBee.NET machine or use alternate port (for instance, port 25 is often blocked while port 587 is not and many SMTP servers listen to that port as well).
  • For SMTP servers which require authentication or SSL connection, you can enable any of these options.

Once the message has been successfully sent to the SMTP server, MailBee.NET's job is over. This, however, does not guarantee the intended recipient has received the message. The recipient's server may seem to accept the message but then bounce it back, put it into Spam folder or just delete it silently. You can learn more in Troubleshoot common sending errors and non-delivery section if you face such issues.

Feature map as compared with System.Net.Mail.SmtpClient

.NET Framework provides System.Net.Mail classes which can be used to send e-mails to SMTP servers.

The below are comparison tables of MailBee.NET and System.Net.Mail features related to creating and sending e-mails. They also provide quick access to the documentation on all the features.

SMTP protocol and e-mail delivery | MailBee | System
Send to SMTP relay server more | + | +
Send to SMTP relay via SSL (dedicated SSL port) more | + | +
Client and server SSL certificates more | + | +
Send to SMTP relay via STARTTLS (SSL over regular port) more | + |
Send to SMTP relay on non-standard ports more | + | +
Send directly (without SMTP relay) more | + |
Send through multiple servers for increased throughput more | + |
Fail-over relay servers and fail-over "direct send" mode more | + |
Throttle SMTP connection to stay within established limits more | + |
Send to queue (e.g. IIS SMTP Pickup service) more | + | +
Upload to IMAP server (e.g. into Sent Messages folder) more | + |
Re-send (forward, reply) e-mail received via POP3 or IMAP more | + |
Validate e-mail address (syntax, DNS, test connection) more | + |
Custom SMTP commands more | + |
DNS queries (MX, TXT/SPF, TXT/DKIM, reverse DNS) more | + |
ESMTP authentication (basic) more | + | +
ESMTP authentication (NTLM, Integrated Windows) more | + | +
ESMTP authentication (CRAM-MD5, GSSAPI, OAuth) more | + |
POP-before-SMTP authentication more | + |
Connection via proxy (SOCKS4, SOCKS5, HTTP) more | + |
Exceptions and error codes more | + | +
Monitor progress with events more | + |
File and memory logging of SMTP session more | + |
Can be used in web (ASP.NET), desktop and console applications more | + | +
Async methods | + | +

With regard to creating e-mails, MailBee.NET provides more features such as automatic importing of embedded pictures in HTML content, security facilities like S/MIME and DKIM, mail merge.

Creating e-mails | MailBee | System
Plain-text and HTML e-mails with alternate views more | + | +
Auto-provision plain-text view for HTML content more | + |
Attachments from files or memory more | + | +
Attachment from existing e-mail (forward e-mail as attachment) more | + |
Linked resources (e.g. embedded images) more | + | +
Auto-embed linked resources more | + |
Get HTML body (and linked resources) from web page more | + |
Message from XML (deserialize XML into e-mail) more | + |
Message from MIME data (e.g. relay e-mail from disk) more | + |
Create any custom header more | + | +
To, CC, BCC, From, ReplyTo more | + | +
Priority more | + | +
Importance, Sensitivity more | + |
Request reading confirmation (read receipt) more | + |
International e-mails, encodings, UTF-8 more | + | +
Access to generated MIME data more | + |
Request delivery confirmation more | + | +
Assign tracking ID for delivery confirmation more | + |
Mail merge more | + |
DKIM and DomainKeys signature more | + |
S/MIME encrypted and signed e-mail more | + |

Besides that, MailBee.NET gives you much more control how e-mails are generated, how SMTP connection is established, how to react if certain recipients were rejected by the server, and so on.

With MailBee.NET events, you can not only monitor the operation progress (being a passive observer), but also actively interfere into the execution. For instance, you can alter the message which is about to be sent, or cancel sending a particular message in mail merge series, and so on.

MailBee.NET exception model is far more developed in comparison to System.Net.Mail so that you can programmatically respond to many specific errors accordingly their nature. For instance, it's not easily possible to distinguish between "bad login or password" and "bad sender's e-mail address" errors with System.Net.Mail while MailBee.NET provides separate exceptions for them.

However, whether to use MailBee.NET or System.Net.Mail is not "either-or" question. MailBee.NET can work together with System.Net.Mail to let you make the transition process smoother.

For instance, you can export System.Net.Mail.MailMessage into MailBee.Mime.MailMessage and then send the resulting e-mail with MailBee.NET SMTP component. The rest of your code which composes e-mails with the help of System.Net.Mail remains intact. See Send e-mail created from System.Net.Mail.MailMessage topic for details.

The opposite scenario (export MailBee.Mime.MailMessage into System.Net.Mail.MailMessage) is also supported.

Import namespaces and set license key

Reference MailBee.NET.dll

To start using MailBee.NET in your projects, add MailBee.NET Objects reference to your project. You can use NuGet Packager Manager console for that:

Install-Package MailBee.NET

If NuGet is not an option (for instance, you have older version of Visual Studio), see below.

In Project menu, click Add a reference:

Then, under .NET tab, locate MailBee.NET Objects. If you installed multiple versions of MailBee.NET Objects, select v2.0 in Runtime column if you're using .NET 2.0/3.5. If you're using .NET v4.5 or higher, select v4.0 Runtime:

In newer versions of Visual Studio, Runtime column is not there and path to the dll is not shown by default so you may need to hover mouse cursor over to see the path (and determine the version). In this case, it's .NET 4.5 version of MailBee.NET.dll:

Click OK to add the reference to your project. MailBee.NET entry should appear in References list of your project.

Import MailBee.NET namespaces

Now, import MailBee.NET namespaces to the beginning of your source code files where you'll use MailBee.NET.

When creating and sending e-mails, you'll typically need some of these namespaces:

  • C#
  • VB
using MailBee;
using MailBee.Mime;
using MailBee.Security;
using MailBee.SmtpMail;

Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security
Imports MailBee.SmtpMail

If you're using direct send mode (without an SMTP relay server) or your code interoperates with Imap or Pop3 components, you may also need to import these namespaces as well:

  • C#
  • VB
using MailBee.DnsMX;
using MailBee.Pop3Mail;
using MailBee.ImapMail;

Imports MailBee.DnsMX
Imports MailBee.Pop3Mail
Imports MailBee.ImapMail

Obtain license key

Now, you need to specify your trial or permanent MailBee.NET license key to unlock the product. If you do not yet have a key, you can generate the trial key with "Get a Trial Key" utility (available in Programs / MailBee.NET Objects menu).

You can specify the key in a number of ways (Windows registry, app.config or web.config file, directly in the code). This guide shows two methods of that: hard-coded key and key stored in app.config (web.config for ASP.NET).

Using Windows registry is not recommended as your application may be lacking permission to access the required registry branches. If you still need to use the registry (e.g. if your application is distributed with the source code so that you cannot embed the key there), refer to Using License Keys topic in MailBee.NET Objects documentation for details.

Option A - specify license key directly in code

Before the first use and creating any instances of Smtp class, set the static MailBee.Global.LicenseKey property to assign the license key. It's assumed you've already imported MailBee.SmtpMail namespace with using (C#) or Imports (VB) directives.

  • C#
  • VB
MailBee.Global.LicenseKey = "MN100-0123456789ABCDEF-0123";

MailBee.Global.LicenseKey = "MN100-0123456789ABCDEF-0123"

You can also create and unlock instances of Smtp class, passing the license key as a parameter of Smtp(string) constructor. Again, it's assumed you've already imported MailBee.SmtpMail namespace.

  • C#
  • VB
Smtp mailer = new Smtp("MN100-0123456789ABCDEF-0123");

Dim mailer As New Smtp("MN100-0123456789ABCDEF-0123")

Option B - put license key in app.config or web.config

Alternatively, you can add app.config to your project (if you do not already have it there) and specify MailBee.NET SMTP license key there.

For ASP.NET application, web.config is always available so that you can immediately edit it, but for other application types you may have to add app.config manually.

The below we are using Visual Studio 2008 but it's all the same with newer Visual Studio versions as well. For instance, we are using Visual Studio 2010 in similar topic in IMAP and POP3 guide.

In Projects menu, click Add New Item:

Select Application Configuration File and click Add:

In app.config or web.config, locate <appSettings> entry in <configuration> section (if it's not there, create it), and add MailBee.NET license key as follows:

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <appSettings>
      <add key="MailBee.Global.LicenseKey" value="MN100-0123456789ABCDEF-0123"/>
  </appSettings>
</configuration>

Note that <appSettings> may also appear as <applicationSettings> in your case.

If <appSettings> originally looked as <appSettings/> (self-closing tag syntax), you'll need to unfold it to <appSettings></appSettings> so that you could insert <add key .../> there.

You can also specify the key in machine.config file. This will enable access to the license key to all applications on the computer so that there will be no need to specify the license key in each application separately. For instance, this is the preferred way if you a hosting provider willing to let your hosting clients create and run applications which use MailBee.NET without disclosing your license key to them.

Send e-mail in a single line of code

We'll send a simple plain-text e-mail using the static (Shared in VB) Smtp.QuickSend method. No need to create an instance of Smtp class for that:

  • C#
  • VB
Smtp.QuickSend("john@domain.com", "jane@company.com", "Question", "How are you?");

Smtp.QuickSend("john@domain.com", "jane@company.com", "Question", "How are you?")

Here and below, we assume that MailBee.SmtpMail namespace is already imported and MailBee.Global.LicenseKey is specified (in the code or in app.config or web.config file).

E-mail addresses can contain display names, and you can specify multiple recipients (comma-separated):

  • C#
  • VB
Smtp.QuickSend("John Doe <john@domain.com>",
    "Jane Doe <jane@company.com>, noname@example.com", "Question", "How are you?");

Smtp.QuickSend("John Doe <john@domain.com>", _
    "Jane Doe <jane@company.com>, noname@example.com", "Question", "How are you?"

Other overloads of Smtp.QuickSend method allow you to send HTML e-mails with attachments or user-supplied MailMessage objects, all with a single line of code.

If Smtp.QuickSend method fails, it throws MailBeeException which you can catch and analyze in your code. If the method succeeds, this means the message has reached the end recipient's server.

Smtp.QuickSend sends e-mails via DNS MX lookup, not using any SMTP relay server (so-called "direct send" mode). This mode has some limitations described in Send e-mail directly without SMTP relay server topic. Also, because no instance of Smtp object is created, you cannot configure anything or check the log file in case if trouble-shooting needed, etc.

Send e-mail to SMTP relay server

Now let's create an instance of Smtp class and send a simple plain-text e-mail via an SMTP relay server:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.here.com");
mailer.From.AsString = "John Doe <john.doe@here.com>";
mailer.To.AsString = "Jane Doe <jane.doe@there.com>";
mailer.Subject = "Meeting request";
mailer.BodyPlainText = "Can we meet today?";
mailer.Send();

Dim mailer As Smtp = New Smtp()
mailer.SmtpServers.Add("mail.here.com")
mailer.From.AsString = "John Doe <john.doe@here.com>"
mailer.To.AsString = "Jane Doe <jane.doe@there.com>"
mailer.Subject = "Meeting request"
mailer.BodyPlainText = "Can we meet today?"
mailer.Send()

mail.here.com is the host name of your SMTP relay server.

No SMTP authentication is used in this sample (anonymous mode). See Send if server requires SMTP authentication topic on how to enable authentication if required.

If Smtp.Send method still throws an exception, you may need to fine-tune SMTP authentication, enable SSL, or open SMTP ports in the firewall. See Send if server requires SSL (like Gmail), MS Exchange SMTP issues or Troubleshoot common sending errors and non-delivery topics for details.

Send HTML e-mail with attachment

This sample sends an HTML e-mail with attachment (MailBee.NET will also auto-generate the plain-text version of the supplied HTML). The e-mail is sent through an SMTP relay server without authentication:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.here.com");
mailer.From.AsString = "John Doe <john.doe@here.com>";
mailer.To.AsString = "Jane Doe <jane.doe@there.com>";
mailer.Subject = "Meeting request";
mailer.BodyHtmlText = "<html><body>Can we meet today?</body></html>";
mailer.AddAttachment(@"C:\Temp\details.doc");
mailer.Send();

Dim mailer As Smtp = New Smtp()
mailer.SmtpServers.Add("mail.here.com")
mailer.From.AsString = "John Doe <john.doe@here.com>"
mailer.To.AsString = "Jane Doe <jane.doe@there.com>"
mailer.Subject = "Meeting request"
mailer.BodyHtmlText = "<html><body>Can we meet today?</body></html>"
mailer.AddAttachment("C:\Temp\details.doc")
mailer.Send()

If you need more advanced features or control over building HTML e-mails or attaching files, see Compose complex e-mail with multiple parts and attachments guide.

Send e-mail with Reply-To and multiple To, CC and BCC recipients

Smtp object itself provides a very limited set of e-mail message properties, and Reply-To, CC or BCC headers are not available there. This is because Smtp object is for sending e-mails, not for creating them. The object responsible for creating e-mails is MailMessage of MailBee.Mime namespace. It assembles the message properties into the MIME data which can then be transmitted to the SMTP server.

Smtp object has Smtp.Message property which references the MailMessage object to be sent. For instance, Smtp.Subject is just a shorter form of Smtp.Message.Subject, and Smtp.AddAttachment is a shorter form of Smtp.Message.Attachments.Add.

The code below demonstrates how to set From, Reply-To, To, CC, BCC in different ways:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.here.com");

// Set From address as a single string.
mailer.Message.From.AsString = "John Doe <john.doe@here.com>";

// Add 1st Reply-To address.
mailer.Message.ReplyTo.AddFromString("John Doe <jdoe@here.com>");

// Add 2nd Reply-To address (no display name).
mailer.Message.ReplyTo.Add("noname@here.com");

// Specify "To" as a single string containing 2 e-mail addresses.
mailer.Message.To.AsString = "Jane Doe <jane.doe@there.com>, Alice <alice@there.com>";

 // Add 3rd and 4th "To" addresses.
mailer.Message.To.AddFromString("mike@nodisplayname.com, Liz <liz@somewhere.com>");

// Specify 2 "CC" addresses separately, with different syntax.
mailer.Message.Cc.AddFromString("Bob Smith <bob@example.com>");
mailer.Message.Cc.Add("john.doe@here.com", "John Doe");

// Specify BCC (no need to supply display name as BCC header will be removed anyway).
mailer.Message.Bcc.Add("boss@here.com");
mailer.Message.Subject = "Meeting request";
mailer.Message.BodyHtmlText = "<html><body>Can we meet today?</body></html>";

mailer.Message.Attachments.Add(@"C:\Temp\details.doc");
mailer.Send();

Dim mailer As Smtp = New Smtp()
mailer.SmtpServers.Add("mail.here.com")

' Set From address as a single string.
mailer.Message.From.AsString = "John Doe <john.doe@here.com>"

' Add 1st Reply-To address.
mailer.Message.ReplyTo.AddFromString("John Doe <jdoe@here.com>")

' Add 2nd Reply-To address (no display name).
mailer.Message.ReplyTo.Add("noname@here.com")

' Specify "To" as a single string containing 2 e-mail addresses.
mailer.Message.To.AsString = "Jane Doe <jane.doe@there.com>, Alice <alice@there.com>"

' Add 3rd and 4th "To" addresses.
mailer.Message.To.AddFromString("mike@nodisplayname.com, Liz <liz@somewhere.com>")

' Specify 2 "CC" addresses separately, with different syntax.
mailer.Message.Cc.AddFromString("Bob Smith <bob@example.com>")
mailer.Message.Cc.Add("john.doe@here.com", "John Doe")

' Specify BCC (no need to supply display name as BCC header will be removed anyway).
mailer.Message.Bcc.Add("boss@here.com")

mailer.Message.Subject = "Meeting request"
mailer.Message.BodyHtmlText = "<html><body>Can we meet today?</body></html>"
mailer.Message.Attachments.Add("C:\Temp\details.doc")

In other words, it's possible to specify e-mail addresses in many ways so that you can always choose the most convenient method for you (and even combine different methods).

To learn more on setting e-mail headers, refer to Set From, Reply-To, Return-Path, To, CC, BCC, Priority and other headers in e-mail guide.

Send if server requires SMTP authentication

Most SMTP servers require clients to authenticate themselves in order to relay e-mails to external domains. In most cases, you just need to set your SMTP username and password in addition to the SMTP relay host name:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.domain.com", "username", "password");

Dim mailer As Smtp = New Smtp()
mailer.SmtpServers.Add("mail.domain.com", "username", "password")

The above enables MailBee.NET to perform ESMTP authentication before sending the e-mail. Note that some servers might require you to use your full e-mail address (username@domain.com or even domain.com\username), not just username.

If your SMTP server requires another sort of authentication (like POP-before-SMTP) or you would like to learn more, refer to SMTP authentication in detail guide.

Send if server requires SSL

Most SMTP relay servers nowadays require clients to establish secure SSL connection with the server. MailBee.NET can automatically enable SSL mode for some popular e-mail services (like Gmail) but in general case you should specify SSL settings manually.

Usually, SMTP-over-SSL port is 465 (while the regular SMTP port is 25). If you specify port 465 for SMTP server, MailBee.NET will automatically enable SSL mode for it:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.domain.com", "username", "password").Port = 465;

Dim mailer As Smtp = New Smtp()
mailer.SmtpServers.Add("mail.domain.com", "username", "password").Port = 465

By default, MailBee.NET uses the most secure SSL protocol supported by the server (usually, TLS).

You can also explicitly specify SSL mode for any port and set other parameters. To learn more on SMTP-over-SSL configuration, refer to SMTP over SSL (Gmail.com, Live.com, certificates) guide.

Send to e-mail address with international domain (IDN)

You can use EmailAddress.ToIdnAddress, EmailAddressCollection.ToIdnAddress or EmailAddress.EscapeIdnDomain methods to convert domain part of a e-mail address, a collection of addresses or any e-mail string into Punycode format. This translates international domain names to ASCII. You can safely IDN-ize normal Latin e-mail addresses as well, they will be left intact.

  • C#
  • VB
// Add IDN-ized email to To list.
mailer.To.Add(new EmailAddress("user@international.domain").ToIdnAddress());

// IDN-ize already existing To list.
mailer.To.AsString = "user@international.domain";
mailer.To = mailer.To.ToIdnAddress();

// IDN-ize From.
mailer.From = new EmailAddress("user@international.domain").ToIdnAddress();

// IDN-ize any string.
mailer.Message.Headers["Some custom header"] = EmailAddress.EscapeIdnDomain("user@international.domain");

' Add IDN-ized email to To list.
mailer.To.Add(New EmailAddress("user@international.domain").ToIdnAddress())

' IDN-ize already existing To list.
mailer.To.AsString = "user@international.domain"
mailer.To = mailer.To.ToIdnAddress()

' IDN-ize From.
mailer.From = New EmailAddress("user@international.domain").ToIdnAddress()

' IDN-ize any string.
mailer.Message.Headers("Some custom header") = EmailAddress.EscapeIdnDomain("user@international.domain")

Account part of e-mail address is not touched. IDN is about domains, not account names. To send to international local names, domain IDN-ize is not enough, you also need to encode e-mail addresses' local parts into UTF-8. To achieve that, you can just tell MailBee to encode all requests it sends to the server in UTF-8 rather than in system's default encoding:

  • C#
  • VB
mailer.RequestEncoding = System.Text.Encoding.UTF8;
mailer.Send();

mailer.RequestEncoding = System.Text.Encoding.UTF8
mailer.Send()

Send e-mail directly without SMTP relay server

To send without any SMTP relay server with a single of code and without creating an instance of Smtp class, you can use Smtp.QuickSend method. See Send e-mail in a single line of code topic for examples.

The below is a typical example of sending an e-mail without SMTP relay:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.DnsServers.Autodetect();
mailer.From.Email = "joe@domain.com";
mailer.To.Add("mike@company.com");
mailer.Subject = "Test message";
mailer.BodyPlainText = "Just a test";
mailer.Send();

Dim mailer As Smtp = New Smtp()
mailer.DnsServers.Autodetect()
mailer.From.Email = "joe@domain.com"
mailer.To.Add("mike@company.com")
mailer.Subject = "Test message"
mailer.BodyPlainText = "Just a test"
mailer.Send()

Note that direct send has a number of limitations in comparison with normal send through SMTP relay server. To learn more, refer to Direct send without SMTP relay server guide.

Verify e-mail address without sending actual e-mail

To check if an e-mail address is valid, you can use Smtp.ValidateEmailAddressSyntax and Smtp.TestSend methods:

To check bulk of addresses, consider using EmailAddressValidator component.

  • C#
  • VB
Smtp mailer = new Smtp();

// Get ready for DNS MX lookup.
mailer.DnsServers.Autodetect();

// Set sender and recipient.
mailer.From.Email = "j.doe@domain.com";
mailer.To.Add("lisa@company.com");

// Validate the e-mail address syntax.
Console.WriteLine(
    Smtp.ValidateEmailAddressSyntax("lisa@company.com").ToString());

// Verify the e-mail address.
Console.WriteLine(
    mailer.TestSend(SendFailureThreshold.AnyRecipientsFailed).ToString());

Dim mailer As New Smtp()

' Get ready for DNS MX lookup.
mailer.DnsServers.Autodetect()

' Set sender and recipient.
mailer.From.Email = "j.doe@domain.com"
mailer.To.Add("lisa@company.com")

// Validate the e-mail address syntax.
Console.WriteLine( _
    Smtp.ValidateEmailAddressSyntax("lisa@company.com").ToString())

' Verify the e-mail address.
Console.WriteLine( _
    mailer.TestSend(SendFailureThreshold.AnyRecipientsFailed).ToString())

Refer to Validate e-mail address via syntax check and DNS MX lookup topic for the more advanced sample, and other notes.

Exceptions and errors

The sample below sends an e-mail message and saves it into a file upon sending. All "expected" exceptions are caught. "Expected" are those like SMTP and file I/O errors. However, we don't catch license key errors (although you can do this if you need to). The exception handling is structured, we use different handlers for different exceptions and fall back to the general MailBeeException if nothing more special found:

  • C#
  • VB
Smtp mailer = new Smtp();

mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret");

mailer.Message.From.AsString = "Joe D. <joe@here.com>";
mailer.Message.To.AsString = "Carl S. <carl@there.com>";
mailer.Message.Subject = "Greetings from Joe";
mailer.Message.BodyPlainText = "Hi there!";

bool sent = false;

try
{
    mailer.Send();
    sent = true;
    Console.WriteLine("Sent successfully");
}
catch (MailBeeSmtpNegativeResponseException e)
{
    Console.WriteLine("Exception message: " + e.Message);
    Console.WriteLine();
    Console.WriteLine("MailBee.NET error code: " + e.ErrorCode.ToString());
    Console.WriteLine();
    Console.WriteLine("SMTP response code: " + e.ResponseCode.ToString());
    Console.WriteLine();
    Console.WriteLine("SMTP reply: " + e.ResponseString);
    Console.WriteLine();
    Console.WriteLine("Server IP: " + e.RemoteEndPoint.Address.ToString());
}
catch (MailBeeException e)
{
    Console.WriteLine("Exception: " + e.ToString());
    Console.WriteLine();
    Console.WriteLine("Exception message: " + e.Message);
}

if (sent)
{
    try
    {
        mailer.Message.SaveMessage("C:\Temp\message.eml");

        Console.WriteLine("Sent successfully");
    }
    catch (MailBeeIOException e)
    {
        Console.WriteLine("Exception message: " + e.Message);
        Console.WriteLine();
        Console.WriteLine("MailBee.NET error code: " + e.ErrorCode.ToString());
        Console.WriteLine();
        Console.WriteLine("InnerException: " + e.InnerException.ToString());
    }
}

Dim mailer As New Smtp()

mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret")

mailer.Message.From.AsString = "Joe D. <joe@here.com>"
mailer.Message.To.AsString = "Carl S. <carl@there.com>"
mailer.Message.Subject = "Greetings from Joe"
mailer.Message.BodyPlainText = "Hi there!"

Dim sent As Boolean = False

Try
    mailer.Send()
    sent = True
    Console.WriteLine("Sent successfully")
Catch e As MailBeeSmtpNegativeResponseException
    Console.WriteLine("Exception message: " & e.Message)
    Console.WriteLine()
    Console.WriteLine("MailBee.NET error code: " & e.ErrorCode.ToString())
    Console.WriteLine()
    Console.WriteLine("SMTP response code: " & e.ResponseCode.ToString())
    Console.WriteLine()
    Console.WriteLine(("SMTP reply: " & e.ResponseString))
    Console.WriteLine()
    Console.WriteLine("Server IP: " & e.RemoteEndPoint.Address.ToString())
Catch e As MailBeeException
    Console.WriteLine(("Exception: " & e.ToString()))
    Console.WriteLine()
    Console.WriteLine(("Exception message: " & e.Message))
End Try

If sent Then
    Try
        mailer.Message.SaveMessage("C:\Temp\message.eml")

        Console.WriteLine("Sent successfully")
    Catch e As MailBeeIOException
        Console.WriteLine(("Exception message: " & e.Message))
        Console.WriteLine()
        Console.WriteLine("MailBee.NET error code: " & e.ErrorCode.ToString())
        Console.WriteLine()
        Console.WriteLine("InnerException: " & e.InnerException.ToString())
    End Try
End If

The special case is asynchronous methods. If the method which executes on a worker thread throws an unhandled exception, the thread silently dies and the application never knows what happened. Always catch all exceptions in worker threads and analyze them.

For more details on processing errors and exceptions in MailBee.NET, refer to Handle exceptions and errors guide.

MS Exchange SMTP issues

When your SMTP relay server is MS Exchange, keep in mind the following facts:

  1. MS Exchange by default does not even run SMTP service. Make sure it's started.
  2. Often, SMTP service operates on SSL ports only. If so, refer to Send if server requires SSL (like Gmail) topic on how to send over SSL.
  3. Even if SMTP service operates on a regular port 25, MS Exchange might require you to use STARTTLS to enable SSL on the connection. Refer to SMTP over SSL (Gmail and others) guide for details.
  4. SMTP service may require you to use secure authentication (e.g. NTLM or GSSAPI). Refer to SMTP authentication in detail guide for details.
  5. MS Exchange may be configured to require you to authenticate as "domain\account" or even "domain\workstation\account" while most other servers accept "account@domain" or simply "account".
  6. With MS Exchange, you may need to increase timeout value. This is because MS Exchange may send "the message was accepted" response after more than 30 seconds since it had received the message data. The default timeout in MailBee.NET is 20 seconds but it's increased to 40 seconds when waiting for response to DATA command. Still, 40 seconds may be not enough in some cases.
  7. SMTP service of MS Exchange claims that it supports ESMTP CHUNKING extension (and thus MailBee.NET takes advantage of that) but in fact Exchange's CHUNKING can slow down the performance due to SMTP Tar Pitting or even not work at all. SMTP Tar Pitting is a setting of MS Exchange for limiting the throughput of the server. It you experience any issues, disable CHUNKING:

server.SmtpOptions = ExtendedSmtpOptions.NoChunking (assuming server is SmtpServer object instance).

Log file of SMTP conversation

You can enable logging of SMTP conversation between MailBee.NET client and the server in a number of ways. You can use logging into a file or memory, subscribe to Smtp.LogNewEntry event which raises each time a new log record is about to be created, and much more.

Logging is useful for trouble-shooting and tracking all the activity for later use. The code below enables logging of all the activity of Smtp object into a file and clears that file:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

Dim mailer As Smtp = New Smtp()
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

To learn more on file or memory logging, refer to Log files and memory logs in detail guide.

Troubleshoot common sending errors and non-delivery

Typical issues you may face and their possible remedy:

  • The application does not run
    • The license key is not set correctly. See Import namespaces and set license key topic.
  • The web application does not run
    • ASP.NET virtual directory is not configured as an application in IIS. In IIS Manager, enable Application for the given web site or virtual directory.
    • ASP.NET v2.0 or v4.0 is disabled (although it may be installed). In IIS Manager for the given web site of virtual directory, check that ASP.NET version being used is 2.0 or higher (4.0 or higher is you're using .NET 4.5 optimized version, MailBee.NET.45.dll).
    • Make sure MailBee.NET.dll actually exists in /bin folder and the application does have permission to read this file.
  • Can't send e-mail at all
    • SMTP port 25 blocked, open it (may not be possible if the port is blocked by your ISP). Some SMTP servers support alternate ports like 587 or SMTP-over-SSL port 465.
    • Your relay server requires SSL connection, use dedicated SSL port 465 or use STARTTLS over regular port 25. See Send if server requires SSL (like Gmail) topic for details.
    • You're trying to send to SSL port as if it were a regular port, or vice versa. See above on how to correctly send via dedicated SSL port or via "SSL over regular port" (STARTTLS).
    • SMTP authentication required. See Send if server requires SMTP authentication topic on now to enable it.
    • SMTP authentication failed due to incorrect username or password. The server may expect username as "account@domain" while you supplied just "account", or vice versa.
    • Secure SMTP authentication failed due to errors in its implementation on the server. See Fine-tune SMTP authentication process topic to tell MailBee.NET to use insecure authentication methods.
    • MS Exchange specific issue. See MS Exchange SMTP issues topic for further suggestions.
    • Check if you can send this e-mail with another SMTP client which is installed on the same computer as MailBee.NET. Another SMTP client should use exactly the same settings like ports, SSL mode, authentication, etc. Note that MS Outlook is not an SMTP client because it usually works via MAPI rather than SMTP. Mozilla Thunderbird is a good example of an SMTP client.
  • Can't send e-mail to external domains
    • SMTP authentication required. See above.
  • E-mail is sent but never appears in the recipient's inbox
    • Check if you can send exactly the same e-mail with another SMTP client which is installed on the same computer as MailBee.NET, and that e-mail gets delivered.
    • Check Spam folder of the recipient. If the e-mail is there, the receiving host thinks it's spam (maybe, you got black-listed or the e-mail content looks spam-alike).
    • Set SmtpServer.HelloDomain property to the external domain name or IP address of the sending machine. E.g. mailer.SmtpServers[0].HelloDomain = "sending.host.com" in C# syntax (assuming mailer is Smtp instance and there is an SmtpServer object already in the collection). See Send custom Hello message to server topic for details.
    • In case of "direct send" mode, set DirectSendServerConfig.HelloDomain property instead. E.g. mailer.DirectSendDefaults.HelloDomain = "sending.host.com".
    • Make sure the IP address of the SMTP relay server is not black-listed.
    • Make sure the sending host has all the required DNS records including MX, PTR, SPF, and they are all properly configured.
  • E-mail gets sent too slowly
    • If your server is MS Exchange, see MS Exchange SMTP issues topic on how to disable CHUNKING.
    • Gmail and many other servers insert significant delays between SMTP commands. They do this intentionally to limit the throughput, as a security and anti-spam measure (if the client sends spam, smaller throughput won't allow sending large volumes of it). See Log file of SMTP conversation topic on how to enable logging and see if the server delays its responses to the client.
  • Can send single e-mail but 2nd (10th, 300th, etc) e-mail fails
    • The server may be configured to limit the maximum number of e-mails per session or from a single IP address per hour. Consider using MailBee.NET Queue. To learn more, refer to Submit to MailBee.NET Queue for increased or limited throughput topic.
  • E-mail looks incorrect (international characters garbled, pictures not displayed in HTML, etc)
    • If there is a problem with international characters, set Smtp.Charset property. Read more in Compose international e-mail guide.
    • If HTML e-mail is missing inline pictures, refer to Send HTML e-mail with embedded pictures and Send e-mail created from web page content topics on how to properly embed inline pictures and other linked resources.

As a general suggestion, read carefully the exception message as it may already provide some useful information, and always enable logging when you face sending errors. The log file is a very helpful source of the debug information which you can use to understand and fix the issue or send it to AfterLogic Support Team for further analysis.

To learn how to deal with logging, see Log file of SMTP conversation topic. To submit the log file to AfterLogic, create a ticket at http://helpdesk.afterlogic.com and upload the file there.

Send feedback to AfterLogic


Send from ASP.NET web application

  • Requirements and limitations
  • Send simple e-mail in ASP.NET
  • Send e-mail with attachment uploaded from client

All MailBee.NET components including Smtp can be used in a web application. This guide explains the specifics of using MailBee.NET SMTP component in ASP.NET WebForms applications, and demonstrates how you can send an e-mail with the attachment uploaded from the client browser.

ASP.NET MVC samples which demonstrate many aspects of using MailBee.NET are also available. They describe how to send and receive e-mails in modern OAuth 2.0 enabled MVC5 apps. See Microsoft and Google regular accounts for MVC5 web applications guide for details.

Requirements and limitations section applies to both WebForms and MVC apps as it highlights issues common for all ASP.NET apps.

Requirements and limitations

The trust level must be High or Full. Medium trust does not allow using Socket objects and making network connections. Neither MailBee.NET nor any other network communication component will work if Socket class cannot be used. With trust level Medium you may, however, use the classes which do not make network connections. For instance, you can parse or build e-mails with MailMessage class.

MailBee.NET.dll must reside in GAC (recommended) or in /bin folder of your web application. If it's in /bin, the user under which context the web application is running (such as NETWORK USER, ASPNET, etc) must have permissions to read that file.

Access to the Windows registry is often not allowed for web applications. It's more reliable to store the license key in web.config or hard-code it in the application code. For the same reason, auto-detection of DNS servers may not work either (this only matters if you're using direct send without any SMTP relay server, and you'll still have the option to specify the DNS servers manually).

SMTP ports like 25, 465 or 587 must be opened in the firewall to let the application connect to SMTP servers at these ports.

Integrated Windows Authentication (NTLM or GSSAPI with empty credentials) won't work if the web application is running under the system user context (like NETWORK USER or ASPNET). Integrated Windows Authentication only makes sense when the application works under "normal" user, like desktop or console apps do.

File I/O access (logging SMTP session into a file, saving or loading e-mails into/from files, etc) can take place only at the folders where the system user is granted read/write access to. For some actions like deleting files and folders, Full Control is needed.

Events raised by Smtp class can still be very useful for a web application even if it does not report the operation progress to the web client (which is the primary use of events in MailBee.NET). In particular, MailBee.NET allows you to use events to control the program flow. For instance, you can cancel sending a message if certain criteria is met during the sending process, and this works the same way for desktop, console and web applications. Learn more at Use events to track successful and failed recipients during sending e-mail topic.

Send simple e-mail in ASP.NET

Virtually all code samples in MailBee.NET documentation can be used in ASP.NET, just replace Console.WriteLine with Response.Write to display results and use Server.HtmlEncode when appropriate (such as when the data being displayed may contain "<>" symbols).

Make sure you have added a reference to MailBee.NET.dll. It's also recommended to put MailBee.NET SMTP license key in web.config file (see Import namespaces and set license key topic for details). If the license key is not there, you'll have to specify it in the code.

The ASP.NET WebForms sample below sends an e-mail message to a recipient and displays the full e-mail address of the recipient. We provide the entire C# and VB code files here. To demonstrate the support of different versions of Visual Studio, C# sample was created with Visual Studio 2008 while VB sample - with Visual Studio 2010, and you can freely use newer versions as well. Here is the code:

  • C#
  • VB
// Default.aspx.cs of the newly created Visual Studio 2008
// Web Site project with Page_Load event added.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MailBee.SmtpMail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Smtp mailer = new Smtp();
        mailer.SmtpServers.Add("mail.here.com", "john.doe", "secret");
        mailer.From.AsString = "John Doe <john.doe@here.com>";
        mailer.To.AsString = "Jane Doe <jane.doe@there.com>";
        mailer.Subject = "Meeting request";
        mailer.BodyPlainText = "Can we meet today?";
        mailer.Send();
        Response.Write("Sent to: " +
        Server.HtmlEncode(mailer.GetAcceptedRecipients().ToString()));
    }
}

' Default.aspx.vb of the newly created Visual Studio 2010
' Web Site project with Page_Load event added.

Imports MailBee.SmtpMail

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object,
          ByVal e As System.EventArgs) Handles Me.Load
        Dim mailer As New Smtp()
        mailer.SmtpServers.Add("mail.here.com", "john.doe", "secret")
        mailer.From.AsString = "John Doe <john.doe@here.com>"
        mailer.To.AsString = "Jane Doe <jane.doe@there.com>"
        mailer.Subject = "Meeting request"
        mailer.BodyPlainText = "Can we meet today?"
        mailer.Send()
        Response.Write("Sent to: " &
            Server.HtmlEncode(mailer.GetAcceptedRecipients().ToString()))
    End Sub
End Class

In Microsoft and Google regular accounts for MVC5 web applications guide you can find (besides other topics) how to send e-mails in OAuth 2.0 enabled ASP.NET MVC apps.

Send e-mail with attachment uploaded from client

The known specifics of web applications is that they often need to get files from client browsers while desktop applications usually deal with files which are already there. In this sample, we'll attach a file uploaded from the client browser.

To prepare this sample, drop the standard FileUpload ASP.NET control (name it FileUpload1) on the form which is declared in Default.aspx file, then add a button which has its PostBackUrl set to Default.aspx. Run the sample, select any file and hit the button to send an e-mail with that file attached:

  • C#
  • VB
// Default.aspx.cs of the newly created Visual Studio 2008
// Web Site project with Page_Load event added.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Smtp mailer = new Smtp();
        mailer.SmtpServers.Add("mail.here.com", "john.doe", "secret");
        mailer.From.AsString = "John Doe <john.doe@here.com>";
        mailer.To.AsString = "Jane Doe <jane.doe@there.com>";
        mailer.Subject = "Requested document";
        mailer.BodyPlainText = "See the document attached";

        if (FileUpload1.HasFile)
        {
            mailer.Message.Attachments.Add(
                FileUpload1.FileBytes, FileUpload1.FileName,
                null, null, null,
                NewAttachmentOptions.None, MailTransferEncoding.Base64);
        }

        mailer.Send();
        Response.Write("Sent to: " +
        Server.HtmlEncode(mailer.GetAcceptedRecipients().ToString()));
    }
}

' Default.aspx.vb of the newly created Visual Studio 2010
' Web Site project with Page_Load event added.

Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Load
        Dim mailer As New Smtp()
        mailer.SmtpServers.Add("mail.here.com", "john.doe", "secret")
        mailer.From.AsString = "John Doe <john.doe@here.com>"
        mailer.To.AsString = "Jane Doe <jane.doe@there.com>"
        mailer.Subject = "Requested document"
        mailer.BodyPlainText = "See the document attached"

        If FileUpload1.HasFile Then
            mailer.Message.Attachments.Add( _
                FileUpload1.FileBytes, FileUpload1.FileName, _
                Nothing, Nothing, Nothing, _
                NewAttachmentOptions.None, MailTransferEncoding.Base64)
        End If

        mailer.Send()
        Response.Write(("Sent to: " & _
            Server.HtmlEncode(mailer.GetAcceptedRecipients().ToString())))
    End Sub
End Class

Note that the file never gets saved to disk. MailBee.NET attaches the file data directly from memory. Your web application may even have no permission to access the filesystem and will still work properly.

Send feedback to AfterLogic


Compose complex e-mail with multiple parts and attachments

  • Send e-mail with separate HTML and plain-text parts
  • Send e-mail with HTML part and auto-generated plain-text part
  • Send e-mail with attachments from stream, memory, another message
  • Send HTML e-mail with embedded pictures
  • Send e-mail created from web page content
  • Create HTML in memory and automatically embed linked resources
  • Create HTML in memory and manually embed linked resources

This guide demonstrates how to send e-mails consisting of several parts. The code snippets also show various methods of how you can set sender and recipients, set SMTP relay server, use quick send, logging and other things related to composing and sending e-mail.

Send e-mail with separate HTML and plain-text parts

Well-designed HTML e-mail should also provide plain-text alternative for those e-mail readers which do not support HTML. Even if you know that all your recipients use HTML-capable e-mail programs, keep in mind that spam filters don't HTML e-mails without plain-text part.

Although MailBee.NET can generate plain-text version of your HTML body automatically, you may need to override this default behavior. For instance, if your HTML data cannot be represented as plain-text at all, and you want to inform users that they must upgrade their e-mail client to be able to see HTML version, or provide a link on your web site where they can view this e-mail online:

  • C#
  • VB
Smtp mailer = new Smtp();

// Enable logging, useful for trouble-shooting.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.here.com", "john.doe", "password");

// Set From and To as EmailAddress objects.
mailer.Message.From = new EmailAddress("john.doe@here.com", "John Doe");
mailer.Message.To.Add("jane.doe@there.com", "Jane Doe");

// The idea is that the message body contains sections in different color, and
// this coloring is essential for understanding this document. Because plain-text
// cannot display colors, it's useless in this case. Inform the user of that.
mailer.Message.Subject = "Revised document, changes marked red";
mailer.Message.BodyPlainText = "You need HTML-capable program to view this e-mail";
mailer.Message.BodyHtmlText =
    "<html><body>Old data<br/><font color=red>New data</font></body></html>";

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Enable logging, useful for trouble-shooting.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.here.com", "john.doe", "password")

' Set From and To as EmailAddress objects.
mailer.Message.From = New EmailAddress("john.doe@here.com", "John Doe")
mailer.Message.To.Add("jane.doe@there.com", "Jane Doe")

' The idea is that the message body contains sections in different color, and
' this coloring is essential for understanding this document. Because plain-text
' cannot display colors, it's useless in this case. Inform the user of that.
mailer.Message.Subject = "Revised document, changes marked red"
mailer.Message.BodyPlainText = "You need HTML-capable program to view this e-mail"
mailer.Message.BodyHtmlText = _
    "<html><body>Old data<br/><font color=red>New data</font></body></html>"

mailer.Send()

For all the samples, we assume MailBee, MailBee.SmtpMail and MailBee.Mime namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

Send e-mail with HTML part and auto-generated plain-text part

If you set only HTML version of the body, MailBee.NET generates plain-text version automatically:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.here.com", " john.doe@here.com", "password");

// Set From and To in various ways.
mailer.Message.From.Email = "john.doe@here.com";
mailer.Message.From.DisplayName = "John Doe";
mailer.Message.To.Add(new EmailAddress("jane.doe@there.com", "Jane Doe"));

// HTML body here contains some HTML-only formatting but it's not
// crucial to understanding this document.
mailer.Message.Subject = "Rich-formatted e-mail";
mailer.Message.BodyHtmlText =
    "<html><body>Data<br/><i>Regards, John</i></body></html>";

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.here.com", " john.doe@here.com", "password")

' Set From and To in various ways.
mailer.Message.From.Email = "john.doe@here.com"
mailer.Message.From.DisplayName = "John Doe"
mailer.Message.To.Add(New EmailAddress("jane.doe@there.com", "Jane Doe"))

' HTML body here contains some HTML-only formatting but it's not
' crucial to understanding this document.
mailer.Message.Subject = "Rich-formatted e-mail"
mailer.Message.BodyHtmlText = _
    "<html><body>Data<br/><i>Regards, John</i></body></html>"

mailer.Send()

If you would like to produce HTML-only e-mail and disable the auto-creation of plain-text from HTML at all, add this line before mailer.Send():

mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.Never

Send e-mail with attachments from stream, memory, another message

To just add an attachment from a file, refer to Send HTML e-mail with attachment topic. This guide demonstrates more advanced matters like different filenames on disk and in the e-mail, memory attachments, and "forward as attachment" techniques.

This sample adds 4 attachments, each is loaded differently:

  1. From a file, the attachment receives a different filename from its original filename on disk.
  2. From a Stream object which represents a file loaded from arbitrary source like database.
  3. From a memory array (in the sample, this array is the result of WebClient.DownloadData method call).
  4. From another MailMessage object which represents another e-mail such as received from IMAP or POP3 server.
  • C#
  • VB
// Create MailMessage object and set headers.
MailMessage msg = new MailMessage();
msg.From.Email = "john.doe@here.com";
msg.From.DisplayName = "John Doe";
msg.To.Add(new EmailAddress("jane.doe@there.com", "Jane Doe"));
msg.Subject = "E-mail with 4 attachments";

// Add attachment from file with temp filename.
msg.Attachments.Add(@"C:\Temp\A13EF8B0.TMP", "report.doc");

// Add attachment from Stream. Here, we'll fill the stream
// with only 1 byte which is zero.
System.IO.Stream dataStream = new System.IO.MemoryStream();
dataStream.WriteByte(0);
dataStream.Position = 0;
msg.Attachments.Add(dataStream, "0.dat", null, null, null,
    NewAttachmentOptions.None, MailTransferEncoding.Base64);

// Add attachment from byte array. This byte array is the content
// of www.afterlogic.com web page.
System.Net.WebClient web = new System.Net.WebClient();
byte[] data = web.DownloadData("http://www.afterlogic.com");
msg.Attachments.Add(data, "afterlogic.html", null, null, null,
    NewAttachmentOptions.None, MailTransferEncoding.QuotedPrintable);

// Download an e-mail from IMAP server and attach it
// as forwarded message to the e-mail being constructed.
MailMessage existingMsg = MailBee.ImapMail.Imap.QuickDownloadMessage(
    "mail.domain.com", "user@domain.com", "secret", "Inbox", -1);
msg.Attachments.Add(existingMsg, null, null, null, null,
    NewAttachmentOptions.None, MailTransferEncoding.None);

// For variety's sake, use QuickSend to send the constructed e-mail.
// We could have also used regular Send as in previous samples.
Smtp.QuickSend(msg);

' Create MailMessage object and set headers.
Dim msg As MailMessage = New MailMessage()
msg.From.Email = "john.doe@here.com"
msg.From.DisplayName = "John Doe"
msg.To.Add(New EmailAddress("jane.doe", "Jane Doe"))
msg.Subject = "E-mail with 4 attachments"

' Add attachment from file with temp filename.
msg.Attachments.Add("C:\Temp\A13EF8B0.TMP", "report.doc")

' Add attachment from Stream. Here, we'll fill the stream
' with only 1 byte which is zero.
Dim dataStream As System.IO.Stream = New System.IO.MemoryStream()
dataStream.WriteByte(0)
dataStream.Position = 0
msg.Attachments.Add(dataStream, "0.dat", Nothing, Nothing, Nothing, _
    NewAttachmentOptions.None, MailTransferEncoding.Base64)

' Add attachment from byte array. This byte array is the content
' of www.afterlogic.com web page.
Dim web As System.Net.WebClient = New System.Net.WebClient()
Dim data() As Byte = web.DownloadData("http://www.afterlogic.com")
msg.Attachments.Add(data, "afterlogic.html", Nothing, Nothing, Nothing, _
    NewAttachmentOptions.None, MailTransferEncoding.QuotedPrintable)

' Download an e-mail from IMAP server and attach it
' as forwarded message to the e-mail being constructed.
Dim existingMsg As MailMessage = MailBee.ImapMail.Imap.QuickDownloadMessage( _
    "mail.domain.com", "user@domain.com", "secret", "Inbox", -1)
msg.Attachments.Add(existingMsg, Nothing, Nothing, Nothing, Nothing, _
    NewAttachmentOptions.None, MailTransferEncoding.None)

' For variety's sake, use QuickSend to send the constructed e-mail.
' We could have also used regular Send as in previous samples.
Smtp.QuickSend(msg)

To learn more on how to reply or forward existing e-mails (received from POP3 or IMAP, loaded from file, etc), refer to Receive e-mail with POP3, forward it as attachment of another e-mail and send with SMTP and Receive e-mail with IMAP, reply to it and send via SMTP topics.

Send HTML e-mail with embedded pictures

MailBee.NET supports several methods which let you embed linked resources like pictures, CSS tables and so on, directly into the e-mail. You also have an option to embed such resources automatically.

Typically, you have an HTML file along with a set of related files like pictures, and want to import this file and all the linked files into the e-mail being constructed. That's how you can do this:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server without authentication.
mailer.SmtpServers.Add("mail.company.com");

// Set From and To in without friendly names.
mailer.Message.From.Email = "john.doe@company.com";
mailer.Message.To.Add("jane.doe@example.com");

mailer.Subject = "HTML e-mail with embedded pictures";

// Load HTML file, analyze it, attach all linked resources, generate and
// assign a Content-ID (CID) to each resource, and finally adjust HTML body
// to replace the resources' filenames with their corresponding Content-IDs.
mailer.Message.LoadBodyText(@"C:\Temp\document.html", MessageBodyType.Html, null,
    ImportBodyOptions.ImportRelatedFiles);

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server without authentication.
mailer.SmtpServers.Add("mail.company.com")

' Set From and To in without friendly names.
mailer.Message.From.Email = "john.doe@company.com"
mailer.Message.To.Add("jane.doe@example.com")

mailer.Subject = "HTML e-mail with embedded pictures"

' Load HTML file, analyze it, attach all linked resources, generate and
' assign a Content-ID (CID) to each resource, and finally adjust HTML body
' to replace the resources' filenames with their corresponding Content-IDs.
mailer.Message.LoadBodyText("C:\Temp\document.html", MessageBodyType.Html, Nothing, _
    ImportBodyOptions.ImportRelatedFiles)

mailer.Send()

ImportBodyOptions.ImportRelatedFiles flag tells MailMessage.LoadBodyText method that it also needs to embed linked resources.

Note that both the HTML document and its related files must reside on the filesystem (i.e. not on the web). All non-local references will stay as is. If you want MailBee.NET to download them from the web and embed to the e-mail just like local resources, add ImportBodyOptions.ImportRelatedFilesFromUris flag in addition to ImportBodyOptions.ImportRelatedFiles:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret");

// Set From and To as strings (with and without friendly names).
mailer.Message.From.AsString = "john.doe@company.com";
mailer.Message.To.AsString = "Jane Doe <jane.doe@example.com>";

mailer.Subject = "HTML e-mail with embedded pictures";

// Load HTML file, analyze it, attach all linked resources (downloading from the web
// if necessary), generate and assign a Content-ID to each resource, and finally adjust
// HTML body to replace the resources' original URIs with their assigned Content-IDs.
mailer.Message.LoadBodyText(@"C:\Temp\document.html", MessageBodyType.Html, null,
    ImportBodyOptions.ImportRelatedFiles |
    ImportBodyOptions.ImportRelatedFilesFromUris);

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret")

' Set From and To as strings (with and without friendly names).
mailer.Message.From.AsString = "john.doe@company.com"
mailer.Message.To.AsString = "Jane Doe <jane.doe@example.com>"

mailer.Subject = "HTML e-mail with embedded pictures"

' Load HTML file, analyze it, attach all linked resources (downloading from the web
' if necessary), generate and assign a Content-ID to each resource, and finally adjust
' HTML body to replace the resources' original URIs with their assigned Content-IDs.
mailer.Message.LoadBodyText("C:\Temp\document.html", MessageBodyType.Html, Nothing, _
    ImportBodyOptions.ImportRelatedFiles Or _
    ImportBodyOptions.ImportRelatedFilesFromUris)

mailer.Send()

It's assumed the links in the source HTML document match the locations of the files they relate to. For example, if the HTML file resides in C:\Temp folder and contains <IMG SRC="images/logo.gif"> tag, logo.gif file must reside in C:\Temp\images folder.

If the above is not the case (your HTML document and its related files are in very different locations), you can either use absolute paths in your HMTL (e.g. <IMG SRC="C:\Data\images\logo.gif">) or set the related files folder root with MessageBuilderConfig.RelatedFilesFolder property (you can access it using MailMessage.Builder.RelatedFilesFolder syntax). See Create HTML in memory and automatically embed linked resources topic for details.

Send e-mail created from web page content

The previous topic demonstrated how you can embed linked resources which can reside on the web but the HTML document itself was required to reside on the local filesystem or a network share (not on the web).

To load HTML document from a web location, add ImportBodyOptions.PathIsUri flag in addition to ImportBodyOptions.ImportRelatedFiles and ImportBodyOptions.ImportRelatedFilesFromUris flags when callingMailMessage.LoadBodyText method:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret");

// Set From and To as strings (with and without friendly names).
mailer.Message.From.AsString = "John Doe <john.doe@company.com>";
mailer.Message.To.AsString = "jane.doe@example.com";

mailer.Subject = "HTML e-mail with embedded pictures";

// Load HTML from the web, analyze it, download and attach all linked resources,
// generate and assign a Content-ID to each resource, and finally adjust HTML body
// to replace the resources' original URIs with their assigned Content-IDs.
mailer.Message.LoadBodyText("http://www.afterlogic.com/mailbee-net/smtp-component",
    MessageBodyType.Html, null,
    ImportBodyOptions.PathIsUri |
    ImportBodyOptions.ImportRelatedFiles |
    ImportBodyOptions.ImportRelatedFilesFromUris);

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret")

' Set From and To as strings (with and without friendly names).
mailer.Message.From.AsString = "John Doe <john.doe@company.com>"
mailer.Message.To.AsString = "jane.doe@example.com"

mailer.Subject = "HTML e-mail with embedded pictures"

' Load HTML from the web, analyze it, download and attach all linked resources,
' generate and assign a Content-ID to each resource, and finally adjust HTML body
' to replace the resources' original URIs with their assigned Content-IDs.
mailer.Message.LoadBodyText("http://www.afterlogic.com/mailbee-net/smtp-component", _
    MessageBodyType.Html, Nothing, _
    ImportBodyOptions.PathIsUri Or _
    ImportBodyOptions.ImportRelatedFiles Or _
    ImportBodyOptions.ImportRelatedFilesFromUris)

mailer.Send()

Note that the actual content you'll receive in the message body may be different from what you see when open the same page in the web browser. The possible reasons of that:

  • The web page may utilize some JavaScript which changes how the page looks.
  • The web page may contain "META refresh" tag which forces the web browser to redirect to another location and display you another page.
  • The web page may check the client's info to determine that the client is not a normal web browser and behave differently in this case.

Create HTML in memory and automatically embed linked resources

Previous topics assumed the HTML body was imported from a file or web location and this HTML had actual references to the linked resources. In other words, we assumed that if the HTML contained <IMG SRC="pictures/logo.gif"> and we took this HTML from C:\Temp folder, the picture's physical location was C:\Temp\pictures\logo.gif. This way, MailBee.NET used the location of the HTML document as a root to resolve all relative paths to the resources referenced in this HTML.

However, if you create the HTML document directly in memory (e.g. you set MailMessage.BodyHtmlText property instead of calling MailMessage.LoadBodyText), MailBee.NET does not know the root location. You can specify it with with MessageBuilderConfig.RelatedFilesFolder property (to access it, use MailMessage.Builder.RelatedFilesFolder syntax). It works for web locations as well.

For demonstration purposes, the sample below loads the HTML data into MailMessage object not using file I/O features of MailBee.NET, then sets the root for resolving relative paths, and finally imports all the linked resources:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret");

// Set From and To as strings (without friendly names).
mailer.Message.From.AsString = "john.doe@company.com";
mailer.Message.To.AsString = "jane.doe@example.com";

mailer.Subject = "HTML e-mail with embedded pictures";

// For demonstration purposes, compose HTML body by downloading it from a web location
// (in real application, it's easier to use MailMessage.LoadBodyText method).
System.Net.WebClient web = new System.Net.WebClient();
mailer.Message.BodyHtmlText =
    web.DownloadString("http://www.afterlogic.com/mailbee-net/smtp-component");

// Set the root for all relative paths in the HTML document.
mailer.Message.Builder.RelatedFilesFolder = "http://www.afterlogic.com/mailbee-net/";

// Analyze BodyHtmlText content, download and attach all linked resources,
// generate and assign a Content-ID to each resource, and finally adjust HTML body
// to replace the resources' original URIs with their assigned Content-IDs.
mailer.Message.ImportRelatedFiles(ImportRelatedFilesOptions.ImportFromUris);

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret")

' Set From and To as strings (without friendly names).
mailer.Message.From.AsString = "john.doe@company.com"
mailer.Message.To.AsString = "jane.doe@example.com"

mailer.Subject = "HTML e-mail with embedded pictures"

' For demonstration purposes, compose HTML body by downloading it from a web location
' (in real application, it's easier to use MailMessage.LoadBodyText method).
Dim web As System.Net.WebClient = New System.Net.WebClient()
mailer.Message.BodyHtmlText = _
    web.DownloadString("http://www.afterlogic.com/mailbee-net/smtp-component")

' Set the root for all relative paths in the HTML document.
mailer.Message.Builder.RelatedFilesFolder = "http://www.afterlogic.com/mailbee-net/"

' Analyze BodyHtmlText content, download and attach all linked resources,
' generate and assign a Content-ID to each resource, and finally adjust HTML body
' to replace the resources' original URIs with their assigned Content-IDs.
mailer.Message.ImportRelatedFiles(ImportRelatedFilesOptions.ImportFromUris)

mailer.Send()

Create HTML in memory and manually embed linked resources

In the previous sample, we stated that the HTML is created by the application but in fact we simply downloaded an existing HTML document (we could have also used MailMessage.LoadBodyText method for the same purpose).

In case if you actually craft the HTML body contents directly in your application, can can make all the links point to Content-IDs from the very beginning instead of making "normal" links and then having MailBee.NET replace them with Content-IDs. This is faster as no extra processing of the HTML body is being made (can make a difference if your HTML document is very large).

The sample below crafts an e-mail with 1 non-embedded picture (used to track when the recipient opens the e-mail) and 2 embedded pictures, all Content-IDs for embedded pictures are created manually:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret");

// Set From and To as strings (with friendly names).
mailer.Message.From.AsString = "John Doe <john.doe@here.com>";
mailer.Message.To.AsString = "Jane Doe <jane.doe@there.com>";

mailer.Subject = "HTML e-mail with embedded and non-embedded pictures";

// Use StringBuilder object for efficient manipulation with strings.
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
strBuilder.Append("<html><body>");

// Declare embedded pictures in HTML.
strBuilder.Append("<img src='cid:picture_01'><br/>");
strBuilder.Append("<img src='cid:picture_02'><br/>");

// We also add external (non-embedded) image. Usually, they are tiny 1x1 pixel
// pictures used to track the user's activity with the e-mail (for instance,
// to get to know when the user viewed it). We assume the assigned ID of this e-mail
// to jane.doe@there.com within your system is 100.
int i = 100;

// Once Jane Doe opens the message, her e-mail program will try to open
// http://www.domain.com/?id=100 URL to display the image,
// provided that viewing external images is enabled in Jane Doe's e-mail program.
strBuilder.Append("<img src='http://www.domain.com/?id=" + i.ToString() + "'>");

strBuilder.Append("</body></html>");
mailer.Message.BodyHtmlText = strBuilder.ToString();

mailer.Message.Attachments.Add(@"C:\Temp\logo.gif", null, "picture_01");
mailer.Message.Attachments.Add(@"C:\Temp\photo.jpg", null, "picture_02");

// The e-mail contains only graphics and cannot be presented in plain-text.
mailer.Message.BodyPlainText = "HTML-capable e-mail program needed to view this e-mail";

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret")

' Set From and To as strings (with friendly names).
mailer.Message.From.AsString = "John Doe <john.doe@here.com>"
mailer.Message.To.AsString = "Jane Doe <jane.doe@there.com>"

mailer.Subject = "HTML e-mail with embedded and non-embedded pictures"

' Use StringBuilder object for efficient manipulation with strings.
Dim strBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
strBuilder.Append("<html><body>")

' Declare embedded pictures in HTML.
strBuilder.Append("<img src='cid:picture_01'><br/>")
strBuilder.Append("<img src='cid:picture_02'><br/>")

' We also add external (non-embedded) image. Usually, they are tiny 1x1 pixel
' pictures used to track the user's activity with the e-mail (for instance,
' to get to know when the user viewed it). We assume the assigned ID of this e-mail
' to jane.doe@there.com within your system is 100.
Dim i As Integer = 100

' Once Jane Doe opens the message, her e-mail program will try to open
' http://www.domain.com/?id=100 URL to display the image,
' provided that viewing external images is enabled in Jane Doe's e-mail program.
strBuilder.Append("<img src='http://www.domain.com/?id=" & i.ToString() & "'>")

strBuilder.Append("</body></html>")
mailer.Message.BodyHtmlText = strBuilder.ToString()

mailer.Message.Attachments.Add("C:\Temp\logo.gif", Nothing, "picture_01")
mailer.Message.Attachments.Add("C:\Temp\photo.jpg", Nothing, "picture_02")

' The e-mail contains only graphics and cannot be presented in plain-text.
mailer.Message.BodyPlainText = "HTML-capable e-mail program needed to view this e-mail"

mailer.Send()

You can mix automatic and manual embedding of linked resources. For instance, MailBee.NET might not automatically embed certain resource (if it was referenced from CSS rather than directly from HTML), and you want to fix this. The below is how you can do this.

After mailer.MailMessage.LoadBodyText has done its job, you can then attach the resource in question to the message and assign certain Content-ID for it, then replace the URL of this resource in mailer.MailMessage.BodyHtmlText value with "cid:" followed by the Content-ID value (it's assumed mailer is an Smtp instance).

If the resource is not local, you can use WebClient.DownloadData to download it and then attach it using mailer.MailMessage.Attachments.Add syntax (AttachmentCollection.Add method has overloads which accept byte array or stream). See Send e-mail with attachments from file, stream, memory, another message topic for details.

Send feedback to AfterLogic


Compose e-mail created from another object or file

  • Send e-mail created from System.Net.Mail.MailMessage
  • Send e-mail created from memory
  • Send e-mail created from file
  • Send e-mail created from serialized XML
  • Send e-mail created from Outlook .MSG message

This guide explains how you can send an existing e-mail (for instance, the e-mail previously stored on disk, in database, XML file, created with System.Net.Mail.MailMessage object, etc).

Send e-mail created from System.Net.Mail.MailMessage

If your existing code composes e-mails with the help of System.Net.Mail.MailMessage class, you can re-use this code with MailBee.NET and easily export this object into MailBee.Mime.MailMessage object used by MailBee.NET class as the standard representation of an e-mail.

When dealing with System.Net.Mail and MailBee.NET classes in the same application, you'll need to use fully qualified type names for MailMessage class because both System.Net.Mail and MailBee.Mime namespaces have classes with such name:

  • C#
  • VB
System.Net.Mail.MailMessage sysMsg = new System.Net.Mail.MailMessage();
sysMsg.Subject = "Test message";
MailBee.Mime.MailMessage msg = new MailBee.Mime.MailMessage();
msg.ConvertFromSystemNetMail(sysMsg);

Dim sysMsg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
sysMsg.Subject = "Test message"
Dim msg As MailBee.Mime.MailMessage = New MailBee.Mime.MailMessage()
msg.ConvertFromSystemNetMail(sysMsg)

Or, you can create aliases for System.Net.Mail.MailMessage and MailBee.Mime.MailMessage classes and use these alias names instead.

The below is a complete Console application sample which imports all the required namespaces, defines aliases and sends the e-mail built from System.Net.Mail.MailMessage class (we assume the license key is already set outside the code, see Import namespaces and set license key topic for details).

In particular, we build the new e-mail as a container e-mail and add the original e-mail (converted from System.Net.Mail.MailMessage) as an attachment to the container e-mail ("forward as attachment" technique):

  • C#
  • VB
using System;
using System.Net.Mail;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;
using SysMailMessage = System.Net.Mail.MailMessage;
using MailBeeMessage = MailBee.Mime.MailMessage;

class Program
{
    static void Main(string[] args)
    {
        // Prepare System.Net.Mail.MailMessage object.
        SysMailMessage sysMsg = new SysMailMessage();
        sysMsg.Subject = "Test message";
        sysMsg.From = new MailAddress("john.doe@domain.com");
        sysMsg.To.Add("jane.doe@company.com");
        sysMsg.Body = "Test message body";

        // Create MailBee.Mime.MailMessage from System.Net.Mail.MailMessage.
        MailBeeMessage msg = new MailBeeMessage();
        msg.ConvertFromSystemNetMail(sysMsg);

        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret");

        // Create an envelope message, add the original message as attachment
        // of the envelope message, and assign the envelope message as the
        // message to be sent by Smtp object.
        mailer.Message = msg.ForwardAsAttachment();

        // Set other headers of the message to be sent.
        mailer.Message.From.Email = "john@here.com";
        mailer.Message.To.Add("mike@there.com");
        mailer.Message.Subject = "See forwarded message in attachment";

        mailer.Send();
    }
}

Imports System
Imports System.Net.Mail
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports SysMailMessage = System.Net.Mail.MailMessage
Imports MailBeeMessage = MailBee.Mime.MailMessage

Module Module1
    Sub Main()
        ' Prepare System.Net.Mail.MailMessage object.
        Dim sysMsg As SysMailMessage = New SysMailMessage()
        sysMsg.Subject = "Test message"
        sysMsg.From = New MailAddress("john.doe@domain.com")
        sysMsg.To.Add("jane.doe@company.com")
        sysMsg.Body = "Test message body"

        ' Create MailBee.Mime.MailMessage from System.Net.Mail.MailMessage.
        Dim msg As MailBeeMessage = New MailBeeMessage()
        msg.ConvertFromSystemNetMail(sysMsg)

        Dim mailer As Smtp = New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret")

        ' Create an envelope message, add the original message as attachment
        ' of the envelope message, and assign the envelope message as the
        ' message to be sent by Smtp object.
        mailer.Message = msg.ForwardAsAttachment()

        ' Set other headers of the message to be sent.
        mailer.Message.From.Email = "john@here.com"
        mailer.Message.To.Add("mike@there.com")
        mailer.Message.Subject = "See forwarded message in attachment"

        mailer.Send()
    End Sub
End Module

In many cases, you won't need to worry about collisions of System.Net.Mail.MailMessage and MailBee.Mime.MailMessage class names at all. Just don't import MailBee.Mime namespace if your code never (or at least rarely) directly uses the class names within MailBee.Mime namespace.

The Console application sample below is different from the previous sample in that it simply re-sends the message which was converted from System.Net.Mail.MailMessage and never uses any class names within MailBee.Mime namespace (the sample does use Smtp.Message property which is of MailBee.Mime.MailMessage type but it never uses this class name explicitly):

  • C#
  • VB
using System;
using System.Net.Mail;
using MailBee;
using MailBee.SmtpMail;

class Program
{
    static void Main(string[] args)
    {
        // Prepare System.Net.Mail.MailMessage object. We don't need to use
        // aliases or full class names as MailBee.Mime namespace wasn't imported.
        MailMessage sysMsg = new MailMessage();
        sysMsg.Subject = "Test message";
        sysMsg.From = new MailAddress("john.doe@domain.com");
        sysMsg.To.Add("jane.doe@company.com");
        sysMsg.Body = "Test message body";

        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret");

        // We implicitly use MailBee.Mime.MailMessage here but the compiler anyway
        // knows the type of mailer.Message and the code compiles just fine even
        // though we never imported MailBee.Mime namespace.
        mailer.Message.ConvertFromSystemNetMail(sysMsg);

        // Demonstrate that we can modify the converted message.
        // Charset property is a good example as you can't easily set the charset
        // with System.Net.Mail.MailMessage and that can be the reason why you
        // need to do this at MailBee.Mime stage (not at System.Net.Mail stage).
        mailer.Message.Charset = "utf-8";

        mailer.Send();
    }
}

Imports System
Imports System.Net.Mail
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports SysMailMessage = System.Net.Mail.MailMessage
Imports MailBeeMessage = MailBee.Mime.MailMessage

Module Module1
    Sub Main()
        ' Prepare System.Net.Mail.MailMessage object.
        Dim sysMsg As SysMailMessage = New SysMailMessage()
        sysMsg.Subject = "Test message"
        sysMsg.From = New MailAddress("john.doe@domain.com")
        sysMsg.To.Add("jane.doe@company.com")
        sysMsg.Body = "Test message body"

        ' Create MailBee.Mime.MailMessage from System.Net.Mail.MailMessage.
        Dim msg As MailBeeMessage = New MailBeeMessage()
        msg.ConvertFromSystemNetMail(sysMsg)

        Dim mailer As Smtp = New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret")

        ' Create an envelope message, add the original message as attachment
        ' of the envelope message, and assign the envelope message as the
        ' message to be sent by Smtp object.
        mailer.Message = msg.ForwardAsAttachment()

        ' Set other headers of the message to be sent.
        mailer.Message.From.Email = "john@here.com"
        mailer.Message.To.Add("mike@there.com")
        mailer.Message.Subject = "See forwarded message in attachment"

        mailer.Send()
    End Sub
End Module

MailBee.NET also allows you to convert MailBee.Mime.MailMessage back to System.Net.Mail.MailMessage. Use MailBee.Mime.MailMessage.ConvertToSystemNetMail method if you need this.

Send e-mail created from memory

If you have an existing e-mail in the form of a byte array or byte stream, you can easily load it into MailMessage object using the overloads of MailMessage.LoadMessage method which accept byte array or Stream, then alter the properties of the loaded message if needed, and finally send it.

The sample below sends the e-mail loaded from a byte array (which you could have received by reading from any data source like database):

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret");

// Load the message from byte array.
mailer.Message.LoadMessage(msgData);

// Demonstrate that we can modify the loaded message.
// Update the date when the message was composed to the current moment.
mailer.Message.Date = DateTime.Now;

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret")

' Load the message from byte array.
mailer.Message.LoadMessage(msgData)

' Demonstrate that we can modify the loaded message.
' Update the date when the message was composed to the current moment.
mailer.Message.Date = DateTime.Now

mailer.Send()

In this and other samples in this guide, it's assumed MailBee and MailBee.SmtpMail namespaces have been imported and the license key has been set (see Import namespaces and set license key topic for details). msgData must point to the byte array (byte[] in C# and Byte() in VB) which you need to set in your code.

Send e-mail created from file

If you have an e-mail in MIME format (for instance, you previously saved it into a file with MailMessage.SaveMessage(string) method), you can then load it back with MailMessage.LoadMessage(string) method, and send it out.

The data format of the file is exactly the same as the byte array's format used in Send e-mail created from memory topic. Thus, MailMessage.SaveMessage(string) method in fact reads the file in a byte array and then loads the message from that byte array using MailMessage.LoadMessage(byte[]) overload.

Note that you can load any MIME-compliant e-mail file even if it wasn't created by MailBee.NET. MIME-compliant e-mail files usually have .EML extension. The sample below loads the e-mail from .EML file and sends it:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "joe@domain.com", "secret");

// Load the message from .EML file (it must be in MIME RFC2822 format).
mailer.Message.LoadMessage(@"C:\Temp\message.eml");

// Demonstrate that we can modify the loaded message.
// Update the date when the message was composed to the current moment.
mailer.Message.Date = DateTime.Now;

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "joe@domain.com", "secret")

' Load the message from .EML file (it must be in MIME RFC2822 format).
mailer.Message.LoadMessage("C:\Temp\message.eml")

' Demonstrate that we can modify the loaded message.
' Update the date when the message was composed to the current moment.
mailer.Message.Date = DateTime.Now

mailer.Send()

Besides of .EML, some programs also use .MSG extension for MIME files. However, .MSG extension is usually associated with MS Office Outlook e-mail messages in binary format.

In case if you indeed would like to read Outlook .MSG files with MailBee.NET, use MailBee.NET Outlook component. It's included in MailBee.NET assembly but it's licensed separately from SMTP component (MailBee.NET Objects bundle includes all the licenses). See Send e-mail created from Outlook .MSG message topic for details.

Send e-mail created from serialized XML

If you have previously saved an e-mail with MailMessage.Serialize(string) method, you can then restore it with MailMessage.Deserialize(string) and send it:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret");

// Load the message from XML file (which was earlier produced
// with MailMessage.Serialize method call).
mailer.Message.Deserialize(@"C:\Temp\message.xml");

// Demonstrate that we can modify the loaded message.
// Update the date when the message was composed to the current moment.
mailer.Message.Date = DateTime.Now;

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.domain.com", "john.doe", "secret")

' Load the message from XML file (which was earlier produced
' with MailMessage.Serialize method call).
mailer.Message.Deserialize("C:\Temp\message.xml")

' Demonstrate that we can modify the loaded message.
' Update the date when the message was composed to the current moment.
mailer.Message.Date = DateTime.Now

mailer.Send()

And you can also deserialize from memory (rather than from a file) using MailMessage.Deserialize(XmlTextReader) overload.

Send e-mail created from Outlook .MSG message

If you have .MSG file in Outlook format, you can convert it into MailBee.Mime.MailMessage object and then do with it whatever you want. For instance, you can then modify and send it.

To load .MSG file into MailBee.Mime.MailMessage object, MailBee.NET Outlook license is required (MailBee.NET SMTP license does not include it while the full MailBee.NET Objects license does).

Before you can use Outlook component, import MailBee.Outlook namespace and set MailBee.Global.LicenseKey (unless you already did this to unlock other components).

The self-contained Console sample below imports all the required namespaces, sets the required license key directly in the code (although you could have placed it elsewhere, such as in app.config), loads the e-mail from .MSG file and sends it out:

  • C#
  • VB
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Outlook;

class Program
{
    static void Main(string[] args)
    {
        // Set license keys not relying on app.config or registry.
        MailBee.Global.LicenseKey = "MailBee.NET SMTP or Objects key";

        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("smtp.domain.com", "joe@domain.com", "secret");

        // Load the e-mail to be sent from Outlook .MSG file.
        MsgConvert msgReader = new MsgConvert();
        mailer.Message = msgReader.MsgToMailMessage(@"C:\Temp\message.msg");

        // Demonstrate that we can modify the loaded message.
        // Update the date when the message was composed to the current moment.
        mailer.Message.Date = DateTime.Now;

        mailer.Send();
    }
}

Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Outlook

Module Module1
    Sub Main()
        ' Set license keys not relying on app.config or registry.
        MailBee.Global.LicenseKey = "MailBee.NET SMTP or Objects key"

        Dim mailer As Smtp = New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("smtp.domain.com", "joe@domain.com", "secret")

        ' Load the e-mail to be sent from Outlook .MSG file.
        Dim msgReader As MsgConvert = New MsgConvert()
        mailer.Message = msgReader.MsgToMailMessage("C:\Temp\message.msg")

        ' Demonstrate that we can modify the loaded message.
        ' Update the date when the message was composed to the current moment.
        mailer.Message.Date = DateTime.Now

        mailer.Send()
    End Sub
End Module

If your .MSG data is stored in memory rather than file, you can read it from Stream with MsgConvert.MsgToMailMessage(Stream) method.

You can also extract e-mails from Outlook .PST files. In this case, use PstReader class. Both MsgConvert and PstReader classes are considered the parts of the same component and are covered by the same license.

Send feedback to AfterLogic


Compose international e-mail

  • Charsets, code pages, encodings, and UTF-8
  • Content-transfer encodings
  • UTF-8 or local language-specific charset?
  • HTML META tag with charset declaration
  • HTML-encoded international characters ("&#xxxx;" sequences)
  • Send plain-text e-mail with Chinese content and "utf-8" or "gb2312" charset
  • Send plain-text e-mail with Windows-1252 headers (German characters in From, Subject, To)
  • Send HTML e-mail with international characters
  • Compose e-mail in right-to-left language like Hebrew
  • Send e-mail with international characters in headers, body, attachment filenames

This guide demonstrates creating e-mails written in languages which use non-Latin alphabet, explains code pages, charsets and character encodings, RTL (right-to-left languages), HTML META tags, localized headers and attachment filenames.

Charsets, code pages, encodings, and UTF-8

In most cases, it's enough to specify the correct message charset in case if put some international characters there. Nowadays, UTF-8 is becoming the standard for the Internet communication and most e-mail programs can correctly display e-mails which use UTF-8 charset:

  • C#
  • VB
mailer.Message.Charset = "utf-8";

mailer.Message.Charset = "utf-8"

We assume mailer is an Smtp object instance. In addition to that, for all the samples in this guide we assume MailBee, MailBee.Mime, and MailBee.SmtpMail namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

By the way, it's recommended to use lower-case names for charsets. For instance, utf-8 is better than UTF-8 because some e-mail clients do not understand charset names which are not lowercase.

If international characters appear in the headers of your e-mail message, it's recommended to encode them using base64 or quoted-printable transformation:

  • C#
  • VB
mailer.Message.Charset = "utf-8";
mailer.Message.EncodeAllHeaders(System.Text.Encoding.UTF8, HeaderEncodingOptions.None)

mailer.Message.Charset = "utf-8"
mailer.Message.EncodeAllHeaders(System.Text.Encoding.UTF8, HeaderEncodingOptions.None)

It's assumed that all the headers and attachments' filenames with international characters had been set by the moment when MailMessage.EncodeAllHeaders method was called.

In the sample above, we use the same UTF-8 charset and apply UTF-8 character encoding to the headers. Although you can use different charsets for different parts of the e-mail, there is usually no reason to do so.

Let's focus on the difference between charsets, encodings, and code pages. In short, they all mean the same but from different points of view. The charset is the string name for an encoding. The codepage is the integer index of an encoding. The encoding is an object.

For instance, System.Text.UTF8 is the Encoding object which allows for byte-to-string and string-to-byte conversions of UTF-8 encoded bytes. Its charset name is utf-8. Its codepage number is 65001. Thus, you can get the same object as System.Text.UTF8, System.Text.Encoding.GetEncoding("utf-8"), or System.Text.Encoding.GetEncoding(65001).

Note that the above describes encoding, charset and codepage in their .NET Framework meaning. For instance, Internet Explorer uses the "encoding" term to refer to a charset. There is no strict definition of these terms and they are often used interchangeably.

Content-transfer encodings

To make things even more tangled, there is also a content-transfer encoding term (typical examples are Base64 and Quoted-Printable). While the character encoding denotes how to convert strings (which are actually sequences of 16-bit Unicode characters) into 8-bit bytes, the content-transfer encoding denotes how to convert 8-bit bytes into 7-bit form. Many 8-bit codes are not allowed in e-mails (for instance, zero byte) and extra encoding is required to convert an arbitrary 8-bit byte into a certain value which would be safe for transfer via communication channels.

Base64 produces 4 (four) 7-bit bytes from every 3 (three) 8-bit bytes. It's effective when the data contains lots of unsafe characters (e.g. binary data or texts in non-Latin charsets). Base64 makes text unreadable.

Quoted-Printable uses a flexible method which leaves ASCII chars as-is (so that Latin text does not change) while unsafe chars are encoded. This method is the best when the text to be encoded contains mostly ASCII chars. Typical examples are texts written in Western European languages and documents which contain only small parts of non-Latin text. The Latin part of the text remains readable even after Quoted-Printable is applied. MailBee.NET uses Quoted-Printable as the default content-transfer encoding.

UTF-8 or local language-specific charset?

When you compose a message in local language, you always have at least two choices:

  • Use UTF-8 charset.
  • Use the charset specific to the language of the message. A few examples: windows-1252 (Western European Windows), windows-1255 (Hebrew Windows), iso-2022-jp (Japan ISO), etc.

The main advantage of UTF-8: it's universal. You can represent any text using this charset.

But in some cases you may still prefer a local charset. First of all, UTF-8 is not efficient in terms of the size of encoded data. The same text encoded in a local charset may be twice as short as its UTF-8 version. Also, some old e-mail readers still can't correctly display UTF-8. The local charset is fine when you know that your e-mail won't contain any characters outside this charset.

There is, however, a special case of HTML e-mails which adds yet another option which is described below.

HTML-encoded international characters ("&#xxxx;" sequences)

When creating HTML e-mails, you may opt not to use international characters at all and stick with ASCII charset by converting all international characters into their HTML-encoded representation. That is, &#1055;&#1088;&#1080;&#1074;&#1077;&#1090; HTML sequence represents "Привет" ("Hello" in Russian).

Pros:

  • No worries about charsets. International characters become "self-contained" and no longer rely on any external declaration of the charset.
  • Any character can be represented. Useful if the message is not UTF-8 (such as if some local charset is used, like windows-1251) and you need to display a character outside this local charset. For instance, your document includes "–" (en dash), but it's missing in windows-1251. You can replace it with &#150; HTML code.

Cons:

  • Works only for HTML. Plain-text does not support this syntax.
  • HTML-encoded sequences cannot be searched, indexed or otherwise processed as text until they are rendered in the browser. This may cause problems for recipients of your e-mails if they process these e-mails somehow.
  • HTML codes are pretty long and will significantly increase the size of the produced e-mail.

The best way of using HTML encoded sequences is when you need to display special characters (or strings which can be treated so). For instance, punctuation symbols, math symbols, quotes in Ancient Greek if they serve decoration purposes, and so on. Such strings do not require indexing as they do not contain any searchable text, and they usually do not take the most part of the document and thus won't significantly increase its size when HTML-encoded.

Thus, if your text contains 10.000 Cyrillic characters and 5 Western European symbols, you may use UTF-8 and it will work fine but the produced text will be about 30.000 bytes long (3 bytes per Cyrillic char in UTF-8). If you opt to use windows-1251 for Cyrillic characters and HTML encoding for the remaining 5 Western European symbols, you'll get slightly more than 10.000 bytes (1 byte per Cyrillic char in windows-1251).

Even if you do not care much about the size of produced e-mails, good understanding of charsets and HTML encodings may still help you to quickly and efficiently resolve issues related to storing and processing non-English data.

HTML META tag with charset declaration

When creating HTML e-mails, be aware of HTML META tag containing the charset declaration!

If your HTML includes a charset information in HTML META tag, that charset value must strictly match the charset you set with MailMessage.Charset property of the e-mail being composed.

This sample correctly sets both charset values (we assume Smtp.Message property denotes the e-mail to be sent):

  • C#
  • VB
mailer.Message.Charset = "windows-1252";
mailer.Message.BodyHtmlText =
    @"<meta http-equiv=Content-Type content=""text/html; charset=windows-1252"">";

mailer.Message.Charset = "windows-1252"
mailer.Message.BodyHtmlText = _
    "<meta http-equiv=Content-Type content=""text/html; charset=windows-1252"">"

Or, you can simply remove this meta tag at all since it's usually needed only for web pages. E-mail messages provide content-type and charset information in their own headers, no need to also duplicate it in HTML headers.

However, if you do not compose the HTML data manually but rather load it from an external source like HTML file or web page, you have no control of META tag and you may even not know what's in it. Moreover, you may not know the charset of the HTML data (because an HTML file does not have any headers like e-mails do).

In this case, META tag may be of a great help because it allows MailBee.NET to understand the charset encoding of the HTML data. When you import HTML data with MailMessage.LoadBodyText method, MailBee.NET automatically picks up the charset encoding from META tag (if it's there) and sets the charset of the produced HTML text part.

Thus, when loading HTML from a web page or file and that HTML already contains the charset information in META tag, you won't need to set MailMessage.Charset property manually. But what if you don't know if the HTML contains any charset information at all? This is meaningful question as HTML documents may freely contain no charset specification. In such case, you may want to specify the charset manually only when the charset is not specified by META tag:

  • C#
  • VB
// Import HTML body from a file.
mailer.Message.LoadBodyText(@"C:\Temp\example.html", MessageBodyType.Html);

// If the HTML contains charset specification in META tag,
// MailBee.NET will automatically assign it to the message.
// If the tag is not there, use UTF-8 charset for the message.
if (string.IsNullOrEmpty(mailer.Message.BodyParts.Html.Charset))
{
    mailer.Message.Charset = "utf-8";
}

' Import HTML body from a file.
mailer.Message.LoadBodyText("C:\Temp\example.html", MessageBodyType.Html)

' If the HTML contains charset specification in META tag,
' MailBee.NET will automatically assign it to the message.
' If the tag is not there, use UTF-8 charset for the message.
If String.IsNullOrEmpty(mailer.Message.BodyParts.Html.Charset) Then
    mailer.Message.Charset = "utf-8"
End If

It's recommended to use this approach whenever you load HTML content from external sources (rather than compose it manually).

Send plain-text e-mail with Chinese content and "utf-8" or "gb2312" charset

You can use UTF-8 to represent text written in any language. It's usually the only option to use if don't know the language of the text.

In case if you know that the text is in written in a certain language (let's say, Simplified Chinese), you can opt to use its local and more specific charset (like gb2312) which represents only the characters of its language and Latin. This makes the text encoded with a local codepage consume less space than encoded with UTF-8.

This sample uses either utf-8 or gb2312 charset to create a plain-text e-mail with headers and body containing Simplified Chinese:

  • C#
  • VB
Smtp mailer = new Smtp();

// This time, let's use logging just to remind that it's
// a very effective debug and trouble-shooting tool.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\log.txt";
mailer.Log.Clear();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "sender", "secret");

// Use this to produce UTF-8 e-mail.
mailer.Message.Charset = "utf-8";

// Or use this to produce Chinese-only e-mail.
mailer.Message.Charset = "gb2312";

// "寄件人" means "Sender".
mailer.Message.From = new EmailAddress("sender@domain.com", "寄件人");

// "收件人" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "收件人");

// Set subject and body.
mailer.Message.Subject = "科目 means Subject in Chinese";
mailer.Message.BodyPlainText = "文本 means Text in Chinese";

// Make sure all headers with non-Latin chars are encoded.
// System.Text.Encoding.GetEncoding(mailer.Message.Charset)
// is used because we don't know which charset you'll use
// (utf-8 or gb2312). If we knew it's, let's say, utf-8,
// we'd simply specify System.Text.Encoding.UTF8.
// Also note that we decided to encode with Base64 rather
// than with Quoted-Printable (default). Chinese texts
// (no matter utf-8 or gb2312) appear shorter in Base64 if
// compared to Quoted-Printable.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.GetEncoding(mailer.Message.Charset),
    HeaderEncodingOptions.Base64);

// For the same reason (to make the data size in bytes smaller), use
// Base64 instead of Quoted-Printable to encode the message body
// provided that is contains mostly non-Latin characters which consume
// a lot of space when encoded with Quoted-Printable. This is, however,
// just an optimization. We could leave Quoted-Printable as is.
mailer.Message.MailTransferEncodingPlain = MailTransferEncoding.Base64;

mailer.Send();

Dim mailer As Smtp = New Smtp

' This time, let's use logging just to remind that it's
' a very effective debug and trouble-shooting tool.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\log.txt"
mailer.Log.Clear()

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "sender", "secret")

' Use this to produce UTF-8 e-mail.
mailer.Message.Charset = "utf-8"

' Or use this to produce Chinese-only e-mail.
mailer.Message.Charset = "gb2312"

' "寄件人" means "Sender".
mailer.Message.From = New EmailAddress("sender@domain.com", "寄件人")

' "收件人" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "收件人")

' Set subject and body.
mailer.Message.Subject = "科目 means Subject in Chinese"
mailer.Message.BodyPlainText = "文本 means Text in Chinese"

' Make sure all headers with non-Latin chars are encoded.
' System.Text.Encoding.GetEncoding(mailer.Message.Charset)
' is used because we don't know which charset you'll use
' (utf-8 or gb2312). If we knew it's, let's say, utf-8,
' we'd simply specify System.Text.Encoding.UTF8.
' Also note that we decided to encode with Base64 rather
' than with Quoted-Printable (default). Chinese texts
' (no matter utf-8 or gb2312) appear shorter in Base64 if
' compared to Quoted-Printable.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.GetEncoding(mailer.Message.Charset),
    HeaderEncodingOptions.Base64)

' For the same reason (to make the data size in bytes smaller), use
' Base64 instead of Quoted-Printable to encode the message body
' provided that is contains mostly non-Latin characters which consume
' a lot of space when encoded with Quoted-Printable. This is, however,
' just an optimization. We could leave Quoted-Printable as is.
mailer.Message.MailTransferEncodingPlain = MailTransferEncoding.Base64

mailer.Send()

For HTML e-mails, make sure META tag either contains the correct charset or no charset information at all. See Send HTML e-mail with international characters topic for details.

Send plain-text e-mail with Windows-1252 headers (German characters in From, Subject, To)

We'll use windows-1252 charset in this example but we could have used UTF-8 either:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "sender", "secret");

// Change to utf-8 if you prefer UTF-8 charset.
mailer.Message.Charset = "windows-1252";

// "Absender" means "Sender".
mailer.Message.From = new EmailAddress("sender@domain.com", "Absender");

// "Empfänger" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "Empfänger");

// "The subject contains a special symbol" in German.
mailer.Message.Subject = "Das Thema enthält ein spezielles Symbol";

// "This text contains a special symbol" in German.
mailer.Message.BodyPlainText = "Dieser Text enthält ein spezielles Symbol";

// Make sure all headers with non-Latin chars are encoded.
// 1252 is the codepage number of windows-1252 charset.
// Should you need UTF-8, use 65001 codepage number or just
// System.Text.Encoding.UTF8 object.
// Also note that we decided to stay with Quoted-Printable
// (default) while the Chinese sample used Base64.
// Quoted-Printable is perfect if the text mostly contains
// Latin characters with rare occurrences of non-Latin ones.
// German is a typical "mostly Latin" language.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.GetEncoding(1252),
    HeaderEncodingOptions.Base64);

mailer.Send()

Dim mailer As Smtp = New Smtp

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "sender", "secret")

' Change to utf-8 if you prefer UTF-8 charset.
mailer.Message.Charset = "windows-1252"

' "Absender" means "Sender".
mailer.Message.From = New EmailAddress("sender@domain.com", "Absender")

' "Empfänger" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "Empfänger")

' "The subject contains a special symbol" in German.
mailer.Message.Subject = "Das Thema enthält ein spezielles Symbol"

' "This text contains a special symbol" in German.
mailer.Message.BodyPlainText = "Dieser Text enthält ein spezielles Symbol"

' Make sure all headers with non-Latin chars are encoded.
' 1252 is the codepage number of windows-1252 charset.
' Should you need UTF-8, use 65001 codepage number or just
' System.Text.Encoding.UTF8 object.
' Also note that we decided to stay with Quoted-Printable
' (default) while the Chinese sample used Base64.
' Quoted-Printable is perfect if the text mostly contains
' Latin characters with rare occurrences of non-Latin ones.
' German is a typical "mostly Latin" language.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.GetEncoding(1252),
    HeaderEncodingOptions.Base64)

mailer.Send()

You can use the same approach with any other local codepages and languages, not only Windows-1252 and German.

Send HTML e-mail with international characters

HTML format raises a number of considerations related to international characters and charsets:

  • With HTML, you can replace international characters with their &#xxxx; representation. However, it does not work for plain-text and that can be a problem if your HTML e-mails also provide plain-text version or it's auto-generated by MailBee.NET (the default behaviour). HTML-encoded international characters ("&#xxxx;" sequences) topic discusses this in more detail.
  • HTML text may contain its own charset declaration in META tag. If this charset does not match the charset you specified with MailMessage.Charset property of the e-mail being composed (denoted by Smtp.Message object), that e-mail won't be displayed properly. You should either not include the charset information in META tag or make sure it matches the value in MailMessage.Charset property. See HTML META tag with charset declaration topic for more information.

The sample below creates HTML e-mail in UTF-8 charset. However, the HTML data gets imported from a web page. If this data contains charset in META tag, that charset will be used for the message body (instead of UTF-8). The message headers will still be encoded in UTF-8:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "sender@domain.com", "secret");

// "Αποστολέας" means "Sender".
mailer.Message.From = new EmailAddress("sender@domain.com", "Αποστολέας");

// "Αποδέκτη" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "Αποδέκτη");

// Set subject and body.
mailer.Message.Subject = "Θέμα means Subject in Greek";

// Import HTML body from a web page. Detect encoding from meta tag.
// If meta tag is missing, MailBee.NET will assume windows-1253
// as it's Greek's the most popular codepage.
mailer.Message.LoadBodyText("http://www.domain.gr", MessageBodyType.Html,
    System.Text.Encoding.GetEncoding(1253),
    ImportBodyOptions.PathIsUri |
    ImportBodyOptions.PreferCharsetFromMetaTag);

// If the HTML contains charset specification in META tag,
// MailBee.NET will automatically assign it to the message.
// If the tag is not there, use UTF-8 charset for the message.
if (string.IsNullOrEmpty(mailer.Message.BodyParts.Html.Charset))
{
    mailer.Message.Charset = "utf-8";
}

// Let's use UTF-8 for headers regardless what charset will be used
// for the body parts. Use Base64 rather than Quoted-Printable as
// Greek phrases contain mosty non-Latin chars and their Base64
// representation will be shorter than Quoted-Printable.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.UTF8,
    HeaderEncodingOptions.Base64);

// Note that MailBee.NET will also create the plain-text version
// from the supplied HTML when the message gets built.
mailer.Send();

Dim mailer As Smtp = New Smtp

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.domain.com", "sender@domain.com", "secret")

' "Αποστολέας means "Sender".
mailer.Message.From = New EmailAddress("sender@domain.com", "Αποστολέας")

' "Αποδέκτη" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "Αποδέκτη")

' Set subject and body.
mailer.Message.Subject = "Θέμα means Subject in Greek"

' Import HTML body from a web page. Detect encoding from meta tag.
' If meta tag is missing, MailBee.NET will assume windows-1253
' as it's Greek's the most popular codepage.
mailer.Message.LoadBodyText("http://www.domain.gr", MessageBodyType.Html, _
    System.Text.Encoding.GetEncoding(1253), _
    ImportBodyOptions.PathIsUri Or _
    ImportBodyOptions.PreferCharsetFromMetaTag)

' If the HTML contains charset specification in META tag,
' MailBee.NET will automatically assign it to the message.
' If the tag is not there, use UTF-8 charset for the message.
If String.IsNullOrEmpty(mailer.Message.BodyParts.Html.Charset) Then
    mailer.Message.Charset = "utf-8"
End If

' Let's use UTF-8 for headers regardless what charset will be used
' for the body parts. Use Base64 rather than Quoted-Printable as
' Greek phrases contain mosty non-Latin chars and their Base64
' representation will be shorter than Quoted-Printable.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.UTF8,
    HeaderEncodingOptions.Base64)

' Note that MailBee.NET will also create the plain-text version
' from the supplied HTML when the message gets built.
mailer.Send()

As you can see, the sample does not encode international characters with &#xxxx; sequences. Instead, the correct charset is specified or determined from the META tag. This ensures that the plain-text version of the body will also have these international characters preserved (for plain-text, there is no other way to represent international characters except of using charsets).

Compose e-mail in right-to-left language like Hebrew

You can compose both plain-text and HTML e-mails in right-to-left languages like Arabic and Hebrew without any additional considerations. There are no special settings in MIME for right-to-left rendering, and e-mail reader programs automatically select the direction depending on the actual characters displayed.

You only need to specify the correct charset (UTF-8 or local language charset), just like you would do for any other international e-mail in left-to-right language:

  • C#
  • VB
// Set Hebrew's local codepage.
mailer.Message.Charset = "windows-1255";

// Set subject and body.
mailer.Message.Subject = "נושא means Subject in Hebrew";
mailer.Message.BodyPlainText = "טקסט means Text in Hebrew";

' Set Hebrew's local codepage.
mailer.Message.Charset = "windows-1255"

' Set subject and body.
mailer.Message.Subject = "נושא means Subject in Hebrew"
mailer.Message.BodyPlainText = "טקסט means Text in Hebrew"

With HTML e-mails, you may need to apply RTL attribute to certain HTML tags when building complex right-to-left documents but these are general HTML design concerns rather than e-mail specific issues. HTML design of right-to-left documents is beyond the scope of this guide.

Send e-mail with international characters in headers, body, attachment filenames

The sample below composes an international e-mail (Japanese) with the attachment which has Japanese filename. Nothing special here because MailMessage.EncodeAllHeaders method (which was widely used in previous samples) also encodes all non-Latin attachment filenames. Just be sure to call MailMessage.EncodeAllHeaders AFTER adding attachments, not BEFORE:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("mail.domain.com", "sender", "secret");

// Or we could have used "utf-8" as well.
mailer.Message.Charset = "iso-2022-jp";

// "送信者" means "Sender".
mailer.Message.From = new EmailAddress("sender@domain.com", "送信者");

// "受信者" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "受信者");

// Set subject.
mailer.Message.Subject = "題目 means Subject in Japanese";

// Set HTML body. MailBee.NET will generate plain-text version
// automatically (Japanese text will be converted correctly).
mailer.Message.BodyHtmlText =
    "<html><body>テキスト means Text in Japanese</body></html>";

// 1st attachment has normal Latin filename on the filesystem but it will
// have Japanese name in the e-mail.
mailer.Message.Attachments.Add(@"C:\Temp\12345678.tmp", "ドキュメント.doc");

// 2nd attachment has Japanese filename on the filesystem and will retain
// it in the e-mail.
mailer.Message.Attachments.Add(@"C:\Temp\イメージ.jpg");

// It's important to call this AFTER attachments have already been added.
mailer.Message.EncodeAllHeaders(
    System.Text.Encoding.GetEncoding(mailer.Message.Charset),
    HeaderEncodingOptions.Base64);

// Uncomment if the message body consists mainly of non-Latin (Japanese)
// chars to decrease the resulting message size. In the current sample,
// Base64 won't provide any benefit because most body chars are HTML tags
// with Latin content, and only few chars are Japanese. Thus, we left the
// default Quoted-Printable setting as is.

// mailer.Message.MailTransferEncodingPlain = MailTransferEncoding.Base64;
// mailer.Message.MailTransferEncodingHtml = MailTransferEncoding.Base64;

mailer.Send();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("mail.domain.com", "sender", "secret")

' Or we could have used "utf-8" as well.
mailer.Message.Charset = "iso-2022-jp"

' "送信者" means "Sender".
mailer.Message.From = New EmailAddress("sender@domain.com", "送信者")

' "受信者" means "Recipient".
mailer.Message.To.Add("recipient@company.com", "受信者")

' Set subject.
mailer.Message.Subject = "題目 means Subject in Japanese"

' Set HTML body. MailBee.NET will generate plain-text version
' automatically (Japanese text will be converted correctly).
mailer.Message.BodyHtmlText = _
    "<html><body>テキスト means Text in Japanese</body></html>"

' 1st attachment has normal Latin filename on the filesystem but it will
' have Japanese name in the e-mail.
mailer.Message.Attachments.Add("C:\Temp\12345678.tmp", "ドキュメント.doc")

' 2nd attachment has Japanese filename on the filesystem and will retain
' it in the e-mail.
mailer.Message.Attachments.Add("C:\Temp\イメージ.jpg")

' It's important to call this AFTER attachments have already been added.
mailer.Message.EncodeAllHeaders( _
    System.Text.Encoding.GetEncoding(mailer.Message.Charset), _
    HeaderEncodingOptions.Base64)

' Uncomment if the message body consists mainly of non-Latin (Japanese)
' chars to decrease the resulting message size. In the current sample,
' Base64 won't provide any benefit because most body chars are HTML tags
' with Latin content, and only few chars are Japanese. Thus, we left the
' default Quoted-Printable setting as is.

' mailer.Message.MailTransferEncodingPlain = MailTransferEncoding.Base64
' mailer.Message.MailTransferEncodingHtml = MailTransferEncoding.Base64

mailer.Send()

Also, MailMessage.EncodeAllHeaders method has an option NOT to encode attachment filenames, but you won't need it in most cases.

Send feedback to AfterLogic


Set From, Reply-To, Return-Path, To, CC, BCC, Priority and other headers in e-mail

  • Introduction
  • Set different From and Return-Path (use "real" sender address different from "From" address)
  • Send to undisclosed recipients (use "real" recipient addresses different from "To", "CC", "BCC" addresses)
  • Set "Request delivery confirmation" and "Request read confirmation" flags
  • Set Reply-To
  • Reply to message and set In-Reply-To and References headers
  • Set Importance, Priority, Sensitivity flags
  • Set custom Date and Message-ID values
  • Add custom headers

Introduction

MailBee.NET allows you to set any headers in the e-mail. For many headers, it also provides convenient methods to work with the header as a collection of objects, enumeration of constants, and so on. Some examples of such headers are such as To, CC, BCC, From, Importance, etc.

Header values which contain non-Latin or special characters can be automatically encoded with MailMessage.EncodeAllHeaders method. See Compose international e-mail guide for details.

Besides that, you can also work with any header value as a string to fully control how the header appears in the resulting e-mail. You can even add multiple headers with the same name (the MIME format allows this, and the typical example is "Received" headers).

This guide also explains SMTP envelopes and what differs them from message headers. The typical examples when SMTP envelopes get involved are when you send from the e-mail address different from "From" address, send to the recipients different from those specified in "To", "CC", "BCC", or request delivery confirmation.

Set different From and Return-Path (use "real" sender address different from "From" address)

Often, the sender of the e-mail ("Return-Path", "X-Sender") and its author ("From") are different e-mail addresses. The common reason for this is when you want bounce e-mails, auto-responders and other system-generated replies to your e-mail return to another address (such as bounce@domain.com) while the author's address is somewhat like newsletter@domain.com.

To explicitly specify the sender's address, use the method like Smtp.Send(string, string) and pass the sender's e-mail address as senderEmail parameter value:

  • C#
  • VB
Smtp mailer = new Smtp();

// For variety's sake, let's enable logging this time to remind
// that it's a very effective debug and trouble-shooting tool.
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Enabled = true;
mailer.Log.Clear();

// Use SMTP relay with authentication.
// Note that we authenticate as sender@domain.com, not as john.doe@domain.com!
mailer.SmtpServers.Add("mail.domain.com", "sender@domain.com", "secret");

// Set From address (author of the e-mail).
mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";

// Set body and other headers.
mailer.Message.To.AsString = "Jane Doe <jane@company.com>";
mailer.Message.Subject = "Items for sale";
mailer.Message.BodyPlainText = "2 new items in stock";

// Send from sender@domain.com.
mailer.Send("sender@domain.com", (string)null);

Dim mailer As Smtp = New Smtp()

' For variety's sake, let's enable logging this time to remind
' that it's a very effective debug and trouble-shooting tool.
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Enabled = True
mailer.Log.Clear()

' Use SMTP relay with authentication.
' Note that we authenticate as sender@domain.com, not as john.doe@domain.com!
mailer.SmtpServers.Add("mail.domain.com", "sender@domain.com", "secret")

' Set From address (author of the e-mail).
mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"

' Set body and other headers.
mailer.Message.To.AsString = "Jane Doe <jane@company.com>"
mailer.Message.Subject = "Items for sale"
mailer.Message.BodyPlainText = "2 new items in stock"

' Send from sender@domain.com.
mailer.Send("sender@domain.com", CType(Nothing, String))

All samples in this guide assume MailBee, MailBee.Mime, and MailBee.SmtpMail namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

The sample above composes the message as usually. However, when transmitting the message data to the SMTP server, the client uses the explicitly specified sender's address rather than the address taken from "From" header.

The sender address is not physically a part of MIME data of an e-mail. It's a part of somewhat called SMTP envelope for an e-mail. SMTP envelope consists of a series of SMTP commands which denote the sender, the recipients, and the MIME message data. In particular, when the client submits the message to the SMTP server, it sends the sender's address in MAIL FROM command. For instance, when you do not explicitly set the sender's address, MailBee.NET issues MAIL FROM:<From@address> where From@address denotes mailer.Message.From.Email value (assuming that mailer is Smtp instance).

Why the real sender's e-mail address is often called Return-Path? The SMTP server may add this header when it receives the message from the client. In other words, Return-Path indeed denotes the real sender but only "post factum". You can examine it in the e-mails you received from the e-mail server but it won't work if you try to set it for an outgoing e-mail to specify the real sender.

There is, however, the special header X-Sender which may in part serve the purpose of setting the real sender directly in the message headers. The problem with SMTP envelopes is that they are not part of message data. For instance, if you load the message from an .EML file, you have no SMTP envelope information.

To overcome this, some e-mail systems use X-Sender header so that the e-mail address specified in X-Sender will be used as the real sender during transmitting the message to the server. This provides the method of storing SMTP envelope information in message headers. Microsoft IIS SMTP server supports this, and so MailBee.NET Queue application does.

Smtp class does not automatically try to send from X-Sender address but you can examine this header after loading the message from the file and use its value when calling Smtp.Send(string, string) method as shown in the sample code above.

Many e-mail servers don't like when the real sender's address is not specified in the message headers. In theory, the SMTP server shouldn't even look into the MIME data and transmit it as-is. In practice, spammers often forge "From:" e-mail address and send from e-mail accounts which are not even close to what's specified in From (e.g. "From:" looks like jdoe@domain.com while real sender is somewhat like xxx34523@middleofnowhere.com).

Thus, it's recommended to include into the message yet another header (usually, Sender), which has no special meaning but just lets the SMTP server know we're not willing to hide the identify of the real sender. Adding this header is especially important if "From:" and the real sender belong to different domains.

You can add Sender header as below:

  • C#
  • VB
mailer.Message.Sender = "sender@domain.com";

mailer.Message.Sender = "sender@domain.com"

In some special cases, when you need to re-send the message to another address with no changes to its "From:" field (so that your recipient would see not "From:" of yours but the original "From:"), you may add Resent-From header and specify your own "From:" address there. Otherwise, the SMTP server might think that you're trying to spoof someone else's "From:" address and hide your own.

Send to undisclosed recipients (use "real" recipient addresses different from "To", "CC", "BCC" addresses)

If you just want to send e-mail to multiple recipients without disclosing their e-mail addresses to each other, you can list them in BCC. However, if your task is more specific, BCC may not always work for you.

For instance, if you want to have some recipients listed in "To:" but the e-mail should not go to them. The most typical case is when "To:" field must contain somewhat like "undisclosed recipients".

MailBee.NET can ignore To, CC, BCC values and use the explicitly specified recipients:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("mail.provider.com", "jdoe@here.com", "secret");

// Set From address (will also use it as real sender's address).
mailer.Message.From.AsString = "John Doe <jdoe@here.com>";

// Set "To" but do not list any actual recipients there.
mailer.Message.To.AsString = "undisclosed recipients";

// Set other fields.
mailer.Message.Subject = "Notification";
mailer.Message.BodyPlainText = "Meet at midnight";

// Create the actual list of recipients.
EmailAddressCollection emails = new EmailAddressCollection();
emails.Add("mr.x@somewhere.com");
emails.Add("mrs.y@nowhere.com");
emails.Add("mr.z@elsewhere.com");

// Send to real recipients. We could also use comma-separated string
// of e-mail addresses rather than EmailAddressCollection object.
mailer.Send(null, emails);

Dim mailer As Smtp = New Smtp()

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("mail.provider.com", "jdoe@here.com", "secret")

' Set From address (will also use it as real sender's address).
mailer.Message.From.AsString = "John Doe <jdoe@here.com>"

' Set "To" but do not list any actual recipients there.
mailer.Message.To.AsString = "undisclosed recipients"

' Set other fields.
mailer.Message.Subject = "Notification"
mailer.Message.BodyPlainText = "Meet at midnight"

' Create the actual list of recipients.
Dim emails As EmailAddressCollection = New EmailAddressCollection()
emails.Add("mr.x@somewhere.com")
emails.Add("mrs.y@nowhere.com")
emails.Add("mr.z@elsewhere.com")

' Send to real recipients. We could also use comma-separated string
' of e-mail addresses rather than EmailAddressCollection object.
mailer.Send(Nothing, emails)

When you explicitly specify recipients, MailBee.NET does not use To, CC, and BCC when submitting recipients to the SMTP server with RCPT TO commands.

The list of real recipients is the part of SMTP envelope, not of the e-mail message itself (see Set different From and Return-Path (use "real" sender address different from "From" address) topic on more details regarding SMTP envelopes). If you need to somehow keep the real recipients information in the e-mail (for instance, if you need to save the message in .EML file and then restore it from that file), you can place this information in BCC, and later read that header when loading the message from file and pass its value to Smtp.Send(string, string) method.

The above works if you have the full control over the application which sends e-mail (e.g. if you can implement reading from BCC and using that value as "real recipients list"). In case if you submit the message file to an external system like Microsoft IIS SMTP service or MailBee.NET Queue, use X-Receiver headers for that. Smtp.SubmitToPickupFolder Method(string, string, string, string, bool) method can do the job:

  • C#
  • VB
mailer.SubmitToPickupFolder(@"C:\Inetpub\mailroot\Pickup", null, null, emails, true);

mailer.SubmitToPickupFolder("C:\Inetpub\mailroot\Pickup", Nothing, Nothing, emails, True)

emails can be a comma-separated string or EmailAddressCollection object.

Set "Request delivery confirmation" and "Request read confirmation" flags

This code snippet enables MailBee.NET to notify the receiving part to send delivery and reading confirmation to the specified e-mail address:

  • C#
  • VB
// Set Disposition-Notification-To header.
mailer.Message.ConfirmRead = "john.doe@company.com";

// Set Return-Receipt-To header.
mailer.Message.ConfirmReceipt = "john.doe@company.com";

// Configure Delivery Status Notification (DSN).
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always;

' Set Disposition-Notification-To header.
mailer.Message.ConfirmRead = "john.doe@company.com"

' Set Return-Receipt-To header.
mailer.Message.ConfirmReceipt = "john.doe@company.com"

' Configure Delivery Status Notification (DSN).
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always

To send delivery confirmation to the specified e-mail address, the e-mail server of the receiving part must support Return-Receipt-To header.

To send reading confirmation to the specified e-mail address, the e-mail client program of the recipient must support Disposition-Notification-To header.

If the e-mail server you're relaying through and the recipient's server both support ESMTP DSN extension, you'll get delivery status notification in case if the e-mail was or wasn't delivered. This notification will be sent to "From:" address or to the actual sender address if you set it explicitly. The address specified in mailer.Message.ConfirmRead or mailer.Message.ConfirmReceipt headers is not used by DSN.

If the e-mail server also supports both Return-Receipt-To header and ESMTP DSN, you may get two delivery notifications of the same event if you enabled both options.

To learn more on how you can request reading and delivery confirmations, assign Tracking ID to each e-mail to simplify processing of bounced messages, and otherwise configure delivery notifications, refer to Request delivery and reading confirmation guide.

Set Reply-To

If you're creating an e-mail and want to specify "Reply-To:" address different from "From:" address, set mailer.Message.ReplyTo value. It's assumed that mailer is an Smtp instance and its Smtp.Message property denotes the MailMessage object to be sent.

You can also specify multiple addresses in Reply-To. To learn more, see MailMessage.ReplyTo property documentation.

The code snippet below adds two Reply-To addresses in different ways (with and without display name):

  • C#
  • VB
mailer.Message.ReplyTo.Add("john.doe@domain.com", "John Doe");
mailer.Message.ReplyTo.Add("jane.doe@domain.com");

mailer.Message.ReplyTo.Add("john.doe@domain.com", "John Doe")
mailer.Message.ReplyTo.Add("jane.doe@domain.com")

You can also specify Reply-To value as a string with mailer.Message.ReplyTo.AsString = "John Doe <jdoe@domain.com>" syntax.

Reply to message and set In-Reply-To and References headers

To reply to an existing e-mail (which you received from, let's say, IMAP or POP3 server) and make it easier for the receiving side to match the original message and its reply, do the following:

  • Add Message-ID of the original message (which is being replied) to In-Reply-To header of the reply. Now the receiving part knows for which e-mail your reply is.
  • Copy the value of References header from the original message to the reply and append Message-ID of the original message there. The only difference from In-Reply-To is that we not only add Message-ID of the original message but also preserve Message-IDs of earlier messages in the same thread. This simplifies grouping e-mails in conversations because References will contain the entire history of each conversation.

For References to work well, the other party (the recipient's mail program) must behave the same way when replying to your e-mail (i.e. it must add your e-mail's Message-ID to References of the reply e-mail).

The sample below receives the last e-mail in inbox from IMAP server, and replies it. When making the reply, the sample adds Message-ID of the original e-mail to In-Reply-To and extends References:

  • C#
  • VB
// Download the last e-mail from inbox.
MailMessage originalMsg = MailBee.ImapMail.Imap.QuickDownloadMessage(
    "imap.example.com", "user", "password", "Inbox", -1);

Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.example.com", "user", "password");

// Set subject and body of the reply.
mailer.Message.Subject = "Re: " + originalMsg.Subject;
mailer.Message.BodyPlainText = "Your message was received";

// Refer the original message with In-Reply-To header.
mailer.Message.Headers["In-Reply-To"] = originalMsg.MessageID;

// Refer the entire thread with References header.
if (string.IsNullOrEmpty(originalMsg.References))
{
    mailer.Message.References = originalMsg.MessageID;
}
else
{
    mailer.Message.References = originalMsg.References +
        " " + originalMsg.MessageID;
}

// Set From address.
mailer.Message.From.Email = "john.doe@company.com";
mailer.Message.From.DisplayName = "John Doe";

// Take the recipient from the original message's "From".
mailer.Message.To.Add(originalMsg.From);

// Send the reply!
mailer.Send();

' Download the last e-mail from inbox.
Dim originalMsg As MailMessage = MailBee.ImapMail.Imap.QuickDownloadMessage( _
    "imap.example.com", "user", "password", "Inbox", -1)

Dim mailer As Smtp = New Smtp()

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.example.com", "user", "password")

' Set subject and body of the reply.
mailer.Message.Subject = "Re: " + originalMsg.Subject
mailer.Message.BodyPlainText = "Your message was received"

' Refer the original message with In-Reply-To header.
mailer.Message.Headers("In-Reply-To") = originalMsg.MessageID

' Refer the entire thread with References header.
If String.IsNullOrEmpty(originalMsg.References) Then
    mailer.Message.References = originalMsg.MessageID
Else
    mailer.Message.References = originalMsg.References & _
        " " & originalMsg.MessageID
End If

' Set From address.
mailer.Message.From.Email = "john.doe@company.com"
mailer.Message.From.DisplayName = "John Doe"

' Take the recipient from the original message's "From".
mailer.Message.To.Add(originalMsg.From)

' Send the reply!
mailer.Send()

In many cases it's enough to specify just In-Reply-To header. References is more "optional" in this regard.

Set Importance, Priority, Sensitivity flags

Let's assign top priority and importance, and also mark the e-mail as confidential:

  • C#
  • VB
mailer.Message.Priority = MailPriority.Highest;
mailer.Message.Importance = MailPriority.Highest;
mailer.Message.Sensitivity = MailSensitivity.Confidential;

mailer.Message.Priority = MailPriority.Highest
mailer.Message.Importance = MailPriority.Highest
mailer.Message.Sensitivity = MailSensitivity.Confidential

It's assumed that mailer is an Smtp object instance and its Smtp.Message property denotes the MailMessage object to be sent.

Set custom Date and Message-ID values

By default, MailBee.NET generates Date and Message-ID values automatically when the e-mail gets sent or submitted as .EML file to MailBee.NET Queue or Microsoft IIS Pickup service.

The default Date value denotes the very moment when the message gets sent. Sometimes, you may want to correct it (e.g. specify the moment when the message was composed if you do not intend to send it immediately).

The default Message-ID value uses the computer's name in the domain part. You may wish to avoid this (e.g. use your company's domain name instead).

To achieve this, you can set Date and/or Message-ID manually and tell MailBee.NET not to generate these values automatically:

  • C#
  • VB
// Assign the date manually (automatic date setting
// would be DateTime.Now instead of DateTime.Today).
mailer.Message.Date = DateTime.Today;
mailer.Message.Builder.SetDateOnSend = false;

// Assign Message-ID manually (automatic setting
// would use the local computer name as domain.
mailer.Message.SetUniqueMessageID("company.com");
mailer.Message.Builder.SetMessageIDOnSend = false;

' Assign the date manually (automatic date setting
' would be DateTime.Now instead of DateTime.Today).
mailer.Message.Date = DateTime.Today
mailer.Message.Builder.SetDateOnSend = False

' Assign Message-ID manually (automatic setting
' would use the local computer name as domain.
mailer.Message.SetUniqueMessageID("company.com")
mailer.Message.Builder.SetMessageIDOnSend = False

Note that if you disabled automatic setting of Date and/or Message-ID and didn't specify them manually, the message will be sent without these headers at all. This can make sense if you wish your SMTP relay server to add these headers (some servers can do this).

For instance, if you submit e-mails to the pickup folder for later delivery, the actual e-mails can get sent hours later since they have been created. Thus, if Date is generated by MailBee.NET at the moment when the e-mail is created and put into the pickup folder, it's Date might be several hours earlier than the actual moment of sending. Some spam filters don't like this and such e-mail can be blocked.

However, if you let your SMTP relay server generate Date for your e-mails, this will occur at the very moment of sending (when the message gets processed from its pickup folder), and the Date value will be relevant.

Add custom headers

You can add your own headers to the message and to any of its parts (e.g. custom headers for attachment). You can also add multiple headers with the same name (for instance, to add new Received header in addition to those which are already in the message).

If you invent your own header, it's better to prefix its name with "X-" and use dash symbol ("-") to separate words in the name.

The sample below adds to the message a few custom headers in different ways (one of them has international characters in its value and therefore encoded). The sample also adds an attachment with custom headers:

  • C#
  • VB
// Add a custom header. If the header with such name already exists,
// overwrite it instead of adding another header with the same name.
mailer.Message.Headers.Add("X-Ref-ID", "8234892", true);

// Add 3 custom headers with the same name. They will form the coherent text.
mailer.Message.Headers.Add("X-Text", "Next line is in Czech", false);

// We also use international characters in 2nd header, and that's why we encode it.
string secondLineInCzech = MailMessage.GetEncodedHeaderValue(
    "X-Text", "Druhý řádek", System.Text.Encoding.UTF8, HeaderEncodingOptions.None);
mailer.Message.Headers.Add("X-Text", secondLineInCzech, false);

// Add the last X-Text header.
mailer.Message.Headers.Add("X-Text", "Its translation is \"Second line\"", false);

// Add a lengthy header to demonstrate line wrapping.
mailer.Message.Headers.Add("X-Long-Line", "This text will be wrapped " +
    "into multiple lines because it's pretty long (much longer than 76 " +
    "characters which is the recommended limit of the line length in MIME", true);

// Add a header at the top of MIME data.
mailer.Message.Headers.Add("X-Top",
    "This will appear at the top of the message source", true, 0);

// Add a custom header to the attachment.
HeaderCollection attachmentHeaders = new HeaderCollection();
attachmentHeaders.Add("Content-Hash", "2D59A090", true);
mailer.Message.Attachments.Add(@"C:\Temp\report.doc", null, null, null,
    attachmentHeaders, NewAttachmentOptions.None, MailTransferEncoding.Base64);

' Add a custom header. If the header with such name already exists,
' overwrite it instead of adding another header with the same name.
mailer.Message.Headers.Add("X-Ref-ID", "8234892", True)

' Add 3 custom headers with the same name. They will form the coherent text.
mailer.Message.Headers.Add("X-Text", "Next line is in Czech", False)

' We also use international characters in 2nd header, and that's why we encode it.
Dim secondLineInCzech As String = MailMessage.GetEncodedHeaderValue( _
    "X-Text", "Druhý řádek", System.Text.Encoding.UTF8, HeaderEncodingOptions.None)
mailer.Message.Headers.Add("X-Text", secondLineInCzech, False)

' Add the last X-Text header.
mailer.Message.Headers.Add("X-Text", "Its translation is ""Second line""", False)

' Add a lengthy header to demonstrate line wrapping.
mailer.Message.Headers.Add("X-Long-Line", "This text will be wrapped " & _
    "into multiple lines because it's pretty long (much longer than 76 " & _
    "characters which is the recommended limit of the line length in MIME", True)

' Add a header at the top of MIME data.
mailer.Message.Headers.Add("X-Top", _
    "This will appear at the top of the message source", True, 0)

' Add a custom header to the attachment.
Dim attachmentHeaders As HeaderCollection = New HeaderCollection()
attachmentHeaders.Add("Content-Hash", "2D59A090", True)
mailer.Message.Attachments.Add("C:\Temp\report.doc", Nothing, Nothing, Nothing, _
    attachmentHeaders, NewAttachmentOptions.None, MailTransferEncoding.Base64)

It's assumed that mailer is an Smtp object instance and its Smtp.Message property denotes the MailMessage object to be sent.

Send feedback to AfterLogic


Mail merge and bulk mail

  • Mail merge in MailBee.NET
  • Bulk mail, explained
  • Error processing in bulk mail operations
  • Send series of e-mails based on template and database
  • Mail merge with post processing
  • Monitor mail merge progress and track successful and failed sendings
  • Submit e-mails generated with mail merge to MailBee.NET Queue

Mail merge in MailBee.NET

Mail merge is a process of generating a series of e-mail messages based on a single template and a data source. The data source (database table, SQL query and so on) delivers the data rows which are applied to the template to produce e-mail messages.

In most cases, you'll use mail merge over database so that the names of data table columns will be used as pattern names. Thus, if the message body contains ##item_name## and there is the data table column named item_name, MailBee.NET will replace ##item_name## in the message body with the value in the data table denoted by the current row and the column named item_name. Both plain-text and HTML bodies can contain patterns.

You can use patterns not only in the body and headers but also in attachment filenames, Delivery Status Notification (DSN) settings, e-mail addresses of actual recipients and sender (if it's different from From address). This guide covers most of these matters. Using templates in DSN is explained in another guide, see Fine-tune ESMTP DSN and assign Tracking ID to e-mail topic.

Also, MailBee.NET provides the mechanism of implementing mail merge manually. It allows for a greater control over the mail merge process and can be used if the data source cannot be represented as aSystem.Data.DataTable or System.Data.IDataReader object. To learn more, refer to MailMerge object documentation.

The e-mails generated with mail merge can be sent immediately or submitted to a mail queue like Microsoft IIS SMTP Pickup service or MailBee.NET Queue.

The mail merge mechanism can generate and send unlimited number of e-mails even the size of RAM memory of the server does not allow to fit all the e-mails generated during mail merge. This is because mail merge occurs in a memory conservative way: the data row gets merged with the template, the e-mail is built, sent and then freed when it comes to the next data row. In multi-threaded mode, the number of e-mails being simultaneously in memory is the number of active threads but it's still limited.

Bulk mail, explained

Bulk mail denotes sending large volumes of e-mails. Although the source of bulk mail is usually the messages generated with mail merge (mail merge can produce thousands of individual e-mails), you can also use bulk mail facilities of MailBee.NET to send e-mails crafted manually.

In MailBee.NET, the source of bulk mail is jobs (SendMailJob objects). The job represents a task of sending a single e-mail or mail merge series. For instance, when you call Smtp.SendMailMerge method to create and send a series of e-mails with mail merge, MailBee.NET actually creates a SendMailJob of mail merge type and executes it.

This guide uses bulk mail only in conjunction with mail merge. For examples on how to send lots of individual e-mails not using mail merge, refer to Send multiple individual e-mails or send through multiple servers guide.

Error processing in bulk mail operations

The error processing in case of bulk mail operations (including mail merge) is different as compared to sending a single e-mail.

If you send a single e-mail and it fails, that's an error, no question here, and MailBee.NET throws an exception then. But in case of multiple e-mails being sent, failure of a single e-mail shouldn't always stop the entire bulk mail operation.

MailBee.NET lets your application stay informed about the failures of individual e-mails without interrupting the whole process by using events. See Monitor mail merge progress and track successful and failed sendings topic for details.

Send series of e-mails based on template and database

This console sample creates the data table containing two rows, and performs mail merge over it. Note that the mail merge process also involves attaching a file which name is a pattern (so that it will attach different files for different data rows):

  • C#
  • VB
using System;
using System.Data;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Create DataTable with some data. In real-world apps,
    // you'll get the data from external sources like SQL query.
    private static DataTable GetData()
    {
        DataTable workTable = new DataTable("customers");

        DataColumn workCol = workTable.Columns.Add("id", typeof(int));
        workCol.AllowDBNull = false;
        workCol.Unique = true;

        workTable.Columns.Add("name", typeof(string));
        workTable.Columns.Add("email", typeof(string));
        workTable.Columns.Add("doc_id", typeof(int));
        workTable.Columns.Add("doc_name", typeof(string));

        // Add two rows to the data source. This way,
        // the mail merge procedure will generate two e-mails.
        DataRow row = workTable.NewRow();
        row["id"] = 1;
        row["name"] = "John Doe";
        row["email"] = "john.doe@company.com";
        row["doc_id"] = 637;
        row["doc_name"] = "annual report.xls";
        workTable.Rows.Add(row);

        row = workTable.NewRow();
        row["id"] = 2;
        row["name"] = "Bob Brown";
        row["email"] = "bob.brown@example.com";
        row["doc_id"] = 2358;
        row["doc_name"] = "agreement draft.pdf";
        workTable.Rows.Add(row);

        return workTable;
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Because mail merge does not throw exceptions, you need to
        // subscribe to ErrorOccurred event or check the log for errors.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Clear();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret");

        // Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>";
        mailer.Message.Subject = "Information";

        // Set templates for To, body, and attachment.
        mailer.Message.To.AsString = "##name## <##email##>";
        mailer.Message.BodyHtmlText = "Attachment for <i>##name##</i>";

        // You may comment this line out if you don't need attacments.
        // Otherwise, you'll need to add "annual report.xls" and
        // "agreement draft.pdf" into "C:\Docs" folder.
        mailer.Message.Merge.AddAttachmentPattern(@"C:\Docs\##doc_name##");

        // Generate and send e-mails.
        mailer.SendMailMerge(null, null, GetData());
    }
}

Imports System
Imports System.Data
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    ' Create DataTable with some data. In real-world apps,
    ' you'll get the data from external sources like SQL query.
    Private Function GetData() As DataTable
        Dim workTable As New DataTable("customers")

        Dim workCol As DataColumn = workTable.Columns.Add("id", GetType(Integer))
        workCol.AllowDBNull = False
        workCol.Unique = True

        workTable.Columns.Add("name", GetType(String))
        workTable.Columns.Add("email", GetType(String))
        workTable.Columns.Add("doc_id", GetType(Integer))
        workTable.Columns.Add("doc_name", GetType(String))

        ' Add two rows to the data source. This way,
        ' the mail merge procedure will generate two e-mails.
        Dim row As DataRow = workTable.NewRow()
        row("id") = 1
        row("name") = "John Doe"
        row("email") = "john.doe@company.com"
        row("doc_id") = 637
        row("doc_name") = "annual report.xls"
        workTable.Rows.Add(row)

        row = workTable.NewRow()
        row("id") = 2
        row("name") = "Bob Brown"
        row("email") = "bob.brown@example.com"
        row("doc_id") = 2358
        row("doc_name") = "agreement draft.pdf"
        workTable.Rows.Add(row)

        Return workTable
    End Function

    Sub Main()
        Dim mailer As New Smtp()

        ' Because mail merge does not throw exceptions, you need to
        ' subscribe to ErrorOccurred event or check the log for errors.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Clear()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret")

        ' Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>"
        mailer.Message.Subject = "Information"

        ' Set templates for To, body, and attachment.
        mailer.Message.To.AsString = "##name## <##email##>"
        mailer.Message.BodyHtmlText = "Attachment for <i>##name##</i>"

        ' You may comment this line out if you don't need attacments.
        ' Otherwise, you'll need to add "annual report.xls" and
        ' "agreement draft.pdf" into "C:\Docs" folder.
        mailer.Message.Merge.AddAttachmentPattern("C:\Docs\##doc_name##")

        ' Generate and send e-mails.
        mailer.SendMailMerge(Nothing, Nothing, GetData())
    End Sub
End Module

Here and below, we assume that MailBee.NET SMTP license key is already set in app.config, web.config or Windows Registry. See Import namespaces and set license key topic for details.

Also, the sample needs annual report.xls and agreement draft.pdf files in C:\Docs folder. If the files are not there, you won't see any exception, the e-mails will just not be sent. Refer to Monitor mail merge progress and track successful and failed sendings topic to learn why.

There is also an async version of this sample in Send multiple e-mails asynchronously topic.

Mail merge with post processing

You can use events to post-process the e-mail message after it has been generated with mail merge but before it gets sent. For instance, if you want to sign it with DKIM or S/MIME signature (see "Other notes" section in Sign e-mail with DomainKeys and DKIM topic to get the idea).

The sample below differs from the previous sample in one thing: the attachment filename on disk is different from the attachment filename as it must appear in the message (for instance, if you're attaching temp files which don't have meaningful names on the filesystem). MailMerge.AddAttachmentPattern method won't work in this case as it does not allow you to specify different "real" and "target" filenames. That's how you can overcome this with events:

  • C#
  • VB
using System;
using System.Data;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Create DataTable with some data. In real-world apps,
    // you'll get the data from external sources like SQL query.
    private static DataTable GetData()
    {
        DataTable workTable = new DataTable("customers");

        DataColumn workCol = workTable.Columns.Add("id", typeof(int));
        workCol.AllowDBNull = false;
        workCol.Unique = true;

        workTable.Columns.Add("name", typeof(string));
        workTable.Columns.Add("email", typeof(string));
        workTable.Columns.Add("doc_id", typeof(int));
        workTable.Columns.Add("doc_name", typeof(string));

        // Add two rows to the data source. This way,
        // the mail merge procedure will generate two e-mails.
        DataRow row = workTable.NewRow();
        row["id"] = 1;
        row["name"] = "John Doe";
        row["email"] = "john.doe@company.com";
        row["doc_id"] = 637;
        row["doc_name"] = "annual report.xls";
        workTable.Rows.Add(row);

        row = workTable.NewRow();
        row["id"] = 2;
        row["name"] = "Bob Brown";
        row["email"] = "bob.brown@example.com";
        row["doc_id"] = 2358;
        row["doc_name"] = "agreement draft.pdf";
        workTable.Rows.Add(row);

        return workTable;
    }

    // After mail merge produced the message, we manually attach a file
    // as we need it to have different "real" (on the filesystem) and
    // "target" (in the e-mail) filenames.
    static void OnSending(object sender, SmtpSendingMessageEventArgs e)
    {
        e.MailMessage.Attachments.Add(@"C:\Docs\" +
            e.MergeTable.Rows[e.MergeRowIndex]["doc_id"].ToString() + ".tmp",
            e.MergeTable.Rows[e.MergeRowIndex]["doc_name"].ToString());
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret");

        // Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>";
        mailer.Message.Subject = "Information";

        // Set templates for To and body.
        mailer.Message.To.AsString = "##name## <##email##>";
        mailer.Message.BodyHtmlText = "Attachment for <i>##name##</i>";

        // Subscribe to the event which raises each time
        // the message is about to be sent.
        mailer.SendingMessage +=
            new SmtpSendingMessageEventHandler(OnSending);

        // Generate and send e-mails.
        mailer.SendMailMerge(null, null, GetData());
    }
}

Imports System
Imports System.Data
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    ' Create DataTable with some data. In real-world apps,
    ' you'll get the data from external sources like SQL query.
    Function GetData() As DataTable
        Dim workTable As New DataTable("customers")

        Dim workCol As DataColumn = workTable.Columns.Add("id", GetType(Integer))
        workCol.AllowDBNull = False
        workCol.Unique = True

        workTable.Columns.Add("name", GetType(String))
        workTable.Columns.Add("email", GetType(String))
        workTable.Columns.Add("doc_id", GetType(Integer))
        workTable.Columns.Add("doc_name", GetType(String))

        ' Add two rows to the data source. This way,
        ' the mail merge procedure will generate two e-mails.
        Dim row As DataRow = workTable.NewRow()
        row("id") = 1
        row("name") = "John Doe"
        row("email") = "john.doe@company.com"
        row("doc_id") = 637
        row("doc_name") = "annual report.xls"
        workTable.Rows.Add(row)

        row = workTable.NewRow()
        row("id") = 2
        row("name") = "Bob Brown"
        row("email") = "bob.brown@example.com"
        row("doc_id") = 2358
        row("doc_name") = "agreement draft.pdf"
        workTable.Rows.Add(row)

        Return workTable
    End Function

    ' After mail merge produced the message, we manually attach a file
    ' as we need it to have different "real" (on the filesystem) and
    ' "target" (in the e-mail) filenames.
    Sub OnSending(ByVal sender As Object, ByVal e As SmtpSendingMessageEventArgs)
        e.MailMessage.Attachments.Add("C:\Docs\" & _
            e.MergeTable.Rows(e.MergeRowIndex)("doc_id").ToString() & ".tmp", _
            e.MergeTable.Rows(e.MergeRowIndex)("doc_name").ToString())
    End Sub

    Sub Main()
        Dim mailer As New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret")

        ' Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>"
        mailer.Message.Subject = "Information"

        ' Set templates for To and body.
        mailer.Message.To.AsString = "##name## <##email##>"
        mailer.Message.BodyHtmlText = "Attachment for <i>##name##</i>"

        ' Subscribe to the event which raises each time
        ' the message is about to be sent.
        AddHandler mailer.SendingMessage, AddressOf OnSending

        ' Generate and send e-mails.
        mailer.SendMailMerge(Nothing, Nothing, GetData())
    End Sub
End Module

As you can see, the sample needs 637.tmp and 2358.tmp files in C:\Docs folder.

Note that if OnSending method throws an exception (for instance, the file with the given filename was not found or whatever), MailBee.NET will catch it. See below why, and how to deal with errors and exceptions in case of sending bulk mail.

Monitor mail merge progress and track successful and failed sendings

Although you can set Smtp.StopJobsOnError to true in case if you want bulk mail operation to stop as soon as any e-mail in the bulk fails, you'll mostly use this for debugging. In production, it's not convenient to have the whole process to stop in case of failure of a single e-mail. Still, you need to somehow track the failed e-mails and the reasons of the occurred errors.

During the bulk mail operation, you can use Smtp.ErrorOccurred and Smtp.MessageNotSent events to get notified of any problems.

After the bulk mail operation, you can examine Smtp.JobsFailed collection to find out which e-mails haven't been processed. The exact approach of using Smtp.JobsFailed property depends on whether the bulk mail operation was a mail merge or a batched sending of independent e-mails, but the key concept remains the same.

The sample below is the more advanced version of the previous sample (mail merge of attachments having different filenames on disk and in e-mail), with the extensive error handling:

  • C#
  • VB
using System;
using System.Data;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Create DataTable with some data. In real-world apps,
    // you'll get the data from external sources like SQL query.
    private static DataTable GetData()
    {
        DataTable workTable = new DataTable("customers");

        DataColumn workCol = workTable.Columns.Add("id", typeof(int));
        workCol.AllowDBNull = false;
        workCol.Unique = true;

        workTable.Columns.Add("name", typeof(string));
        workTable.Columns.Add("email", typeof(string));
        workTable.Columns.Add("doc_id", typeof(int));
        workTable.Columns.Add("doc_name", typeof(string));

        // Add two rows to the data source. This way,
        // the mail merge procedure will generate two e-mails.
        DataRow row = workTable.NewRow();
        row["id"] = 1;
        row["name"] = "John Doe";
        row["email"] = "john.doe@company.com";
        row["doc_id"] = 637;
        row["doc_name"] = "annual report.xls";
        workTable.Rows.Add(row);

        row = workTable.NewRow();
        row["id"] = 2;
        row["name"] = "Bob Brown";
        row["email"] = "bob.brown@example.com";
        row["doc_id"] = 2358;
        row["doc_name"] = "agreement draft.pdf";
        workTable.Rows.Add(row);

        return workTable;
    }

    // After mail merge produced the message, we manually attach a file
    // as we need it to have different "real" (on the filesystem) and
    // "target" (in the e-mail) filenames.
    static void OnSending(object sender, SmtpSendingMessageEventArgs e)
    {
        e.MailMessage.Attachments.Add(@"C:\Docs\" +
            e.MergeTable.Rows[e.MergeRowIndex]["doc_id"].ToString() + ".tmp",
            e.MergeTable.Rows[e.MergeRowIndex]["doc_name"].ToString());
    }

    // Raises in many cases. Does not necessarily indicates the e-mail wasn't
    // sent. For instance, if you're using main and fail-over backup SMTP servers
    // and the main server is down, you'll get OnError stating about that, but
    // then the message can still get sent through the fail-over server.
    static void OnError(object sender, ErrorEventArgs e)
    {
        if (e.Reason is MailBeeExternalException)
        {
            Console.WriteLine(
                "OnError: Some of your event handlers has thrown an exception.");
            Console.WriteLine("The details: " + e.Reason.Message);
            Console.WriteLine();
        }
        else if (e.Reason is MailBeeNetworkException)
        {
            // Do nothing because OnNotSent will take care of failed messages.
            // ErrorOccurred event is not so reliable when it comes to
            // MailBeeNetworkException which may occur multiple times with
            // fail-over servers and the e-mail can still get delivered.
            // Other, non-MailBeeNetworkException errors, are definitive and
            // non-recoverable. If a non-MailBeeNetworkException error has
            // occurred for a certain e-mail, you can count on that the
            // operation won't be retried and probably succeed for the second
            // time (like it's possible with MailBeeNetworkException and
            // fail-over servers).
        }
        else
        {
            Console.WriteLine("OnError: " + e.Reason.Message);
            Console.WriteLine();
        }

    }

    // Raises if the e-mail could not be sent. The e-mail must have been
    // successfully generated during mail merge or provided by the application.
    // Doesn't raise if the error occurred before sending (at mail merge stage).
    private static void OnNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        Console.WriteLine("OnNotSent: Failed row #" + e.MergeRowIndex.ToString());
        Console.WriteLine("OnNotSent: " + e.Reason.Message);
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret");

        // Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>";
        mailer.Message.Subject = "Information";

        // Set templates for To and body.
        mailer.Message.To.AsString = "##name## <##email##>";
        mailer.Message.BodyPlainText = "Attachment for ##name##";

        // Raises each time the message is about to be sent. We use it
        // to add attachment after merging the template and data row.
        mailer.SendingMessage +=
            new SmtpSendingMessageEventHandler(OnSending);

        // Raises whenever anything goes wrong (warning or fatal error).
        // In our case, mails get generated with the help of external code
        // (in OnSending event handler). If that code fails, ErrorOccurred
        // is the only way to get the error description.
        mailer.ErrorOccurred += new ErrorEventHandler(OnError);

        // Raises when sending the message started but then failed.
        // However, does not raise if the message wasn't even built.
        // For instance, failed mail merge won't trigger it.
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(OnNotSent);

        // Uncomment if you want to stop bulk mail procedure on any error.
        // mailer.StopJobsOnError = true;

        // Generate and send e-mails.
        mailer.SendMailMerge(null, null, GetData());
    }
}

Imports System
Imports System.Data
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    ' Create DataTable with some data. In real-world apps,
    ' you'll get the data from external sources like SQL query.
    Function GetData() As DataTable
        Dim workTable As New DataTable("customers")

        Dim workCol As DataColumn = workTable.Columns.Add("id", GetType(Integer))
        workCol.AllowDBNull = False
        workCol.Unique = True

        workTable.Columns.Add("name", GetType(String))
        workTable.Columns.Add("email", GetType(String))
        workTable.Columns.Add("doc_id", GetType(Integer))
        workTable.Columns.Add("doc_name", GetType(String))

        ' Add two rows to the data source. This way,
        ' the mail merge procedure will generate two e-mails.
        Dim row As DataRow = workTable.NewRow()
        row("id") = 1
        row("name") = "John Doe"
        row("email") = "john.doe@company.com"
        row("doc_id") = 637
        row("doc_name") = "annual report.xls"
        workTable.Rows.Add(row)

        row = workTable.NewRow()
        row("id") = 2
        row("name") = "Bob Brown"
        row("email") = "bob.brown@example.com"
        row("doc_id") = 2358
        row("doc_name") = "agreement draft.pdf"
        workTable.Rows.Add(row)

        Return workTable
    End Function

    ' After mail merge produced the message, we manually attach a file
    ' as we need it to have different "real" (on the filesystem) and
    ' "target" (in the e-mail) filenames.
    Sub OnSending(ByVal sender As Object, ByVal e As SmtpSendingMessageEventArgs)
        e.MailMessage.Attachments.Add("C:\Docs\" & _
            e.MergeTable.Rows(e.MergeRowIndex)("doc_id").ToString() & ".tmp", _
            e.MergeTable.Rows(e.MergeRowIndex)("doc_name").ToString())
    End Sub

    ' Raises in many cases. Does not necessarily indicates the e-mail wasn't
    ' sent. For instance, if you're using main and fail-over backup SMTP servers
    ' and the main server is down, you'll get OnError stating about that, but
    ' then the message can still get sent through the fail-over server.
    Sub OnError(ByVal sender As Object, ByVal e As ErrorEventArgs)
        If TypeOf e.Reason Is MailBeeExternalException Then
            Console.WriteLine(
                "OnError: Some of your event handlers has thrown an exception.")
            Console.WriteLine(("The details: " & e.Reason.Message))
            Console.WriteLine()
        Else
            If TypeOf e.Reason Is MailBeeNetworkException Then
                ' Do nothing because OnNotSent will take care of failed messages.
                ' ErrorOccurred event is not so reliable when it comes to
                ' MailBeeNetworkException which may occur multiple times with
                ' fail-over servers and the e-mail can still get delivered.
                ' Other, non-MailBeeNetworkException errors, are definitive and
                ' non-recoverable. If a non-MailBeeNetworkException error has
                ' occurred for a certain e-mail, you can count on that the
                ' operation won't be retried and probably succeed for the second
                ' time (like it's possible with MailBeeNetworkException and
                ' fail-over servers).
            Else
                Console.WriteLine(("OnError: " & e.Reason.Message))
                Console.WriteLine()
            End If
        End If
    End Sub

    ' Raises if the e-mail could not be sent. The e-mail must have been
    ' successfully generated during mail merge or provided by the application.
    ' Doesn't raise if the error occurred before sending (at mail merge stage).
    Sub OnNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        Console.WriteLine(("OnNotSent: Failed row #" & e.MergeRowIndex.ToString()))
        Console.WriteLine(("OnNotSent: " & e.Reason.Message))
        Console.WriteLine()
    End Sub

    Sub Main()
        Dim mailer As New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret")

        ' Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>"
        mailer.Message.Subject = "Information"

        ' Set templates for To and body.
        mailer.Message.To.AsString = "##name## <##email##>"
        mailer.Message.BodyPlainText = "Attachment for ##name##"

        ' Raises each time the message is about to be sent. We use it
        ' to add attachment after merging the template and data row.
        AddHandler mailer.SendingMessage, AddressOf OnSending

        ' Raises whenever anything goes wrong (warning or fatal error).
        ' In our case, mails get generated with the help of external code
        ' (in OnSending event handler). If that code fails, ErrorOccurred
        ' is the only way to get the error description.
        AddHandler mailer.ErrorOccurred, AddressOf OnError

        ' Raises when sending the message started but then failed.
        ' However, does not raise if the message wasn't even built.
        ' For instance, failed mail merge won't trigger it.
        AddHandler mailer.MessageNotSent, AddressOf OnNotSent

        ' Uncomment if you want to stop bulk mail procedure on any error.
        ' mailer.StopJobsOnError = true;
        ' Generate and send e-mails.
        mailer.SendMailMerge(Nothing, Nothing, GetData())
    End Sub
End Module

Submit e-mails generated with mail merge to MailBee.NET Queue

Mail merge in MailBee.NET can also be used with a mail queue like MS IIS SMTP Pickup service or MailBee.NET Queue.

MailBee.NET Queue is a separate application from MailBee.NET Objects, it comes with its own installer. You, however, don't need a separate license key for it. MailBee.NET Queue consumes your existing MailBee.NET SMTP key (unified MailBee.NET Objects key will work either).

Several Visual Studio sample projects demonstrating how to submit e-mails to MailBee.NET Queue (including mail merge) are shipped with MailBee.NET Queue itself. Once installed MailBee.NET Queue, you can find them in Samples section of Start / Programs / MailBee.NET Queue menu.

In short, to perform bulk mailing into a mail queue rather than sending directly, use Smtp.AddJob and Smtp.SubmitJobsToPickupFolder methods instead of Smtp.SendMailMerge:

  • C#
  • VB
using System;
using System.Data;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Create DataTable with some data. In real-world apps,
    // you'll get the data from external sources like SQL query.
    private static DataTable GetData()
    {
        DataTable workTable = new DataTable("customers");

        DataColumn workCol = workTable.Columns.Add("id", typeof(int));
        workCol.AllowDBNull = false;
        workCol.Unique = true;

        workTable.Columns.Add("name", typeof(string));
        workTable.Columns.Add("email", typeof(string));
        workTable.Columns.Add("doc_id", typeof(int));
        workTable.Columns.Add("doc_name", typeof(string));

        // Add two rows to the data source. This way,
        // the mail merge procedure will generate two e-mails.
        DataRow row = workTable.NewRow();
        row["id"] = 1;
        row["name"] = "John Doe";
        row["email"] = "john.doe@company.com";
        row["doc_id"] = 637;
        row["doc_name"] = "annual report.xls";
        workTable.Rows.Add(row);

        row = workTable.NewRow();
        row["id"] = 2;
        row["name"] = "Bob Brown";
        row["email"] = "bob.brown@example.com";
        row["doc_id"] = 2358;
        row["doc_name"] = "agreement draft.pdf";
        workTable.Rows.Add(row);

        return workTable;
    }

    static void Main(string[] args)
    {
        // Note that we do not add any SMTP relay server here.
        Smtp mailer = new Smtp();

        // Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>";
        mailer.Message.Subject = "Information";

        // Set templates for To, body, and attachment.
        mailer.Message.To.AsString = "##name## <##email##>";
        mailer.Message.BodyPlainText = "Attachment for ##name##";
        mailer.Message.Merge.AddAttachmentPattern("C:\\Docs\\##doc_name##");

        // Create mail merge job.
        mailer.AddJob(null, null, null, GetData());

        // Generate e-mails accordingly the mail merge job and submit them
        // to MailBee.NET Queue (IIS SMTP Pickup service would work too).
        mailer.SubmitJobsToPickupFolder(
            "C:\\MailBeeNetQueue Files\\Pickup", false);
    }
}

Imports System
Imports System.Data
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    ' Create DataTable with some data. In real-world apps,
    ' you'll get the data from external sources like SQL query.
    Function GetData() As DataTable
        Dim workTable As New DataTable("customers")

        Dim workCol As DataColumn = workTable.Columns.Add("id", GetType(Integer))
        workCol.AllowDBNull = False
        workCol.Unique = True

        workTable.Columns.Add("name", GetType(String))
        workTable.Columns.Add("email", GetType(String))
        workTable.Columns.Add("doc_id", GetType(Integer))
        workTable.Columns.Add("doc_name", GetType(String))

        ' Add two rows to the data source. This way,
        ' the mail merge procedure will generate two e-mails.
        Dim row As DataRow = workTable.NewRow()
        row("id") = 1
        row("name") = "John Doe"
        row("email") = "john.doe@company.com"
        row("doc_id") = 637
        row("doc_name") = "annual report.xls"
        workTable.Rows.Add(row)

        row = workTable.NewRow()
        row("id") = 2
        row("name") = "Bob Brown"
        row("email") = "bob.brown@example.com"
        row("doc_id") = 2358
        row("doc_name") = "agreement draft.pdf"
        workTable.Rows.Add(row)

        Return workTable
    End Function

    Sub Main()
        ' Note that we do not add any SMTP relay server here.
        Dim mailer As New Smtp()

        ' Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>"
        mailer.Message.Subject = "Information"

        ' Set templates for To, body, and attachment.
        mailer.Message.To.AsString = "##name## <##email##>"
        mailer.Message.BodyPlainText = "Attachment for ##name##"
        mailer.Message.Merge.AddAttachmentPattern("C:\Docs\##doc_name##")

        ' Create mail merge job.
        mailer.AddJob(Nothing, Nothing, Nothing, GetData())

        ' Generate e-mails accordingly the mail merge job and submit them
        ' to MailBee.NET Queue (IIS SMTP Pickup service would work too).
        mailer.SubmitJobsToPickupFolder("C:\MailBeeNetQueue Files\Pickup", False)
    End Sub
End Module

Note that the error handling issue applies to this method too. In case if, for instance, the attachment under the given name is not found, MailBee.NET will just silently go to the next message, and so on. Use Smtp.ErrorOccurredevent, like in previous sample, for handling errors.

If you need to alter the message after mail merge, use Smtp.SubmittingMessageToPickupFolder event like you used Smtp.SendingMessage in case of "normal send".

Send feedback to AfterLogic


Request delivery and reading confirmation

  • Comparison of various methods of requesting delivery and reading confirmations
  • Request delivery and reading confirmation via message headers
  • Request delivery status notification with ESMTP DSN
  • Use ESMTP DSN and message headers together
  • ESMTP DSN in detail
  • Fine-tune ESMTP DSN and assign Tracking ID to e-mail

If you just need to request read and delivery receipts for your e-mail, refer to Set "Request delivery confirmation" and "Request read confirmation" flags topic. The current guide is the much more detailed version of that topic.

Comparison of various methods of requesting delivery and reading confirmations

MailBee.NET supports several methods of requesting read receipts (reading confirmation) and delivery receipts (delivery confirmation).

"Request read receipt" methods:

  • Using mailer.Message.ConfirmRead = "send_receipt_to@address.com" syntax, set MailMessage.ConfirmRead property of the outgoing e-mail.

    This sets Disposition-Notification-To message header which enables the e-mail reader of the recipient to send confirmation e-mail when the recipient opens the message for the first time. That e-mail reader program must support this functionality.

  • Use HTML body with an external image with dynamic URL and monitor access to that URL to determine the moment when the recipient opens the message and the HTML renderer requests this URL to draw the picture. The e-mail reader of the recipient must be configured to show external images.

    Nowadays, most e-mail programs do not show external images by default so this method is also not perfect. Moreover, spammers widely use this technology so your e-mail may get busted by anti-spam programs if it uses such "spam-like" techniques.

"Request delivery receipt" methods:

  • Using mailer.Message.ConfirmReceipt = "send_receipt_to@address.com" syntax, set MailMessage.ConfirmReceipt property of the outgoing e-mail.

    This sets Return-Receipt-To message header which enables the e-mail server of the recipient to send confirmation e-mail when the original e-mail gets received by that server. However, most newer e-mail servers do not support Return-Receipt-To header.

  • Using mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always syntax, set DeliveryNotificationOptions.NotifyCondition property of the mailer.

    During sending, this will cause the mailer to set the DSN flags in the SMTP envelope to inform the receiving part to send notification not only when the message cannot be delivered but also when the delivery succeeds.

    This is a better alternative to setting Return-Receipt-To header as most newer servers support DSN (Delivery Status Notification extension to SMTP protocol). Also, you can combine both methods to better cover both older and newer servers.

Here and below, we assume mailer is an Smtp object instance.

You can use various methods together as there is no 100% reliable method of getting reading or delivery confirmations. The question is even not technical but rather social. People don't like to be tracked. So, you can request read and delivery receipts but you can never rely on them.

Generally speaking, if you got a delivery confirmation, you can safely assume the event described in this delivery confirmation has actually occurred. But if you haven't got any confirmation, this does not yet mean the actual event has never happened.

Request delivery and reading confirmation via message headers

This code snippet inserts message headers which will notify the receiving part to send delivery and reading confirmation to the specified e-mail address:

  • C#
  • VB
mailer.Message.ConfirmRead = "john.doe@company.com";
mailer.Message.ConfirmReceipt = "john.doe@company.com";

mailer.Message.ConfirmRead = "john.doe@company.com"
mailer.Message.ConfirmReceipt = "john.doe@company.com"

The e-mail server of the receiving part must support Return-Receipt-To header to send delivery confirmation, and the e-mail client program of the recipient must support Disposition-Notification-To header to send reading confirmation.

Request delivery status notification with ESMTP DSN

This method uses DSN (Delivery Status Notification) extension to SMTP protocol. If your server supports it, it includes DSN in the list of capabilities which is sent to the client in response to EHLO command.

This code snippet will cause MailBee.NET to notify the SMTP server that it needs to send delivery confirmation back to the sender in both cases (if the message was or wasn't delivered):

  • C#
  • VB
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always;

mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always

The SMTP server must support DSN extension to send delivery confirmation.

Note that the only way to set the e-mail address where these notifications will arrive to is to set the actual sender of the message. See Set different From and Return-Path (use "real" sender address different from "From" address)topic on how to set the actual sender.

Use ESMTP DSN and message headers together

ESMTP DSN, Return-Receipt-To and Disposition-Notification-To message headers can be used all together because they are completely independent from each other:

  • C#
  • VB
// Request reading confirmation to the From address.
// Requires support from the recipient's e-mail reader.
// Most e-mail reader support this but it's often disabled.
mailer.Message.ConfirmRead = "john.doe@company.com";

// Request delivery confirmation to the From address.
// Requires support from the recipient's e-mail server.
// Most new servers don't support this but old servers often do.
mailer.Message.ConfirmReceipt = "john.doe@company.com";

// Request delivery confirmation for both delivery and non-delivery.
// Requires DSN support in the e-mail servers of yours and your recipient.
// Most new servers support this. If your server supports DSN but your
// recipient's server doesn't, delivery notifications will still work
// in most cases (unless there are more than 2 SMTP servers in the chain).
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always;

' Request reading confirmation to the From address.
' Requires support from the recipient's e-mail reader.
' Most e-mail reader support this but it's often disabled.
mailer.Message.ConfirmRead = "john.doe@company.com"

' Request delivery confirmation to the From address.
' Requires support from the recipient's e-mail server.
' Most new servers don't support this but old servers often do.
mailer.Message.ConfirmReceipt = "john.doe@company.com"

' Request delivery confirmation for both delivery and non-delivery.
' Requires DSN support in the e-mail servers of yours and your recipient.
' Most new servers support this. If your server supports DSN but your
' recipient's server doesn't, delivery notifications will still work
' in most cases (unless there are more than 2 SMTP servers in the chain).
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always

ESMTP DSN in detail

In practice, ESMTP DSN method is the most reliable method of getting delivery confirmation. However, this method uses SMTP envelope rather than message headers. For instance, if you save the message into a file and then restore it back, the delivery confirmation flag will be lost. To overcome this within your own system, you can save this flag into your own custom message header and examine this header when you later load the message back.Send to undisclosed recipients (use "real" recipient addresses different from "To", "CC", "BCC" addresses) topic explains this.

Unfortunately, you can't pass DSN-related information to external sending systems (like you can sometimes do with X-Sender and X-Receiver headers in order to pass real sender and recipients). However, you can often configure DSN settings in the sending e-mail system itself.

Another specifics of ESMTP DSN method is that it always sends notifications to the "real sender" of the message. Be aware of that if you set "real sender" different from "From" sender, as described in Set different From and Return-Path (use "real" sender address different from "From" address) topic.

But unlike "request read receipt" or "request delivery receipt" message header flags which do not provide any mechanism to check if the receiving side supports these flags, ESMTP DSN method has the advantage that you can check if your SMTP server supports DSN:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret");

// Set From address.
mailer.Message.From.Email = "john.doe@company.com";
mailer.Message.From.DisplayName = "John Doe";

// Set the recipient.
mailer.Message.To.Add("jane.doe@domain.com", "Jane Doe");

// Set subject and body.
mailer.Message.Subject = "Hello";
mailer.Message.BodyPlainText = "Can we meet tomorrow?";

// Request delivery confirmation for both delivery and non-delivery.
// Requires DSN support in the e-mail servers of yours and your recipient.
// Most new servers support this. If your server supports DSN but your
// recipient's server doesn't, delivery notifications will still work
// in most cases (unless there are more than 2 SMTP servers in the chain).
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always;

// To determine if DSN is supported before sending the message, we
// need to explicitly connect to the server and say hello. The server
// responds with its capabilities to that. Still, even if your server
// supports DSN, this does not yet mean the recipient's server does.
mailer.Connect();
mailer.Hello();
if (mailer.GetExtension("DSN") != null)
{
    Console.WriteLine("Delivery Status Notification supported");
}
else
{
    Console.WriteLine("Delivery Status Notification not supported");
}

// Authenticate and send the message.
mailer.Login();
mailer.Send();

// Since we connected manually, we need to disconnect manually either.
mailer.Disconnect();

Dim mailer As Smtp = New Smtp()

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret")

' Set From address.
mailer.Message.From.Email = "john.doe@company.com"
mailer.Message.From.DisplayName = "John Doe"

' Set the recipient.
mailer.Message.To.Add("jane.doe@domain.com", "Jane Doe")

' Set subject and body.
mailer.Message.Subject = "Hello"
mailer.Message.BodyPlainText = "Can we meet tomorrow?"

' Request delivery confirmation for both delivery and non-delivery.
' Requires DSN support in the e-mail servers of yours and your recipient.
' Most new servers support this. If your server supports DSN but your
' recipient's server doesn't, delivery notifications will still work
' in most cases (unless there are more than 2 SMTP servers in the chain).
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always

' To determine if DSN is supported before sending the message, we
' need to explicitly connect to the server and say hello. The server
' responds with its capabilities to that. Still, even if your server
' supports DSN, this does not yet mean the recipient's server does.
mailer.Connect()
mailer.Hello()
If Not mailer.GetExtension("DSN") Is Nothing Then
    Console.WriteLine("Delivery Status Notification supported")
Else
    Console.WriteLine("Delivery Status Notification not supported")
End If

' Authenticate and send the message.
mailer.Login()
mailer.Send()

' Since we connected manually, we need to disconnect manually either.
mailer.Disconnect()

Fine-tune ESMTP DSN and assign Tracking ID to e-mail

With DSN, you can not only set which condition must trigger the delivery notification to be sent (delivery, non-delivery, delay) but also specify which part of the original message to return with the notification, and even assign a unique value for each e-mail so that you can expect this value to appear in the notification messages.

Tracking ID lets you match your original e-mails and delivery notifications you receive upon delivery (or, sadly, non-delivery) of these e-mails to recipients. This is important if you implement processing bounced messages to automatically unsubscribe dead addresses, etc.

MailBee.NET BounceMail component allows you to extract Tracking ID as long as any other information from delivery notifications. This component is part of MailBee.NET assembly and it doesn't need any license key (free functionality). For details, see DeliveryStatusParser class documentation.

The sample below sets Tracking ID and informs the receiving part to send delivery notification only in case of troubles (delivery failure or delay).

We also request the receiving part to include the entire original message in response, not just the message header section (this is not required for Tracking ID to work, we do this just for demonstration purposes):

  • C#
  • VB
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always;
mailer.DeliveryNotification.ReturnPortion = DsnReturnPortion.FullMessage;
mailer.DeliveryNotification.TrackingID = "702345_Newsletter_Mar_2011";

mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always
mailer.DeliveryNotification.ReturnPortion = DsnReturnPortion.FullMessage
mailer.DeliveryNotification.TrackingID = "702345_Newsletter_Mar_2011"

If you send bulk e-mail using mail merge feature, you may find it useful that mailer.DeliveryNotification.TrackingID (DeliveryNotificationOptions.TrackingID) can be the part of the e-mail template so that you can automatically assign the unique Tracking ID to every e-mail being generated. For instance, something like this:

  • C#
  • VB
mailer.DeliveryNotification.TrackingID = "##subscriber_id##_Newsletter_Mar_2011";

mailer.DeliveryNotification.TrackingID = "##subscriber_id##_Newsletter_Mar_2011"

It's assumed subscriber_id is the column name in System.Data.DataTable object which is used as the data source for mail merge (see Smtp.SendMailMerge method documentation for details).

Send feedback to AfterLogic


Adjust e-mail to let it pass through spam filters

  • Sign e-mail with DomainKeys and DKIM
  • General suggestions

Spam filters are far from being perfect. This guide describes what you can do if your legitimate e-mails keep getting blocked by spam filters.

Sign e-mail with DomainKeys and DKIM

DomainKeys technology and its newer version DKIM allow the receiving part to check if the incoming e-mail is indeed sent from the e-mail address which appears in the message. Spammers usually forge addresses in e-mails and therefore can't sign e-mails with DomainKeys and DKIM. If your e-mail has a valid DomainKeys and DKIM signatures, the chances the receiving part will consider it spam will reduce significantly.

Note that DomainKeys/DKIM signing must be the very last thing you during creating the e-mail. If you modify the e-mail content after the signature has been created, it will become invalid.

To support DomainKeys/DKIM, you need a pair of certificates:

  • Private certificate which you will use to sign outgoing e-mails.
  • Public certificate as DNS TXT record of your e-mail server. The domain record where this certificate resides must be somewhat like selector._domainkey.yourdomain.com. selector part of the string is configurable, the rest is not.

Certificates can be created with OpenSSL tool. Unlike SSL and S/MIME certificates, self-signed DomainKeys/DKIM certificates are perfectly OK. Just make sure the certificate's private key is at least 1024 bits strong.

When the receiving part gets an incoming message signed with DomainKeys/DKIM, it validates that the message is not altered using the signature in the message and the public certificate on your server. This assures that the message was sent by someone who has access to the private certificate for this server.

Even if spammer was able to send e-mail through your server (e.g. the server is open relay), the spammer will be unable to properly sign e-mails without access to the private certificate. Of course, the private certificate must be kept in a safe place. Do not give it to anyone! If you have external (but legitimate) users which need to send e-mail through your server and sign with DKIM/DomainKeys, implement server-side signing of their e-mails instead of giving the certificate to them.

All types and classes related to DKIM/DomainKeys reside in MailBee.Security namespace. Also, MailMessage object provides a convenient MailMessage.DomainKeysSign method for quick access to the "sign with DKIM/DomainKeys" function.

The sample below signs the message with DomainKeys and DKIM. The sample assumes that the DK/DKIM public key resides in DNS TXT record named dk._domainkey.company.com and the corresponding private key resides in C:\Temp\rsa1024.private file:

  • C#
  • VB
Smtp mailer = new Smtp();

// Set the message properties.
mailer.Message.From.Email = "john.doe@company.com";
mailer.Message.To.Add("jane.doe@example.com");
mailer.Message.Subject = "Hello";
mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?";

// Sign the message with DomainKeys and DKIM.
mailer.Message.DomainKeysSign(false, null, @"C:\Temp\rsa1024.private",
    true, "dk", DomainKeysTypes.Both);

// Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret");
mailer.Send();

Dim mailer As Smtp = New Smtp()

' Set the message properties.
mailer.Message.From.Email = "john.doe@company.com"
mailer.Message.To.Add("jane.doe@example.com")
mailer.Message.Subject = "Hello"
mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?"

' Sign the message with DomainKeys and DKIM.
mailer.Message.DomainKeysSign(False, Nothing, "C:\Temp\rsa512.private", _
    True, "dk", DomainKeysTypes.Both)

' Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret")
mailer.Send()

We assume that MailBee, MailBee.Mime, MailBee.SmtpMail and MailBee.Security namespaces are already imported and MailBee.Global.LicenseKey is specified (in the code or in app.config or web.config file). To learn more, refer to Import namespaces and set license key topic.

Other notes:

  • For ASP.NET applications, the first parameter of MailMessage.DomainKeysSign method must be true.
  • dk is selector, it assumes the public certificate's DNS TXT record is available at dk._domainkey.yourdomain.com.
  • MailBee.NET does not check if selector._domainkey.yourdomain.com DNS TXT record actually exists when you sign the message. This check is only performed by the receiving part which needs to validate the signature of the incoming message.
  • For e-mails generated with mail merge (such as with Smtp.SendMailMerge method), you can call MailMessage.DomainKeysSign method during mail merge post-processing. Subscribe to Smtp.SendingMessage event and call e.MailMessage.DomainKeysSign in the event handler (assuming e is SmtpSendingMessageEventArgs parameter of the event handler). For details on mail merge post-processing, refer to Mail merge with post processing topic.
  • Signing with DomainKeys/DKIM is a memory and resource consuming operation. Ideally, it should be your e-mail server's responsibility to sign all outgoing e-mails, not MailBee.NET's. If your server does not support DomainKeys/DKIM and you have to use MailBee.NET for that, you can optimize performance by signing with DKIM only (no classic DomainKeys). In practice, if the server supports classic DomainKeys, it will support DKIM either, so having DKIM-only signature should be enough.
  • If combined with S/MIME encryption or signing, you must first do S/MIME thing, and AFTER that sign with DomainKeys/DKIM.

To read more on DomainKeys/DKIM, refer to DomainKeys class. It provides more explanations and features in addition to MailMessage.DomainKeysSign method.

General suggestions

Although DomainKeys/DKIM is a powerful tool to satisfy spam filters, it's often not sufficient (or even not possible to use at all if you are not an administrator of the server and thus cannot add entries to its DNS records).

What else you can do with the server (if you're the server's admin):

  • Make sure the e-mail server has the valid PTR record (reverse DNS) and MX record. There are many online tools in the Internet which allow you to check if your e-mail server has all the required DNS records.
  • Set DNS SPF record for the e-mail server to publish the list of all IP addresses which have permission to relay through it. Not as mandatory as PTR and MX, but quite important though.
  • Check if the IP address of your e-mail server is not black-listed. You may need to change the IP address if it's "poor".

What else you can do with the e-mails you're creating (if you're just a user):

  • If sending automated messages, provide clearly visible unsubscribe links and make sure they work. You can also add List-Unsubscribe header to your e-mails and implement List-Unsubscribe mechanism.
  • Process bounced e-mails and unsubscribe dead addresses in a timely manner. You can use DeliveryStatusParser class of MailBee.BounceMail namespace to check if the e-mail is a delivery or non-delivery report.
  • For HTML e-mails, provide plain-text version as well. MailBee.NET does this by default, do not turn this off.
  • Avoid external images in HTML e-mails (they are often used by spammers to track when people open e-mail in their e-mail clients).

Send feedback to AfterLogic


Sign and encrypt e-mail with S/MIME

  • Introduction
  • Sign e-mail with S/MIME to prove authenticity of sender
  • Sign and encrypt e-mail with S/MIME to ensure privacy and security

This guide describes using security certificates, certificate stores, public and private keys to sign and encrypt e-mails with S/MIME.

Introduction

To securely transfer an e-mail between the client and the server, SSL connection can be used. However, to protect the message from unauthorized access on all the steps of its lifecycle, you should encrypt the message itself.

Signing the message with S/MIME assures nobody has altered it during the transmission. You can additionally sign the message with DomainKeys/DKIM if you wish (but their certificates are different as S/MIME and DomainKeys/DKIM serve different purposes and use certificates of a different format).

S/MIME is all about certificates, so you'll usually need to purchase a certificate from a well-known security provider (Certification Authority, CA) unless you already have one.

Please note that MailBee.NET SMTP license does not include the license for S/MIME. You need the full MailBee.NET Objects license in order to send S/MIME signed or encrypted e-mails with MailBee.NET.

ASP.NET note. Many operations with certificates involve using Windows Registry so S/MIME functionality is very sensitive to the current user context. For instance, system-level certificate stores are practically useless for web applications as users have their certificates on their computers, in their own system-level stores. While a desktop application which runs on your computer under your user context can get your certificate, a web application running elsewhere can get access to this certificate only if you somehow upload the certificate file there.

Sign e-mail with S/MIME to prove authenticity of sender

Before sending S/MIME signed e-mail with MailBee.NET, make sure of the following:

  • You have a "private key" certificate which you'll use to sign the outgoing e-mail.
  • You tested sending e-mail signed with this certificate in another e-mail client like Outlook and Thunderbird.
  • Your recipient received the e-mail and confirmed that the signature is valid.

The sample below signs the message with S/MIME and DKIM signatures (the private keys for both are taken from files), and sends the message:

  • C#
  • VB
Smtp mailer = new Smtp();

// Set the message properties.
mailer.Message.From.Email = "john.doe@company.com";
mailer.Message.To.Add("jane.doe@example.com");
mailer.Message.Subject = "Hello";
mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?";

// Load the private key of john.doe@company.com from .PFX file.
Certificate signingCert = new Certificate(@"C:\Docs\private.pfx",
    CertFileType.Pfx, "secret");

// Sign the message with S/MIME.
Smime secureMime = new Smime();
mailer.Message = secureMime.Sign(mailer.Message, signingCert);

// Also sign the message with DKIM. It's not required for S/MIME,
// we just demonstrate you can use S/MIME and DKIM together.
// Comment the next two lines out if you don't need DKIM signature.
mailer.Message.DomainKeysSign(false, null, @"C:\Docs\rsa512.private",
    true, "dk", DomainKeysTypes.DKIM);

// Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret");
mailer.Send();

Dim mailer As Smtp = New Smtp()

' Set the message properties.
mailer.Message.From.Email = "john.doe@company.com"
mailer.Message.To.Add("jane.doe@example.com")
mailer.Message.Subject = "Hello"
mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?"

' Load the private key of john.doe@company.com from .PFX file.
Dim signingCert As Certificate = New Certificate("C:\Docs\private.pfx", _
    CertFileType.Pfx, "secret")

' Sign the message with S/MIME.
Dim secureMime As Smime = New Smime()
mailer.Message = secureMime.Sign(mailer.Message, signingCert)

' Also sign the message with DKIM. It's not required for S/MIME,
' we just demonstrate you can use S/MIME and DKIM together.
' Comment the next two lines out if you don't need DKIM signature.
mailer.Message.DomainKeysSign(False, Nothing, "C:\Docs\rsa512.private", _
    True, "dk", DomainKeysTypes.DKIM)

' Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret")
mailer.Send()

We assume that MailBee, MailBee.Mime, MailBee.SmtpMail and MailBee.Security namespaces are already imported, MailBee.Global.LicenseKey is specified (directly in the code, or in app.config or web.config file). This license key must include MailBee.NET SMTP and MailBee.NET Security licenses (usually, MailBee.NET Objects unified key).

The sample above loaded the certificates from files. You can also load certificates from memory, or from certificate stores which in turn can be located in Windows Registry (also called System store), files or LDAP directory.

Note that in case of a web application, you cannot use System store unless you've added all the required certificates into the System store of the user whose context is used to run your ASP.NET application.

Let's say your private certificate resides in Personal folder of System store (you can find it at Personal tab in "Internet Options/Content/Certificates" dialog of Internet Explorer). The sample below uses S/MIME to sign the message with the private key taken from System/Personal storage and sends the e-mail out:

  • C#
  • VB
// Open the System store (it actually resides in Windows Registry).
CertificateStore store = new CertificateStore(CertificateStore.Personal,
    CertStoreType.System, null);

// Find the certificates of john.doe@company.com
CertificateCollection certs = store.FindCertificates("john.doe@company.com",
    CertificateFields.EmailAddress);

// We can now close the certificate store (it's unmanaged resource,
// that's why we must do this manually to avoid having the resource
// opened until GC eventually frees it).
store.Dispose();

if (certs.Count == 0)
{
    Console.WriteLine("Certificate not found in the store");
    return;
}

Smtp mailer = new Smtp();

// Set the message properties.
mailer.Message.From = new EmailAddress("john.doe@company.com", "John Doe");
mailer.Message.To.Add("jane.doe@example.com", "Jane Doe");
mailer.Message.Subject = "Hello";
mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?";

// Sign the message with S/MIME.
Smime secureMime = new Smime();
mailer.Message = secureMime.Sign(mailer.Message, certs[0]);

// Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret");
mailer.Send();

' Open the System store (it actually resides in Windows Registry).
Dim store As CertificateStore = New CertificateStore(CertificateStore.Personal, _
    CertStoreType.System, Nothing)

' Find the certificates of john.doe@company.com
Dim certs As CertificateCollection = store.FindCertificates("john.doe@company.com", _
    CertificateFields.EmailAddress)

' We can now close the certificate store (it's unmanaged resource,
' that's why we must do this manually to avoid having the resource
' opened until GC eventually frees it).
store.Dispose()

If certs.Count = 0 Then
    Console.WriteLine("Certificate not found in the store")
    Return
End If

Dim mailer As Smtp = New Smtp()

' Set the message properties.
mailer.Message.From = New EmailAddress("john.doe@company.com", "John Doe")
mailer.Message.To.Add("jane.doe@example.com", "Jane Doe")
mailer.Message.Subject = "Hello"
mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?"

' Sign the message with S/MIME.
Dim secureMime As Smime = New Smime()
mailer.Message = secureMime.Sign(mailer.Message, certs(0))

' Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret")
mailer.Send()

Sign and encrypt e-mail with S/MIME to ensure privacy and security

In order to encrypt an e-mail, you need to make sure your recipients will be able to decrypt it. This makes encryption and decryption procedure quite different from the signing and verifying the signature.

When you sign the message, you use your private key. But when you encrypt it, you use the public key of your recipient. If there are many recipients, you'll need to obtain the public key of every recipient.

When the recipient receives a signed message, he/she uses the public key encapsulated into the message to verify it. In other words, signing does not require the opposite party to have any security keys in order to complete the signature verification process.

When the recipient receives an encrypted message, he/she uses one's private key to decrypt it. Of course, this private key must match the public key this person previously gave you to let you encrypt e-mails for this person.

No need to transfer the public key from the recipient to the sender only via a secure channel, you can even publish it on the web. Only private keys must be kept in safety.

The sample below creates an e-mail, signs it with your private key taken from Personal folder of System store, encrypts it with the public keys of two people, and sends it out. For demonstration purposes, we take one public key from a file and another public key from your Address Book that resides in System store:

  • C#
  • VB
// Open Personal folder of System store.
CertificateStore store = new CertificateStore(CertificateStore.Personal,
    CertStoreType.System, null);

// Find the certificates of john.doe@company.com (sender).
CertificateCollection certs = store.FindCertificates("john.doe@company.com",
    CertificateFields.EmailAddress);

// Close the certificate store to free unmanaged resources.
store.Dispose();

if (certs.Count == 0)
{
    Console.WriteLine("Sender's certificate not found in the store");
    return;
}

Certificate senderCert = certs[0];

// Open Address Book.
store = new CertificateStore(CertificateStore.OtherPeople,
    CertStoreType.System, null);

// Find the certificates of jane.doe@example.com (one of recipients).
certs = store.FindCertificates("jane.doe@example.com",
    CertificateFields.EmailAddress);

// Close the certificate store to free unmanaged resources.
store.Dispose();

if (certs.Count == 0)
{
    Console.WriteLine("Recipient's certificate not found in the store");
    return;
}

// The public key of the recipient from Address Book.
Certificate recipientCert1 = certs[0];

// Load the public key of another recipient from .CER file.
Certificate recipientCert2 = new Certificate(@"C:\Docs\alice.cer",
    CertFileType.Cer, null);

// Make up the list of public certificates of all recipients.
certs.Clear();
certs.Add(recipientCert1);
certs.Add(recipientCert2);

Smtp mailer = new Smtp();

// Set the message properties (and demonstrate different methods
// of setting email addresses in From and To).
mailer.Message.From = new EmailAddress("john.doe@company.com", "John Doe");
mailer.Message.To.Add("jane.doe@example.com", "Jane Doe");
mailer.Message.To.AddFromString("Alice <alice@there.com>");
mailer.Message.Subject = "Hello";
mailer.Message.BodyPlainText = "Hello, Jane and Alice, can we meet today?";

// Sign and encrypt the message with S/MIME.
Smime secureMime = new Smime();
mailer.Message = secureMime.SignAndEncrypt(mailer.Message, senderCert, certs);

// Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret");
mailer.Send();

' Open Personal folder of System store.
Dim store As CertificateStore = New CertificateStore(CertificateStore.Personal, _
    CertStoreType.System, Nothing)

' Find the certificates of john.doe@company.com (sender).
Dim certs As CertificateCollection = store.FindCertificates("john.doe@company.com", _
    CertificateFields.EmailAddress)

' Close the certificate store to free unmanaged resources.
store.Dispose()

If certs.Count = 0 Then
    Console.WriteLine("Sender's certificate not found in the store")
    Return
End If

Dim senderCert As Certificate = certs(0)

' Open Address Book.
store = New CertificateStore(CertificateStore.OtherPeople, _
    CertStoreType.System, Nothing)

' Find the certificates of jane.doe@example.com (one of recipients).
certs = store.FindCertificates("jane.doe@example.com", _
    CertificateFields.EmailAddress)

' Close the certificate store to free unmanaged resources.
store.Dispose()

If certs.Count = 0 Then
    Console.WriteLine("Recipient's certificate not found in the store")
    Return
End If

' The public key of the recipient from Address Book.
Dim recipientCert1 As Certificate = certs(0)

' Load the public key of another recipient from .CER file.
Dim recipientCert2 As Certificate = New Certificate("C:\Docs\alice.cer", _
    CertFileType.Cer, Nothing)

' Make up the list of public certificates of all recipients.
certs.Clear()
certs.Add(recipientCert1)
certs.Add(recipientCert2)

Dim mailer As Smtp = New Smtp()

' Set the message properties (and demonstrate different methods
' of setting email addresses in From and To).
mailer.Message.From = New EmailAddress("john.doe@company.com", "John Doe")
mailer.Message.To.Add("jane.doe@example.com", "Jane Doe")
mailer.Message.To.AddFromString("Alice <alice@there.com>")
mailer.Message.Subject = "Hello"
mailer.Message.BodyPlainText = "Hello, Jane and Alice, can we meet today?"

' Sign and encrypt the message with S/MIME.
Dim secureMime As Smime = New Smime()
mailer.Message = secureMime.SignAndEncrypt(mailer.Message, senderCert, certs)

' Send the message via SMTP server (authentication is enabled).
mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret")
mailer.Send()

To view which certificates you have in Address Book, open Other People tab in "Internet Options/Content/Certificates" dialog of Internet Explorer. However, this does not make sense for a web application as it usually runs on another computer (web server). And even when you run the web application on your own computer, it's usually executed under the context of a system user, not your own user.

Send feedback to AfterLogic


Accepted and refused recipients

  • Introduction
  • Allow or disallow refused (failed) recipients
  • Get successful and failed recipients after sending e-mail
  • Use events to track successful and failed recipients during sending e-mail

Introduction

If you send an e-mail to multiple recipients, it may turn out that the server has accepted some recipients while other recipients have been rejected. The SMTP protocol is very permissive in this regard, and the message will be accepted for delivery even if at least one recipient was accepted. So does MailBee.NET.

However, such "partial delivery" may not be suitable for you in case if you believe your e-mail makes sense only if delivered to all the recipients). In this case, you can tell MailBee.NET to cancel the submission of the e-mail to the SMTP relay server if any recipient gets rejected.

In case if you allow failed recipients, you can then track which recipients have succeeded and which ones have failed. You can do this both during and after sending the message. You can also make a decision whether to allow failed recipients on per-recipient basis.

Anyway, it's important to understand that even if your SMTP relay server has accepted some recipients, this does not yet guarantee they will actually receive the message. For performance sake, your server may just accept all the e-mail addresses you're submitting to it without making any additional checks. Also, even if the server finds the particular e-mail address to be valid, it does not yet mean that address actually exists (it only means the domain part of the address is valid).

Note that you can enable or disable failed recipients only when sending via an SMTP relay server. If you're using direct send via DNX MX lookup, it's not possible to disallow failed recipients. This is because direct send is not an "atomic" operation (transaction) which can be easily rolled back at any moment.

For instance, if you send to joe@firstdomain.com and jane@seconddomain.com via DNS MX lookup, MailBee.NET needs to create separate connections with SMTP MX servers of firstdomain.com (MX1) and seconddomain.com (MX2). If MX1 has accepted the message but MX2 hasn't, it's not possible to tell MX1 to "forget" the message it just received.

Of course, direct send does not permit failed recipients if you send to a single recipient only (if it fails, nobody will receive the message, so you never have the "partial delivery" problem with single recipients). Due to this and some other reasons, it's recommended to send e-mails in "direct send" mode only to single recipients.

Allow or disallow refused (failed) recipients

By default, refused (failed, rejected) recipients are allowed. To enable that the e-mail will be sent only if all the recipients are accepted, set SmtpServer.AllowRefusedRecipients to false in the SmtpServer object which represents the SMTP relay server you're connecting to:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
SmtpServer server = mailer.SmtpServers.Add("mail.here.com", "joe", "secret");

// Disallow rejected recipients.
server.AllowRefusedRecipients = false;

Dim mailer As New Smtp()

' Use SMTP relay server with authentication.
Dim server As SmtpServer = mailer.SmtpServers.Add("mail.here.com", "joe", "secret")

' Disallow rejected recipients.
server.AllowRefusedRecipients = False

The samples throughout this guide assume that MailBee and MailBee.SmtpMail namespaces are imported and MailBee.NET SMTP license key is set. See Import namespaces and set license key topic for details.

Get successful and failed recipients after sending e-mail

Once the message has been sent, you can check which recipients have been accepted or rejected. The sample below displays failed and successful recipients in two different ways:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
SmtpServer server = mailer.SmtpServers.Add("mail.example.com", "jane", "secret");

// Allow rejected recipients (true is default value so you can remove this line).
server.AllowRefusedRecipients = true;

// The message is not very important. If someone can't receive it, no big deal.
mailer.Message.From.Email = "jane@example.com";
mailer.Message.Subject = "Notification";
mailer.Message.BodyPlainText = "I'm going on vacation";

// We'll send the message to 3 addresses.
mailer.Message.To.Add("bill@domain1.com", "Bill C.");
mailer.Message.To.Add("mike@domain2.com", "Mike T.");
mailer.Message.To.Add("john@domain3.com", "John D.");

// Will succeed if at least one recipient is accepted.
mailer.Send();

// Report e-mail addresses (with display names) of accepted and rejected recipients.
Console.WriteLine("Succeessful: " + mailer.GetAcceptedRecipients().ToString());
Console.WriteLine("Failed: " + mailer.GetRefusedRecipients().ToString());

Console.WriteLine();

// Report e-mail addresses (no display names) of accepted and rejected recipients.
foreach (EmailAddress addr in mailer.GetAcceptedRecipients())
{
    Console.WriteLine("Successful e-mail: " + addr.Email);
}
foreach (EmailAddress addr in mailer.GetRefusedRecipients())
{
    Console.WriteLine("Failed e-mail: " + addr.Email);
}

Dim mailer As New Smtp()

' Use SMTP relay server with authentication.
Dim server As SmtpServer = mailer.SmtpServers.Add("mail.example.com", "jane", "secret")

' Allow rejected recipients (true is default value so you can remove this line).
server.AllowRefusedRecipients = True

' The message is not very important. If someone can't receive it, no big deal.
mailer.Message.From.Email = "jane@example.com"
mailer.Message.Subject = "Notification"
mailer.Message.BodyPlainText = "I'm going on vacation"

' We'll send the message to 3 addresses.
mailer.Message.To.Add("bill@domain1.com", "Bill C.")
mailer.Message.To.Add("mike@domain2.com", "Mike T.")
mailer.Message.To.Add("john@domain3.com", "John D.")

' Will succeed if at least one recipient is accepted.
mailer.Send()

' Report e-mail addresses (with display names) of accepted and rejected recipients.
Console.WriteLine("Succeessful: " & mailer.GetAcceptedRecipients().ToString())
Console.WriteLine("Failed: " & mailer.GetRefusedRecipients().ToString())

Console.WriteLine()

' Report e-mail addresses (no display names) of accepted and rejected recipients.
Dim addr As EmailAddress
For Each addr In mailer.GetAcceptedRecipients()
   Console.WriteLine("Successful e-mail: " & addr.Email)
Next addr
For Each addr In mailer.GetRefusedRecipients()
   Console.WriteLine("Failed e-mail: " & addr.Email)
Next addr

In case if your server always accepts all recipients regardless if they belong to existing domains or not, you can check the work of the sample by editing one or two recipients' e-mail address to make them invalid (e.g. remove @ symbol). The server, even if it does not check the validity of domain part, should at least perform syntax check on every address.

Use events to track successful and failed recipients during sending e-mail

Events allow your application to find out which recipients have been accepted or rejected before the completion of the sending process. You may even cancel the sending if you find out that an important recipient was rejected.

The console sample below sends an e-mail to a primary recipient (listed in To) and two secondary recipients (listed in CC). Let's assume we only care of primary recipients. If CC recipients receive the message, that's great. If they won't, no big deal. But we'll cancel the sending process in case if anyone listed in To field gets rejected:

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    private static void OnRecipient(object sender,
        SmtpMessageRecipientSubmittedEventArgs e)
    {
        // If the recipient was accepted, just move on.
        if (e.Result)
        {
            return;
        }

        // Check if it was the To recipient who was rejected.
        foreach (EmailAddress addr in e.MailMessage.To)
        {
            if (addr.Email == e.RecipientEmail)
            {
                e.AllowRefusedRecipient = false;
            }
        }
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        SmtpServer server = mailer.SmtpServers.Add(
            "mail.example.com", "jane", "secret");

        // Allow rejected recipients (the default state).
        server.AllowRefusedRecipients = true;

        // The message is not important to anyone but the boss.
        mailer.Message.From.Email = "jane@example.com";
        mailer.Message.Subject = "Notification";
        mailer.Message.BodyPlainText = "I'm going on vacation";

        // We'll send the message to 1 important and 2 other addresses.
        mailer.Message.To.Add("boss@example.com", "Big Boss");
        mailer.Message.Cc.Add("mike@here.com", "Mike T.");
        mailer.Message.Cc.Add("john@there.com", "John D.");

        // Subscribe to MessageRecipientSubmitted event to track
        // failed recipients and control the sending process.
        mailer.MessageRecipientSubmitted +=
            new SmtpMessageRecipientSubmittedEventHandler(OnRecipient);

        // Will succeed if at least To recipients are accepted.
        mailer.Send();

        // Report e-mail addresses of accepted and rejected recipients.
        foreach (EmailAddress addr in mailer.GetAcceptedRecipients())
        {
            Console.WriteLine("Successful e-mail: " + addr.Email);
        }
        foreach (EmailAddress addr in mailer.GetRefusedRecipients())
        {
            Console.WriteLine("Failed e-mail: " + addr.Email);
        }
    }
}

Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    Private Sub OnRecipient(ByVal sender As Object, _
          ByVal e As SmtpMessageRecipientSubmittedEventArgs)
        ' If the recipient was accepted, just move on.
        If e.Result Then
            Return
        End If

        ' Check if it was the To recipient who was rejected.
        Dim addr As EmailAddress
        For Each addr In e.MailMessage.To
            If addr.Email = e.RecipientEmail Then
                e.AllowRefusedRecipient = False
            End If
        Next addr
    End Sub

    Sub Main()
        Dim mailer As New Smtp()

        ' Use SMTP relay server with authentication.
        Dim server As SmtpServer = mailer.SmtpServers.Add( _
            "mail.example.com", "jane", "secret")

        ' Allow rejected recipients (the default state).
        server.AllowRefusedRecipients = True

        ' The message is not important to anyone but the boss.
        mailer.Message.From.Email = "jane@example.com"
        mailer.Message.Subject = "Notification"
        mailer.Message.BodyPlainText = "I'm going on vacation"

        ' We'll send the message to 1 important and 2 other addresses.
        mailer.Message.To.Add("boss@example.com", "Big Boss")
        mailer.Message.Cc.Add("mike@here.com", "Mike T.")
        mailer.Message.Cc.Add("john@there.com", "John D.")

        ' Subscribe to MessageRecipientSubmitted event to track
        ' failed recipients and control the sending process.
        AddHandler mailer.MessageRecipientSubmitted, AddressOf OnRecipient

        ' Will succeed if at least To recipients are accepted.
        mailer.Send()

        ' Report e-mail addresses of accepted and rejected recipients.
        Dim addr As EmailAddress
        For Each addr In mailer.GetAcceptedRecipients()
            Console.WriteLine("Successful e-mail: " & addr.Email)
        Next addr
        For Each addr In mailer.GetRefusedRecipients()
            Console.WriteLine("Failed e-mail: " & addr.Email)
        Next addr
    End Sub
End Module

Send feedback to AfterLogic


Direct send without SMTP relay server

  • Send with SMTP relay server, explained
  • Direct send via DNS MX lookup, explained
  • Set DNS servers in code, via auto-detection, or in config file
  • Direct send example
  • Set appropriate Hello message to pass reverse DNS check
  • Direct send vs normal send
  • Validate e-mail address via syntax check and DNS MX lookup

This guide provides the detailed explanation of "SMTP relay", "SMTP MX" and "DNS MX lookup" terms, the comparison of "direct send" and "send through a relay server" modes, and shows how to send e-mail without an SMTP relay server.

Send with SMTP relay server, explained

Typically, the client sends e-mail through an SMTP relay server. An relay server is a hub which accepts e-mails from clients and relays them to SMTP servers of their intended recipients. These SMTP servers as called MX servers (Mail eXchange). To find out which MX server exchanges e-mail for a particular domain, the relay server makes DNS MX lookup query for that domain.

The diagram below demonstrates sending e-mail VIA an SMTP relay server:

So the entire process in case of "send through a relay server" is:

  1. The client submits the e-mail over SMTP protocol to its SMTP relay server.
  2. The SMTP relay server examines each recipient's e-mail address, gets the domain part of each address and asks the DNS server which MX server is accepting e-mail for the given domain.
  3. Once the SMTP relay got the answers, it then establishes SMTP connection with MX server for every recipient's domain and submits the e-mail message data.
  4. The MX server of every recipient saves the message in the corresponding user's mailbox.

In practice, this process may involve multiple DNS servers for better performance and reliability (and the recipient's domain may have several MX servers assigned) but the idea remains the same.

Direct send via DNS MX lookup, explained

If you do not have an SMTP relay server, it's now the client's task to do all those things which are normally done by an SMTP relay.

The diagram below demonstrates sending e-mail WITHOUT an SMTP relay server:

MailBee.NET is capable of making DNS MX lookup queries and thus can discover recipients' MX servers. After the MX host name has been discovered, the client can send the e-mail to this MX host as if were a relay server.

From this moment, the only difference between an MX and a relay server is that MX server does not require authentication. This is because you send e-mail to a local recipient of this MX server and this MX does not need to relay the e-mail elsewhere (authentication is only needed when you want to send to external domains).

In many cases, SMTP relay and SMTP MX is the same server but from different points of view. When you're the sender, you assume this is your relay server. But it's your local MX for other senders (on other domains) who are willing to send e-mail to you and treat you as their recipient.

Set DNS servers in code, via auto-detection, or in config file

To let MailBee.NET perform DNS MX queries instead of a normal send through an SMTP relay server, fill Smtp.DnsServers collection instead of Smtp.SmtpServers.

You can specify DNS servers manually or rely on automatic detection of the DNS servers which are used by your active network connection. It's recommended to have more than one DNS server (primary and secondary) for better performance and reliability.

To find out which DNS servers are used by your current connection, examine the active TCP/IP network connection properties in Windows Control Panel / Network Connections.

That's how you can set DNS servers manually:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.DnsServers.Add("192.168.0.1");
mailer.DnsServers.Add("192.168.0.2");

Dim mailer As Smtp = New Smtp()
mailer.DnsServers.Add("192.168.0.1")
mailer.DnsServers.Add("192.168.0.2")

Here and below, we assume that MailBee and MailBee.SmtpMail namespaces are already imported and MailBee.Global.LicenseKey is specified (directly in the code, or in app.config or web.config file). To learn more, refer toImport namespaces and set license key topic.

When using direct send, you may also need to import MailBee.DnsMX namespace.

The above method works if you know which DNS servers are available in your network. Another method is to let MailBee.NET auto-detect the available DNS servers itself. However, this method may not work if .NET security system does not allow your application to access NetworkInterface class, WMI or the required Windows Registry branch.

That's how you can auto-detect the DNS servers (assuming the permissions are OK):

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.DnsServers.Autodetect();

Dim mailer As Smtp = New Smtp()
mailer.DnsServers.Autodetect()

If the auto-detection of DNS servers does not work in your case (usually happens with ASP.NET web applications lacking permission to access NetworkInterface class), you'll need to change Trust Level of your web application to Full.

If changing Trust Level is not an option, you can specify DNS servers' IP addresses in web.config file:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="MailBee.DnsMX.DnsServerCollection" value="192.168.0.1,0;192.168.0.2"/>
  </appSettings>

Note that <appSettings> may also appear as <applicationSettings> in your case.

In the first place, DnsServerCollection.Autodetect method uses the values specified in the config file and proceeds to other methods only if no DNS servers were listed there. You can also specify priorities of DNS servers in the config file, see the documentation on DnsAutodetectOptions enumeration for examples.

Direct send example

The code below uses the auto-detection of DNS servers and sends a simple e-mail via DNS MX lookup to several recipients:

  • C#
  • VB
Smtp mailer = new Smtp();

// See in the log what exactly happens during direct send.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Auto-detect DNS servers.
mailer.DnsServers.Autodetect();

// Specify From, To, CC in various ways.
mailer.From.Email = "joe@domain.com";
mailer.From.DisplayName = "Joe";
mailer.To.Add("mike@company1.com");
mailer.To.Add("liz@company1.com", "Liz");
mailer.Cc.Add("bill@company2.com", "Bill");
mailer.Cc.Add(new EmailAddress("kate@company3.com", "Kate"));

// Specify other fields and send the message.
mailer.Subject = "Test message";
mailer.BodyPlainText = "Just a test";
mailer.Send()

Dim mailer As New Smtp()

' See in the log what exactly happens during direct send.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Auto-detect DNS servers.
mailer.DnsServers.Autodetect()

' Specify From, To, CC in various ways.
mailer.From.Email = "joe@domain.com"
mailer.From.DisplayName = "Joe"
mailer.To.Add("mike@company1.com")
mailer.To.Add("liz@company1.com", "Liz")
mailer.Cc.Add("bill@company2.com", "Bill")
mailer.Cc.Add(New EmailAddress("kate@company3.com", "Kate"))

' Specify other fields and send the message.
mailer.Subject = "Test message"
mailer.BodyPlainText = "Just a test"
mailer.Send()

Note that as one of the recipients is set from EmailAddress object, you'll also need to import MailBee.Mime namespace.

You can also fine-tune a number of settings specific to "direct send" mode using Smtp.DirectSendDefaults property. Some examples of setting "direct send" defaults can also be found throughout Advanced SMTP connections (proxy, extensions, custom hello, commands and ports) guide.

Besides that, Smtp class provides some events specific to "direct send" mode: Smtp.MessageMXLookupDone and Smtp.MessageDirectSendDone.

You can also use DNS queries (including DNS MX lookup) for other purposes besides sending e-mail. For instance, you can validate e-mail addresses and perform various checks to filter spam by examining DNS-related data. To learn more, refer to Validate e-mail address via syntax check and DNS MX lookup topic or Filter spam with DNS queries (MX, SPF, DKIM, reverse DNS) guide respectively.

Set appropriate Hello message to pass reverse DNS check

By default, MailBee.NET uses the IPv4 address of the sending machine in the parameter of EHLO and HELO commands when making connections with MX hosts, or the local host name if the IPv4 address is not available.

Most SMTP MX servers perform reverse DNS check over the domain name or IP address listed in the EHLO/HELO parameter, and do not trust the connections which come from IP addresses not matching those specified in EHLO/HELO. MailBee.NET cannot always determine your external IP address (this is not possible if you're behind NAT) and thus your local IP address will be used. You can use DirectSendServerConfig.HelloDomain property to overcome this.

Note that if you specify the IP address instead of the domain name, you should enclose it in square brackets. Example: [15.16.23.42], so that the command to be sent would be EHLO [15.16.23.42].

Still, using the public (i.e. external) domain name is much more preferred than the IP address. Unfortunately, the public domain name is not known to the system (even if the public IP address is known) so that you can only specify it manually.

Example (assuming mailer is an Smtp instance):

  • C#
  • VB
mailer.DirectSendDefaults.HelloDomain = "sending.host.com";

mailer.DirectSendDefaults.HelloDomain = "sending.host.com"

Note that setting Hello message is essential for direct send (whereas it isn't so important when sending through a relay server).

Direct send vs normal send

In short, use normal send whenever possible. Use direct send only if normal send is not available.

Normal send via an SMTP relay server usually provides the optimal performance. SMTP relay sits in the data center with a very fast Internet connection, it can sort and pre-process incoming requests from clients in optimal way, maintain large cache of DNS records to avoid making DNS MX queries for popular domains, retry failed sends later, etc.

Also, if your e-mail is addressed to multiple recipients, there is a great difference between direct send and normal send. When "direct send" mode is used, rejected recipients are always allowed (unless you send to a single recipient only). However, with the SMTP relay and SmtpServer.AllowRefusedRecipients property, you can change this to require that the e-mail is considered as sent only if all recipients have been accepted. This means MailBee.NET will abort the transmission and cancel the e-mail completely - no recipients will receive it.

Such transactional mechanism ("all or none") is not possible with direct send because delivering e-mail to recipients' MXes is not a single transaction. In contrast, submitting recipients to SMTP relay can be assumed as the transaction which can be rolled back.

Even more important vote for SMTP relay is the fact that most e-mail services nowadays do not accept e-mail from hosts which are not full-fledged SMTP servers. This is because "direct send" mode is widely used by spammers' bot networks. A typical e-mail service, after it receives the incoming request to deliver an e-mail to it, makes reverse connection to the client's host, checks if that host is an SMTP server itself, if it has properly configured DNS MX, PTR, and SPF records, and so on.

Due to the above, you as a client may use "direct send" only when you send from the host which has all the DNS records and open SMTP port for reverse connections. Otherwise, many of your e-mails will not be delivered or will just end up in Spam folder of recipients' e-mail accounts.

More meaningful way of using direct send is the fail-over delivery method if the SMTP relay fails. Although MailBee.NET does allow you to use multiple SMTP relays (such as primary and fail-over), it does not help in case if you have only one SMTP relay and no fail-over one. In this case, you can implement fail-over mode only via direct send. Refer to Send through SMTP relay server or use direct send if SMTP relay server is down topic for example.

Last but not least, you can use direct send to verify e-mail addresses for validity (i.e. if certain string denotes an existing e-mail address). Although you can use Smtp.TestSend method with a relay server as well, usually it produces more accurate results with direct send. See the next topic for details.

Validate e-mail address via syntax check and DNS MX lookup

This is the advanced version of Verify e-mail address without sending actual e-mail topic.

To check if an e-mail address is valid, you can:

  1. Perform a syntax check over the address string (for instance, using Smtp.ValidateEmailAddressSyntax static method, or, in custom cases, your own regular expressions, like in the sample below).
  2. Additionally use Smtp.TestSend method to check if the domain name of the e-mail address is valid (and, with some degree of accuracy, the account name).
  3. EmailAddressValidator component is the ultimate tool for e-mail address verification, for both single addresses and (especially) bulks.

The sample below performs both syntax check via custom RegEx pattern and DNX MX lookup check. If the domain is found, MailBee.NET connects to the found MX server of the recipient being tested, and makes an attempt to submit the sender's and the recipient's e-mail addresses. If everything went fine, MailBee.NET closes the connection and reports that the specified e-mail address is valid:

  • C#
  • VB
// The e-mail address to check.
string email = "jane.doe@company.com";

string addressPattern =
    @"^(([\w-]+['\.])+[\w-]+|([\w-]+))@" +
    @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?" +
    @"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
    @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?" +
    @"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
    @"([a-zA-Z0-9]+[\w-]*\.)+[a-zA-Z]{2,9})$";

bool isCorrectSyntax =
    System.Text.RegularExpressions.Regex.IsMatch(email, addressPattern);

if (!isCorrectSyntax)
{
    Console.WriteLine("Syntax check failed");
}
else
{
    Smtp mailer = new Smtp();

    // See in the log how exactly MailBee.NET validates the address.
    mailer.Log.Enabled = true;
    mailer.Log.Filename = "C:\\Temp\\log.txt";
    mailer.Log.Clear();

    // Get ready for DNS MX lookup.
    mailer.DnsServers.Autodetect();

    // Set sender. It's recommended to use the address
    // from which you'll then be sending the actual e-mail.
    mailer.From.Email = "john.doe@domain.com";

    // Set the recipient's address we're going to verify.
    mailer.To.Add(email);

    // Verify the e-mail address.
    TestSendResult res =
        mailer.TestSend(SendFailureThreshold.AnyRecipientsFailed);

    switch (res)
    {
        case TestSendResult.OK:
            Console.WriteLine("Existing address");
            break;
        case TestSendResult.BadRecipient:
            // E.g. bad-recipient@good-domain.com.
            Console.WriteLine("Invalid account but valid domain");
            break;
        case TestSendResult.NoMXRecord:
            // E.g. bad-recipient@bad-domain.com.
            Console.WriteLine("Invalid account and domain");
            break;
        default:
            Console.WriteLine("Other error");
            break;
    }
}

' The e-mail address to check.
Dim email As String = "jane.doe@company.com"

Dim addressPattern As String = _
    "^(([\w-]+['\.])+[\w-]+|([\w-]+))@" & _
    "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?" & _
    "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." & _
    "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?" & _
    "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" & _
    "([a-zA-Z0-9]+[\w-]*\.)+[a-zA-Z]{2,9})$"

Dim isCorrectSyntax As Boolean = _
    System.Text.RegularExpressions.Regex.IsMatch(email, addressPattern)

If Not isCorrectSyntax Then
    Console.WriteLine("Syntax check failed")
Else
    Dim mailer As New Smtp()

    ' See in the log how exactly MailBee.NET validates the address.
    mailer.Log.Enabled = True
    mailer.Log.Filename = "C:\Temp\log.txt"
    mailer.Log.Clear()

    ' Get ready for DNS MX lookup.
    mailer.DnsServers.Autodetect()

    ' Set sender. It's recommended to use the address
    ' from which you'll then be sending the actual e-mail.
    mailer.From.Email = "john.doe@domain.com"

    ' Set the recipient's address we're going to verify.
    mailer.To.Add(email)

    ' Verify the e-mail address.
    Dim res As TestSendResult = _
        mailer.TestSend(SendFailureThreshold.AnyRecipientsFailed)

    Select Case res
        Case TestSendResult.OK
            Console.WriteLine("Existing address")
        Case TestSendResult.BadRecipient
            ' E.g. bad-recipient@good-domain.com.
            Console.WriteLine("Invalid account but valid domain")
        Case TestSendResult.NoMXRecord
            ' E.g. bad-recipient@bad-domain.com.
            Console.WriteLine("Invalid account and domain")
        Case Else
            Console.WriteLine("Other error")
    End Select
End If

As you can see, the sender's address is also required (in addition to the recipient's address being tested).

Smtp.TestSend method returns not just true or false but more than 20 status codes (see TestSendResult documentation) to let the application know what exactly went wrong. For instance, if you got, let's say, TestSendResult.DnsConnectionError, this means there is a problem with the DNS server being used, not with the e-mail address being checked.

You can also verify multiple addresses at once (in this case, failureThreshold parameter denotes whether to allow failed recipients or not). In there is a single recipient only, failureThreshold parameter value is ignored.

Note that it's not always possible to validate an e-mail address with 100% accuracy guarantee. Usually, you can reliably verify the syntax and the domain part (domain.com in user@domain.com).

As for the account name part (user in user@domain.com), the server may accept the e-mail to that address but bounce it back later (so that spammers would be unable to go over the list of popular words and try each word against the server to collect valid e-mail accounts on that server).

Also, even if the e-mail address is indeed correct and the recipient's server has confirmed this, you may be unable to send an actual e-mail to that address. For instance, Gmail allows any client to check if certain e-mail address exists in its domain, but only full-fledged e-mail servers with MX and PTR records can actually send e-mail there (again, to prevent spam). So, if the machine you're sending from is a public server with MX and PTR records and it isn't blacklisted on major DNSRBL's, you shouldn't have any issues in this regard.

Send feedback to AfterLogic


Filter spam with DNS queries (MX, SPF, DKIM, reverse DNS)

  • Introduction
  • DNS RBL lookup
  • Get DNS MX records
  • Get SPF or DKIM ADSP records with DNS TXT query
  • Get reverse DNS records with DNS PTR query
  • Use rDNS to check if sender's IP address matches HELO domain
  • Use rDNS query to find out if sender is home computer or Internet server

Introduction

MailBee.NET can make use of DNS queries for these tasks:

  • Send e-mails and verify e-mail addresses via DNS MX lookup (see Direct send without SMTP relay server guide).
  • Check DKIM and DomainKeys signatures of incoming e-mails (such as with MailMessage.DomainKeysVerify method).
  • DNS queries to RBL servers (real-time databases of IP addresses sending spam). See RblFilter class for details.

Besides that, MailBee.NET lets you make various DNS queries directly. Although MailBee.NET SMTP component mainly serves the purposes of sending e-mail, its capabilities of making DNS queries can also be used to verify incoming e-mails in a number of ways (including the validation of the e-mail address and IP address of the message sender).

For instance, if your code needs to perform an extensive anti-spam check against incoming e-mails, verifying just DKIM/DomainKeys signatures might not be enough and you'd also want to make sure sending hosts have valid MX, PTR, and SPF records.

In most cases, you'll perform such checks against the domain part of "From" e-mail address. You can take it as follows:

  • C#
  • VB
domain = msg.From.GetDomain();

domain = msg.From.GetDomain()

we assume msg is a MailMessage instance which represents the incoming e-mail message being examined.

However, "From:" e-mail address may be forged. Usually, you'll need to combine different methods to improve the reliability of anti-spam checks, such as to use reverse DNS check which is immune to e-mail address forging. See Get reverse DNS records with DNS PTR query topic for details.

Also, you can perform content filtering with MailBee.NET AntiSpam component which implements self-learning Bayesian filter. This component is included in MailBee.NET assembly. See BayesFilter class for details.

DNS RBL lookup

To make queries to RBL servers, you can use RblFilter class (you can find the sample code there as well).

Get DNS MX records

To request the list of DNS MX names for the given domain, use Smtp.GetMXHosts method. It also properly handles the situation when the host does not have any MX records but has A record (in case if the MX domain for the host is the host itself).

This sample downloads the last e-mail from an account on a POP3 server, then checks if the "From" domain has the required MX records (or A record) to determine if at least the domain part of the "From:" address denotes an existing host. The return value of Smtp.GetMXHosts method isn't used, we just need to know if the DNS MX records for that host are there:

  • C#
  • VB
// Get the last message from the POP3 server.
MailMessage msg = Pop3.QuickDownloadMessage(
    "mail.domain.com", "jdoe", "secret", -1);

Smtp mailer = new Smtp();

// See in the log on how exactly MailBee.NET makes DNS queries.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Get ready for DNS MX lookup.
mailer.DnsServers.Autodetect();

bool isDomainValid;
try
{
    // Make DNS query. We don't care for results.
    // If the method succeeds, the domain is OK.
    mailer.GetMXHosts(msg.From.GetDomain());
    isDomainValid = true;
}
catch (MailBeeDnsNameErrorException)
{
    // DNS server does not know this domain.
    isDomainValid = false;
}
catch (MailBeeDnsRecordsDisabledException)
{
    // By default, caching DNS queries is on. If the domain
    // being requested is already in the cache and MailBee.NET
    // already knows it's invalid, no actual query will be made.
    isDomainValid = false;
}

if (isDomainValid)
{
    Console.WriteLine("Valid domain");
}
else
{
    Console.WriteLine("Invalid domain");
}

' Get the last message from the POP3 server.
Dim msg As MailMessage = Pop3.QuickDownloadMessage( _
    "mail.domain.com", "jdoe", "secret", -1)

Dim mailer As New Smtp()

' See in the log on how exactly MailBee.NET makes DNS queries.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Get ready for DNS MX lookup.
mailer.DnsServers.Autodetect()

Dim isDomainValid As Boolean
Try
    ' Make DNS query. We don't care for results.
    ' If the method succeeds, the domain is OK.
    mailer.GetMXHosts(msg.From.GetDomain())
    isDomainValid = True
Catch e As MailBeeDnsNameErrorException
    ' DNS server does not know this domain.
    isDomainValid = False
Catch e As MailBeeDnsRecordsDisabledException
    ' By default, caching DNS queries is on. If the domain
    ' being requested is already in the cache and MailBee.NET
    ' already knows it's invalid, no actual query will be made.
    isDomainValid = False
End Try

If isDomainValid Then
    Console.WriteLine("Valid domain")
Else
    Console.WriteLine("Invalid domain")
End If

Here and below, we assume that MailBee, MailBee.Pop3Mail, MailBee.SmtpMail and MailBee.DnsMX namespaces are already imported, MailBee.Global.LicenseKey is specified (directly in the code, or in app.config or web.config file). To learn more, refer to Import namespaces and set license key topic.

As you can see, the spam detection efficiency of this method is very low. The spammer can easily forge "From:" address and use an existing domain in it (e.g. fake_from_address@hotmail.com). It's more reliable to use spam filtering methods which examine the sender's IP address instead (as it cannot be forged).

For instance, you can use rDNS query to get the sender's domain name from its IP address and then get MX records for the "From:" domain name. If any of these MX records contain the domain name of the sender, this indicates the "From:" domain is not forged.

The opposite is not correct, however. If the sending host's domain does not appear in MX list of the "From:" domain, it may indicate the relay SMTP server of the sender and its SMTP MX server are different hosts. This is perfectly normal for large providers.

Thus, you can use the method described above only to confirm that certain e-mail is not spam. If this check is negative, you should try other methods before you can say the e-mail is spam.

Get SPF or DKIM ADSP records with DNS TXT query

MailBee.NET provides built-in support of DomainKeys/DKIM verification with advanced methods of DomainKeys class and a short-hand MailMessage.DomainKeysVerify method.

Still, you may need to get some DNS TXT records manually, including those used with SPF (Sender Policy Framework, RFC 4408) or DKIM ADSP (Author Domain Signing Practices, RFC 5617).

MailBee.NET does not provide built-in mechanisms for SPF and DKIM ADSP but allows you to easily extract their DNS information for a domain. Your application will only need to parse the text string returned.

Although many servers use SPF nowadays, no server implementing DKIM ADSP is known to the moment (at least all major e-mail providers like Gmail, Hotmail and Yahoo still didn't support it at the moment of writing).

The sample below gets TXT records for DKIM ADSP (no exception is thrown in case if not found) and also checks root TXT records of the domain and searches for SPF record there:

  • C#
  • VB
Smtp mailer = new Smtp();

// See in the log on how exactly MailBee.NET makes DNS queries.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Get ready for making DNS queries.
mailer.DnsServers.Autodetect();

string[] records = null;

try
{
    // Get DKIM ADSP record (will likely to fail so ignore exceptions).
    records = mailer.GetTxtData("_adsp._domainkey.domain.com");

    // Some servers do not claim error but return no records. Check this.
    if (records != null)
    {
        Console.Write("DKIM ADSP record:");
        foreach (string rec in records)
        {
            // Should be only one such record (if any).
            Console.WriteLine(rec);
        }
        Console.WriteLine();
    }
}
catch (MailBeeDnsNameErrorException) { }
catch (MailBeeDnsRecordsDisabledException) { }

// Get root TXT records (to filter SPF record from them).
records = mailer.GetTxtData("domain.com");
if (records != null)
{
    foreach (string rec in records)
    {
        if (rec.ToLower().StartsWith("v=spf1"))
        {
            // Should be only one such record (if any).
            Console.Write("SPF record: ");
            Console.WriteLine(rec);
        }
    }
}

Dim mailer As New Smtp()

' See in the log on how exactly MailBee.NET makes DNS queries.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Get ready for making DNS queries.
mailer.DnsServers.Autodetect()

Dim records As String() = Nothing

Try
    ' Get DKIM ADSP record (will likely to fail so ignore exceptions).
    records = mailer.GetTxtData("_adsp._domainkey.domain.com")

    ' Some servers do not claim error but return no records. Check this.
    If Not (records Is Nothing) Then
        Console.Write("DKIM ADSP record:")
        Dim rec As String
        For Each rec In records
            ' Should be only one such record (if any).
            Console.WriteLine(rec)
        Next rec
        Console.WriteLine()
    End If
Catch e As MailBeeDnsNameErrorException
Catch e As MailBeeDnsRecordsDisabledException
End Try

' Get root TXT records (to filter SPF record from them).
records = mailer.GetTxtData("domain.com")

If Not (records Is Nothing) Then
    Dim rec As String
    For Each rec In records
        If rec.ToLower().StartsWith("v=spf1") Then
            ' Should be only one such record (if any).
            Console.Write("SPF record: ")
            Console.WriteLine(rec)
        End If
    Next rec
End If

You can extend the sample with the analysis of what's in the SPF record (for instance, get an e-mail from a POP3 or IMAP server, then look the SPF record up for the IP address of the sender which you can find inMailMessage.TimeStamps collection).

See the next sample on how to extract IP addresses from time stamps (Received headers). However, these sample represent only very basics of DNS-based spam filtering. For instance, SPF record may contain IP address ranges or special tokens like "mx" which need some additional processing.

Get reverse DNS records with DNS PTR query

Reverse DNS queries (also known as rDNS or DNS PTR) are used in many popular methods of filtering spam. You can also make rDNS queries for other needs, such as network diagnostics.

For a very simple code sample, see Smtp.GetPtrData method documentation.

The next two topics provide the extensive samples of checking rDNS to filter spam. Both samples check the IP address of the sender (if available in the Received header) and perform a DNS PTR query on it. After that, the samples do different things:

  • The first sample then just checks if the domain name returned by the rDNS query matches the domain name supplied in the EHLO/HELO command by the sender.
  • The second sample tries to guess if the returned domain name denotes a home PC (or something like that) rather than a full-fledged Internet server. It's assumed that serious server machines do not send spam while home computers are often infected with bots.

Use rDNS to check if sender's IP address matches HELO domain

This method is widely used by SMTP MX servers when they respond to the connection request from the sending party (which can be the relay SMTP server of the sender or the machine which directly sends e-mail).

An SMTP session starts with HELO or HELO command. The sending party issues a command like EHLO sending.host.com where sending.host.com must designate the external IP address or the external host name of the sending computer. In case if it's a host name, the SMTP MX server makes a reverse DNS query to resolve this host name into an IP address and makes sure the obtained IP address matches the actual IP address of the incoming connection.

As your application is not an SMTP MX server and does not accept connections from senders directly, it can only determine the incoming connection's IP address and HELO domain from the message headers if your SMTP MX server added them to the message before putting the message into your inbox. Most servers do this by adding a Received header. Still, the exact format depends on a particular server so you'll need to adapt the code for your particular server.

The console sample below gets the last e-mail in a POP3 e-mail account, extracts the sender's IP address and HELO/EHLO domain, and uses rDNS query to check if they match. The sample also correctly handles the situation when the HELO/EHLO domain is an IP address:

  • C#
  • VB
using System;
using System.Net;
using System.Text.RegularExpressions;
using MailBee;
using MailBee.Mime;
using MailBee.Pop3Mail;
using MailBee.SmtpMail;
using MailBee.DnsMX;

class Sample
{
    static string MatchIPAddress(string ipAddrString)
    {
        return Regex.Match(ipAddrString,
            @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").ToString();
    }

    // Examples of receivedFrom and the results.
    //
    // receivedFrom: [139.126.112.43] (helo=relay-5.company.com)
    // Results: ip=139.126.112.43, heloDomain=relay-5.company.com, heloIsIP=false.
    //
    // receivedFrom: [127.0.0.1] (account joe@my-pc.office HELO localhost)
    // Results: ip=127.0.0.1, heloDomain=localhost, heloIsIP=false.
    //
    // receivedFrom: [139.126.112.43] (helo=139.126.112.43)
    // Result: ip=139.126.112.43, heloDomain=139.126.112.43, heloIsIP=true.
    //
    // receivedFrom: 139.126.112.43 (helo=[139.126.112.43])
    // Results: ip=139.126.112.43, heloDomain=139.126.112.43, heloIsIP=true.
    static bool GetIPAddressAndHeloValue(string receivedFrom,
        ref string ip, ref string heloDomain, ref bool heloIsIP)
    {
        Match m = Regex.Match(receivedFrom,
            @"((?'ip'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)|" +
            @"(?i:helo(=| )(?'helo'\[?(\w|-|\.)+\]?))|(.))+");

        if (m.Groups["ip"].Length > 0)
        {
            ip = m.Groups["ip"].ToString();
            if (m.Groups["helo"].Length > 0)
            {
                heloDomain = m.Groups["helo"].ToString();

                // [127.0.0.1] => 127.0.0.1
                if (heloDomain.StartsWith("[") && heloDomain.EndsWith("]"))
                {
                    heloDomain = heloDomain.Substring(1, heloDomain.Length - 2);
                }

                // Is helloDomain value an IP address?
                heloIsIP = (MatchIPAddress(heloDomain).Length > 0);

                // Both IP address and hello domain found.
                return true;
            }
        }

        return false;
    }

    static void Main(string[] args)
    {
        // Get the last message from the POP3 server.
        MailMessage msg = Pop3.QuickDownloadMessage(
            "mail.domain.com", "jdoe", "secret", -1);

        Smtp mailer = new Smtp();

        // See in the log on how exactly MailBee.NET makes DNS queries.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = "C:\\Temp\\log.txt";
        mailer.Log.Clear();

        // Get ready for making DNS queries.
        mailer.DnsServers.Autodetect();

        string fromString = null;
        IPAddress ip = null;
        string fromIP = null;
        string fromHelloDomain = null;
        bool helloDomainIsIP = false;

        // Analyze the message we received from the POP3 server.
        if (msg.TimeStamps.Count > 0)
        {
            // Get the "from" part of the most recent Received header.
            fromString = msg.TimeStamps[0].From;

            Console.WriteLine("\"Received: from\" value: " + fromString);
            Console.WriteLine();

            // Get IP address and hello domain.
            if (GetIPAddressAndHeloValue(fromString,
                ref fromIP, ref fromHelloDomain, ref helloDomainIsIP))
            {
                Console.WriteLine("Received from IP: " + fromIP);
                Console.WriteLine("HELO/EHLO domain used by client: " +
                    fromHelloDomain);
                Console.WriteLine("HELO/EHLO domain is IP address: " +
                    helloDomainIsIP.ToString());
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("IP address and HELO domain not available");
                return;
            }

            // Check if the value is really an IP address.
            if (IPAddress.TryParse(fromIP, out ip))
            {
                Console.WriteLine("Sender's IP address: " + fromIP);
                Console.WriteLine();

                // In case if HELO/EHLO parameter is also an IP address,
                // just make sure both IP addresses match.
                if (helloDomainIsIP)
                {
                    // Is the IP address where the message came from the
                    // same as the IP address in HELO/EHLO parameter?
                    if (fromIP == fromHelloDomain)
                    {
                        Console.WriteLine("Both IP addresses match. Perfect!");
                    }
                    else
                    {
                        Console.WriteLine("IP addresses do NOT match!");
                    }
                }
                else
                {
                    string[] recs = null;

                    try
                    {
                        // Perform reverse DNS check for the sender's IP address.
                        recs = mailer.GetPtrData(fromIP);
                    }
                    catch (MailBeeDnsNameErrorException e)
                    {
                        Console.WriteLine("No rDNS for the host " + e.HostName);
                        return;
                    }
                    catch (MailBeeDnsRecordsDisabledException e)
                    {
                        Console.WriteLine("The local cache states " +
                            "there is no rDNS for the host " + e.Domain);
                        return;
                    }

                    if (recs != null)
                    {
                        Console.WriteLine("Reverse DNS record(s) found.");
                        Console.WriteLine();
                        foreach (string record in recs)
                        {
                            Console.WriteLine(record);

                            if (record.ToLower() == fromHelloDomain.ToLower())
                            {
                                Console.WriteLine("Perfect match!");
                            }
                            else
                            {
                                Console.WriteLine(record +
                                    " does not match " + fromHelloDomain);
                            }
                        }
                    }
                    else
                    {
                        // Can happen if the DNS record exists but empty.
                        Console.WriteLine(
                            "No corresponding rDNS record found for " + fromIP);
                    }
                }
            }
        }
    }
}

Imports System
Imports System.Net
Imports System.Text.RegularExpressions
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pop3Mail
Imports MailBee.SmtpMail
Imports MailBee.DnsMX

Module Module1
    Function MatchIPAddress(ByVal ipAddrString As String) As String
        Return Regex.Match(ipAddrString, _
            "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").ToString()
    End Function

    ' Examples of receivedFrom and the results.
    '
    ' receivedFrom: [139.126.112.43] (helo=relay-5.company.com)
    ' Results: ip=139.126.112.43, heloDomain=relay-5.company.com, heloIsIP=false.
    '
    ' receivedFrom: [127.0.0.1] (account joe@my-pc.office HELO localhost)
    ' Results: ip=127.0.0.1, heloDomain=localhost, heloIsIP=false.
    '
    ' receivedFrom: [139.126.112.43] (helo=139.126.112.43)
    ' Result: ip=139.126.112.43, heloDomain=139.126.112.43, heloIsIP=true.
    '
    ' receivedFrom: 139.126.112.43 (helo=[139.126.112.43])
    ' Results: ip=139.126.112.43, heloDomain=139.126.112.43, heloIsIP=true.
    Function GetIPAddressAndHeloValue(ByVal receivedFrom As String, _
            ByRef ip As String, ByRef heloDomain As String, _
            ByRef heloIsIP As Boolean) As Boolean
        Dim m As Match = Regex.Match(receivedFrom, _
            "((?'ip'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)|" & _
            "(?i:helo(=| )(?'helo'\[?(\w|-|\.)+\]?))|(.))+")

        If m.Groups("ip").Length > 0 Then
            ip = m.Groups("ip").ToString()
            If m.Groups("helo").Length > 0 Then
                heloDomain = m.Groups("helo").ToString()

                ' [127.0.0.1] => 127.0.0.1
                If heloDomain.StartsWith("[") And heloDomain.EndsWith("]") Then
                    heloDomain = heloDomain.Substring(1, heloDomain.Length - 2)
                End If

                ' Is helloDomain value an IP address?
                heloIsIP = MatchIPAddress(heloDomain).Length > 0

                ' Both IP address and hello domain found.
                Return True
            End If
        End If

        Return False
    End Function

    Sub Main()
        ' Get the last message from the POP3 server.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage( _
            "mail.domain.com", "jdoe", "secret", -1)

        Dim mailer As New Smtp()

        ' See in the log on how exactly MailBee.NET makes DNS queries.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Clear()

        ' Get ready for making DNS queries.
        mailer.DnsServers.Autodetect()

        Dim fromString As String = Nothing
        Dim ip As IPAddress = Nothing
        Dim fromIP As String = Nothing
        Dim fromHelloDomain As String = Nothing
        Dim helloDomainIsIP As Boolean = False

        ' Analyze the message we received from the POP3 server.
        If msg.TimeStamps.Count > 0 Then
            ' Get the "from" part of the most recent Received header.
            fromString = msg.TimeStamps(0).From

            Console.WriteLine("""Received: from"" value: " & fromString)
            Console.WriteLine()

            ' Get IP address and hello domain.
            If GetIPAddressAndHeloValue(fromString, _
                    fromIP, fromHelloDomain, helloDomainIsIP) Then
                Console.WriteLine("Received from IP: " & fromIP)
                Console.WriteLine("HELO/EHLO domain used by client: " & _
                    fromHelloDomain)
                Console.WriteLine("HELO/EHLO domain is IP address: " & _
                    helloDomainIsIP.ToString())
                Console.WriteLine()
            Else
                Console.WriteLine("IP address and HELO domain not available")
                Return
            End If

            ' Check if the value is really an IP address.
            If IPAddress.TryParse(fromIP, ip) Then
                Console.WriteLine("Sender's IP address: " & fromIP)
                Console.WriteLine()

                ' In case if HELO/EHLO parameter is also an IP address,
                ' just make sure both IP addresses match.
                If helloDomainIsIP Then
                    ' Is the IP address where the message came from the
                    ' same as the IP address in HELO/EHLO parameter?
                    If fromIP = fromHelloDomain Then
                        Console.WriteLine("Both IP addresses match. Perfect!")
                    Else
                        Console.WriteLine("IP addresses do NOT match!")
                    End If
                Else
                    Dim recs As String() = Nothing

                    Try
                        ' Perform reverse DNS check for the sender's IP address.
                        recs = mailer.GetPtrData(fromIP)
                    Catch e As MailBeeDnsNameErrorException
                        Console.WriteLine("No rDNS for the host " & e.HostName)
                        Return
                    Catch e As MailBeeDnsRecordsDisabledException
                        Console.WriteLine("The local cache states " & _
                            "there is no rDNS for the host " & e.Domain)
                        Return
                    End Try

                    If Not (recs Is Nothing) Then
                        Console.WriteLine("Reverse DNS record(s) found.")
                        Console.WriteLine()
                        Dim record As String
                        For Each record In recs
                            Console.WriteLine(record)

                            If record.ToLower() = fromHelloDomain.ToLower() Then
                                Console.WriteLine("Perfect match!")
                            Else
                                Console.WriteLine(record & _
                                    " does not match " & fromHelloDomain)
                            End If
                        Next record
                    Else
                        ' Can happen if the DNS record exists but empty.
                        Console.WriteLine( _
                            "No corresponding rDNS record found for " & fromIP)
                    End If
                End If
            End If
        End If
    End Sub
End Module

We assume your license key covers not only Smtp class but for Pop3 as well. The sample gets the e-mail to analyze from a POP3 server but you can get it from any source including an IMAP server.

Use rDNS query to find out if sender is home computer or Internet server

As most of spam is being sent from home systems, not Internet servers, it's enough to check if the sending part has a "good-looking" host name. If it doesn't, we probably deal with a personal computer which sends spam.

How can we know that the host name "looks good"? Good question.

Good records are somewhat like "mail.server.net", "smtp20.mail-cluster.mx.domain.com", etc. They should not have IP-address-alike sequences in their names which are "101.92.140.39.dynamic.isp.com" or "cable-78-109-33-05.provider.net" (typical external host names of home systems as assigned by ISPs).

As you can see, it's quite an informal definition which just tries to exploit naming habits of Internet providers which tend to use some common patterns for host names they assign to their customers. That's why it's pretty hard to distinguish between "good" and "bad" hosts, and requires a lot of coding to implement this.

The method discussed in the previous topic is simpler to implement but it's more limited and won't allow detecting spam if a spam program uses the correct host name in EHLO. The method discussed here, however, goes deeper and checks if the host name of the sending party (even if it's correct) has the format which is more typical for home systems rather than for Internet servers.

The spam program can put whatever it wants into EHLO command but it can't change the public IP address and the public host name of the machine it's sending from. And if this name looks suspicious, it can't do anything with it.

By the way, that's why it's so important to have a valid DNS PTR record and a good-looking public host name for your server which sends e-mail. Otherwise, other hosts will consider you a spam source.

The console sample below performs reverse DNS check for the IP address from which the e-mail came to the destination server. Unfortunately, there is no well-defined standard of storing the sender's IP address in the message so that the exact code may differ for your particular server. Moreover, as already said above, there is no strict rule of what is a good DNS record and what is not.

This sample assumes the sender's IP address is contained in the most recent Received header, and "good" DNS record is somewhat like "mx.domain.com" while "56.32.104.9.provider.net" is not. The e-mail message to check is taken from a POP3 server:

  • C#
  • VB
using System;
using System.Net;
using System.Text.RegularExpressions;
using MailBee;
using MailBee.Mime;
using MailBee.Pop3Mail;
using MailBee.SmtpMail;
using MailBee.DnsMX;

class Sample
{
    static string MatchIPAddress(string ipAddrString)
    {
        return Regex.Match(ipAddrString,
            @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").ToString();
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // See in the log on how exactly MailBee.NET makes DNS queries.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = "C:\\Temp\\log.txt";
        mailer.Log.Clear();

        // Get ready for making DNS queries.
        mailer.DnsServers.Autodetect();

        // Get last message from the POP3 server.
        MailMessage msg = Pop3.QuickDownloadMessage(
            "mail.domain.com", "jdoe", "secret", -1);

        string ipAddrString = null;
        IPAddress ip = null;

        if (msg.TimeStamps.Count > 0)
        {
            ipAddrString = msg.TimeStamps[0].From;

            // Remove everything but IP address.
            ipAddrString = MatchIPAddress(ipAddrString);

            // Check if the value is an IP address.
            if (IPAddress.TryParse(ipAddrString, out ip))
            {
                try
                {
                    Console.WriteLine(
                        "Sender's IP address is " + ipAddrString);
                    Console.WriteLine();

                    // Perform reverse DNS check for this IP address.
                    // Ignore "name not found" exceptions if failed
                    // (this indicates spam with no valid rDNS).
                    string[] recs = mailer.GetPtrData(ipAddrString);

                    if (recs != null)
                    {
                        Console.WriteLine("Reverse DNS record found.");
                        Console.WriteLine("Will report all records now.");
                        Console.WriteLine("Records:");
                        foreach (string record in recs)
                        {
                            // Display the record found. We'll then check
                            // if the record is "good" in terms of rDNS
                            // spam checks.
                            Console.Write(record);

                            bool isGoodName = false;

                            // If the record contains IP address, no good.
                            ipAddrString = MatchIPAddress(record);

                            if (ipAddrString == string.Empty)
                            {
                                string[] parts = record.Split('.');

                                // If no dot, this is a local name - no good.
                                if (parts.Length > 1)
                                {
                                    // Short name like mail.domain.com is good.
                                    if (parts.Length <= 3)
                                    {
                                        isGoodName = true;
                                    }
                                    else
                                    {
                                        int nonLetterCount = 0;
                                        isGoodName = true;

                                        // Check first two sections for
                                        // IP-address like things and digits.
                                        for (int i = 0; i < 2; i++)
                                        {
                                            // Check if looks like
                                            // "adsl-11-22-33-44".
                                            ipAddrString =
                                                parts[i].Replace('-', '.');

                                            if (MatchIPAddress(ipAddrString) !=
                                                string.Empty)
                                            {
                                                // IP-address-alike is not a
                                                // good record (home system).
                                                nonLetterCount = 0;
                                                isGoodName = false;
                                                break;
                                            }

                                            for (int j = 0;
                                                j < parts[i].Length; j++)
                                            {
                                                if (!char.IsLetter(
                                                    parts[i][j]))
                                                {
                                                    nonLetterCount++;
                                                }
                                            }
                                        }

                                        // Too much digits and dashes - no good.
                                        if (isGoodName && nonLetterCount >= 5)
                                        {
                                            isGoodName = false;
                                        }
                                    }
                                }
                            }

                            if (isGoodName)
                            {
                                Console.WriteLine(" looks good (server host)");
                            }
                            else
                            {
                                Console.WriteLine(" looks bad (home host?)");
                            }
                        }
                    }
                }
                catch (MailBeeDnsNameErrorException) { }
                catch (MailBeeDnsRecordsDisabledException) { }
            }
        }
    }
}

Imports System
Imports System.Net
Imports System.Text.RegularExpressions
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pop3Mail
Imports MailBee.SmtpMail
Imports MailBee.DnsMX

Module Module1
    Function MatchIPAddress(ByVal ipAddrString As String) As String
        Return Regex.Match(ipAddrString, _
            "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").ToString()
    End Function

    Sub Main()
        Dim mailer As New Smtp()

        ' See in the log on how exactly MailBee.NET makes DNS queries.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Clear()

        ' Get ready for making DNS queries.
        mailer.DnsServers.Autodetect()

        ' Get last message from the POP3 server.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage( _
            "mail.domain.com", "jdoe", "secret", -1)

        Dim ipAddrString As String = Nothing
        Dim ip As IPAddress = Nothing

        If msg.TimeStamps.Count > 0 Then
            ipAddrString = msg.TimeStamps(0).From

            ' Remove everything but IP address.
            ipAddrString = MatchIPAddress(ipAddrString)

            ' Check if the value is an IP address.
            If IPAddress.TryParse(ipAddrString, ip) Then
                Try
                    Console.WriteLine("Sender's IP address is " & ipAddrString)
                    Console.WriteLine()

                    ' Perform reverse DNS check for this IP address.
                    ' Ignore "name not found" exceptions if failed
                    ' (this indicates spam with no valid rDNS).
                    Dim recs As String() = mailer.GetPtrData(ipAddrString)

                    If Not (recs Is Nothing) Then
                        Console.WriteLine("Reverse DNS record found.")
                        Console.WriteLine("Will report all records now.")
                        Console.WriteLine("Records:")
                        Dim record As String
                        For Each record In recs
                            ' Display the record found. We'll then check
                            ' if the record is "good" in terms of rDNS
                            ' spam checks.
                            Console.Write(record)

                            Dim isGoodName As Boolean = False

                            ' If the record contains IP address, no good.
                            ipAddrString = MatchIPAddress(record)

                            If ipAddrString = String.Empty Then
                                Dim parts As String() = record.Split("."c)

                                ' If no dot, this is a local name - no good.
                                If parts.Length > 1 Then
                                    ' Short name like mail.domain.com is good.
                                    If parts.Length <= 3 Then
                                        isGoodName = True
                                    Else
                                        Dim nonLetterCount As Integer = 0
                                        isGoodName = True

                                        ' Check first two sections for
                                        ' IP-address like things and digits.
                                        Dim i As Integer
                                        For i = 0 To 1
                                            ' Check if looks like
                                            ' "adsl-11-22-33-44".
                                            ipAddrString = _
                                                parts(i).Replace("-"c, "."c)

                                            If MatchIPAddress( _
                                                ipAddrString) <> _
                                                String.Empty Then
                                                ' IP-address-alike is not a
                                                ' good record (home system).
                                                nonLetterCount = 0
                                                isGoodName = False
                                                Exit For
                                            End If

                                            Dim j As Integer
                                            For j = 0 To (parts(i).Length) - 1
                                                If Not _
                                                    Char.IsLetter( _
                                                        parts(i)(j)) Then
                                                    nonLetterCount += 1
                                                End If
                                            Next j
                                        Next i

                                        ' Too much digits and dashes - no good.
                                        If isGoodName And _
                                            nonLetterCount >= 5 Then
                                            isGoodName = False
                                        End If
                                    End If
                                End If
                            End If

                            If isGoodName Then
                                Console.WriteLine(" looks good (server host)")
                            Else
                                Console.WriteLine(" looks bad (home host?)")
                            End If
                        Next record
                    End If
                Catch e As MailBeeDnsNameErrorException
                Catch e As MailBeeDnsRecordsDisabledException
                End Try
            End If
        End If
    End Sub
End Module

We assume your license key covers not only Smtp class but Pop3 as well. The sample gets the e-mail to analyze from a POP3 server but you can get it from any source including an IMAP server.

The idea is to get rDNS records and check what's in there. If the record looks like "12.34.65.111.users.provider.com" or "dsl-134-50-127-9.telecom.net", this is probably home machine (not a network server), and such machine should not try to send e-mail without relay server (and most likely it's a spam source).

Note that this example (though it's big) still just demonstrates the idea, it should not be used in production. Real-world reverse DNS check can be even much more complicated to allow for different formats of "Received" headers from which time stamps are taken, more sophisticated patterns of "good" and "not good" host names, etc.

Send feedback to AfterLogic


Send multiple individual e-mails or send through multiple servers

  • Introduction
  • Send two e-mails in single session
  • Send two e-mails in single session via SSL or STARTTLS
  • Send bulk e-mail through two SMTP relay servers for increased throughput
  • Send through main SMTP relay server or through fail-over SMTP relay server if main server is down
  • Send through SMTP relay server or use direct send if SMTP relay server is down
  • Submit to MailBee.NET Queue for increased or limited throughput
  • Throttle throughput (limit sending rate)
  • Performance optimization

Introduction

Sending large volumes of e-mails raises a number of performance and security considerations, and they often contradict each other. To name a few:

Ways to improve performance | Limitations imposed by many SMTP servers
It's much faster to send several e-mails through a single SMTP session than to send one e-mail per session. | You can't send unlimited number of e-mails per session.
It's usually faster to send several e-mails simultaneously in separate threads (and each thread can send multiple e-mails per session). | You can't make multiple simultaneous connections from a single IP address.
Higher sending rate allows for quicker delivery of bulk mail. | The maximum allowed number of e-mails which can be accepted in a hour or day from a single IP address is strictly limited.

If you face such issues, you'll need to achieve balance between the performance and the security limitations of your e-mail server. For instance, send no more than 10 e-mails per session and use up to 3 simultaneous connections if these are the limits, and so on. MailBee.NET provides the extensive settings for that.

Also, you can send through multiple SMTP servers for better throughput and reliability, or use a mail queue like MailBee.NET Queue to deliver your e-mails.

This guide demonstrates different techniques of improving performance, reducing memory usage, error handling and dealing with other issues related to bulk mailing.

Send two e-mails in single session

If you compose a message, then call Smtp.Send, then compose another and call Smtp.Send again, MailBee.NET will establish the connection twice. For better performance, you can establish the connection manually and send both e-mails within a single SMTP session:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.provider.com", "joe@company.com", "secret");

// Connect and authenticate.
mailer.Connect();
mailer.Hello();
mailer.Login();

// Set up 1st simple e-mail.
mailer.Message.From.Email = "joe@company.com";
mailer.Message.To = new EmailAddressCollection("jane@domain.com");
mailer.Message.Subject = "Message for Jane";
mailer.Message.BodyPlainText = "This is a test message for Jane.";

// Send 1st e-mail.
mailer.Send();

// Set up 2nd simple e-mail from the same sender joe@company.com.
mailer.Message.To = new EmailAddressCollection("carl@example.com");
mailer.Message.Subject = "Message for Carl";
mailer.Message.BodyPlainText = "This is a test message for Carl.";

// Send 2nd e-mail.
mailer.Send();

// Since we connected manually, we need to disconnect manually either.
mailer.Disconnect();

Dim mailer As New Smtp()

' Use SMTP relay with authentication.
mailer.SmtpServers.Add("smtp.provider.com", "joe@company.com", "secret")

' Connect and authenticate.
mailer.Connect()
mailer.Hello()
mailer.Login()

' Set up 1st simple e-mail.
mailer.Message.From.Email = "joe@company.com"
mailer.Message.To = New EmailAddressCollection("jane@domain.com")
mailer.Message.Subject = "Message for Jane"
mailer.Message.BodyPlainText = "This is a test message for Jane."

' Send 1st e-mail.
mailer.Send()

' Set up 2nd simple e-mail from the same sender joe@company.com.
mailer.Message.To = New EmailAddressCollection("carl@example.com")
mailer.Message.Subject = "Message for Carl"
mailer.Message.BodyPlainText = "This is a test message for Carl."

' Send 2nd e-mail.
mailer.Send()

' Since we connected manually, we need to disconnect manually either.
mailer.Disconnect()

We assume mailer is an Smtp object instance. In addition to that, for all the samples in this guide we assume MailBee, MailBee.Mime, and MailBee.SmtpMail namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

As you can see, we do not set "From:" address for the second e-mail in the series. Smtp object does not destroy the message upon sending so you can reuse its contents for subsequent messages. If you, however, need to reset it, call Smtp.ResetMessage method.

Send two e-mails in single session via SSL or STARTTLS

The sample in this topic adds the following functionality to the previous sample:

  • Logging into a file. Just a few more lines but a great help for troubleshooting.
  • STARTTLS or SSL connection with the server.
  • Attachments and different body formats (plain-text and HTML) for different e-mails.
  • Also, we specify the sender and the recipients in different ways, just for demonstration purposes.

Note that to compile this sample you also need to import MailBee.Security namespace. No additional license keys, though.

  • C#
  • VB
Smtp mailer = new Smtp();

// Let's enable logging SMTP session into a file so that you can then
// examine which commands MailBee.NET sent to the server and how many
// connections it has made.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

// Use SMTP relay with authentication.
SmtpServer server = mailer.SmtpServers.Add("smtp.company.com", "sender", "secret");

// Use STARTTLS (SSL over regular SMTP port) when it's supported.
server.SslMode = SslStartupMode.UseStartTlsIfSupported;

// Or uncomment to use dedicated SSL connection over port 465.
// server.SslMode = SslStartupMode.OnConnect;
// server.Port = 465;

// Connect and authenticate.
mailer.Connect();
mailer.Hello();
mailer.Login();

// Set 1st e-mail (plain-text with attachment).
mailer.Message.From = new EmailAddress("joe@company.com", "Joe T.");
mailer.Message.To.Add("jane@domain.com", "Jane D.");
mailer.Message.To.Add("mike@domain.com", "Mike R.");
mailer.Message.Subject = "Message #1";
mailer.Message.BodyPlainText = "plain-text message";
mailer.Message.Attachments.Add(@"C:\Docs\document1.doc");

// Send 1st e-mail.
mailer.Send();

// If you don't reset the message, you'd need to clear some properties
// manually (for instance, clear Attachments collection). But if all
// your e-mails contain the same set of attachments, you can optimize
// the performance and don't reset the message to have the attachments
// reused for every message being sent.
mailer.ResetMessage();

// Set 2nd e-mail (HTML with attachment).
mailer.Message.From.AsString = "Bill T. <bill@company.com>";
mailer.Message.To.AsString = "Susan C. <susan@domain.com";
mailer.Message.To.AddFromString("Gregory <greg@example.com>");
mailer.Message.Subject = "Message #2";
mailer.Message.BodyHtmlText = "<html>HTML message</html>";
mailer.Message.Attachments.Add(@"C:\Docs\document2.doc");

// Send 2nd e-mail.
mailer.Send();

// Since we connected manually, we need to disconnect manually either.
mailer.Disconnect();

Dim mailer As New Smtp()

' Let's enable logging SMTP session into a file so that you can then
' examine which commands MailBee.NET sent to the server and how many
' connections it has made.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay with authentication.
Dim server As SmtpServer = mailer.SmtpServers.Add("smtp.company.com", "sender", "secret")

' Use STARTTLS (SSL over regular SMTP port) when it's supported.
server.SslMode = SslStartupMode.UseStartTlsIfSupported

' Or uncomment to use dedicated SSL connection over port 465.
' server.SslMode = SslStartupMode.OnConnect
' server.Port = 465

' Connect and authenticate.
mailer.Connect()
mailer.Hello()
mailer.Login()

' Set 1st e-mail (plain-text with attachment).
mailer.Message.From = New EmailAddress("joe@company.com", "Joe T.")
mailer.Message.To.Add("jane@domain.com", "Jane D.")
mailer.Message.To.Add("mike@domain.com", "Mike R.")
mailer.Message.Subject = "Message #1"
mailer.Message.BodyPlainText = "plain-text message"
mailer.Message.Attachments.Add("C:\Docs\document1.doc")

' Send 1st e-mail.
mailer.Send()

' If you don't reset the message, you'd need to clear some properties
' manually (for instance, clear Attachments collection). But if all
' your e-mails contain the same set of attachments, you can optimize
' the performance and don't reset the message to have the attachments
' reused for every message being sent.
mailer.ResetMessage()

' Set 2nd e-mail (HTML with attachment).
mailer.Message.From.AsString = "Bill T. <bill@company.com>"
mailer.Message.To.AsString = "Susan C. <susan@domain.com"
mailer.Message.To.AddFromString("Gregory <greg@example.com>")
mailer.Message.Subject = "Message #2"
mailer.Message.BodyHtmlText = "<html>HTML message</html>"
mailer.Message.Attachments.Add("C:\Docs\document2.doc")

' Send 2nd e-mail.
mailer.Send()

' Since we connected manually, we need to disconnect manually either.
mailer.Disconnect()

Send bulk e-mail through two SMTP relay servers for increased throughput

To send large volumes of e-mails you can use a number of methods listed in Introduction. The sample below uses them all, including multi-threading. All parameters of the SMTP servers being used are set for optimal performance. If the server implies some restrictions on the sending process (such as maximum number of simultaneous IP connections from a single IP address), you can adjust the corresponding parameters of SmtpServerobjects which represent the relay servers being used.

Unlike previous samples, this sample does not explicitly call Smtp.Connect method. Instead, it uses the concept of jobs (see Bulk mail, explained topic for details).

Smtp.SendJobs method is smart enough to automatically connect to the server, send multiple number of e-mails over this connection, automatically disconnect if the maximum number of message per session reached, reconnect, and so on. It can also distribute the load between multiple servers, use fail-over servers, and so on.

By the way, the regular Smtp.Send method is also capable of using fail-over servers. See Send through main SMTP relay server or through fail-over SMTP relay server if main server is down topic on this.

The sample generates and sends 100 e-mails. Note that we do not generate all the e-mails at once. Instead, we generate only 20 e-mails as initial portion (so that up to 20 e-mails could be sent simultaneously). If we generated 100 e-mails at once, they would have occupied pretty much memory (imagine if you had 10.000 e-mails to be sent). Instead, this sample shows how to "feed" the jobs list while Smtp.SendJobs method is running. In other words, you can add new jobs when some jobs are already being processed.

However, when creating a mail merge job, you do not need to worry about such optimizations of memory use. MailBee.NET creates an individual e-mail in a mail merge series and keeps it in memory only for a short moment while this e-mail is being sent.

Last note is on multi-threading. This sample enables logging of all the activities into a file, and the extended format of the log file is used to make it easier to track individual sending threads.

Also, you may ask "where is the synchronization of access to the collection of pending jobs?". Such synchronization is needed to make sure no race condition occurs in case when you modify the collection by adding a new job in the main thread while the worker thread of MailBee.NET modifies the same collection by extracting the existing job at the very same moment. So, how to get things synchronized?

The answer: Smtp.AddJob and Smtp.RetryFailedJobs methods are automatically synchronized, for the rest you can use Smtp.JobsSyncRoot property.

Here we go:

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    static int i;

    // Creates an e-mail and adds it into the list of pending jobs.
    // For brevity, all e-mails are very simple. In real-world apps,
    // you can make e-mails as complex as you need.
    static void AddEmailAsJob(Smtp mailer)
    {
        string s = i.ToString("000"); // 25 -> "025".
        mailer.Message.From.AsString = "joe@domain.com";

        // For every even i (2, 4, ..., 100) we'll generate invalid e-mail
        // address with missing "@" character to demonstrate what happens
        // in case of an error.
        string at = (i % 2) == 0 ? "" : "@";

        mailer.Message.To.AsString = "user_" + s + at + "company.com";
        mailer.Message.Subject = "Message #" + s;
        mailer.Message.BodyPlainText = "Text of message #" + s;
        mailer.AddJob(s, null, null);
    }

    // In case if less than 100 e-mails have been made to the moment,
    // create one more. To free memory, finished job won't be preserved.
    static void OnJobReady(object sender, SmtpFinishingJobEventArgs e)
    {
        Smtp mailer = (Smtp)sender;

        if (i <= 100)
        {
            AddEmailAsJob(mailer);
            i++;
        }

        if (e.IsSuccessful)
        {
            Console.WriteLine("Sent to " + e.Job.Recipients.ToString());
        }
        else
        {
            Console.WriteLine(e.Job.ErrorReason.Message);
        }

        Console.WriteLine();

        // We don't want the e-mail be kept in memory as we need to create
        // subsequent e-mails, and the memory resource is limited.
        e.KeepIt = false;
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        mailer.Log.Enabled = true;
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Use SMTP relays with authentication. Both relay have the same
        // priority and the load will be distributed equally between them.
        SmtpServer server1 =
            mailer.SmtpServers.Add("smtp1.domain.com", "joe", "secret");
        SmtpServer server2 =
            mailer.SmtpServers.Add("smtp2.domain.com", "joe", "secret");

        // Configure 1st server for optimal performance. Actually,
        // these are the default values so we list them here for
        // demonstration purposes only.
        server1.PauseInterval = 0;
        server1.MaxConnectionCount = -1;
        server1.MaxSendPerSessionCount = -1;

        // Let's use up to 20 threads.
        mailer.MaxThreadCount = 20;

        // Feed Smtp object with 20 e-mails to be sent.
        // This is the minimum count to feed all 20 threads.
        // However, it's not a requirement, you can use any
        // combinations of numbers of threads and jobs.
        for (i = 1; i <= 20; i++)
        {

            AddEmailAsJob(mailer);
        }

        // Will use it to add more jobs when SendJobs is working.
        mailer.FinishingJob += new SmtpFinishingJobEventHandler(OnJobReady);

        // This will send 100 e-mails in spite of we initially added only 20.
        mailer.SendJobs();
    }
}

Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    Dim i As Integer

    ' Creates an e-mail and adds it into the list of pending jobs.
    ' For brevity, all e-mails are very simple. In real-world apps,
    ' you can make e-mails as complex as you need.
    Sub AddEmailAsJob(ByVal mailer As Smtp)
        Dim s As String = i.ToString("000") ' 25 -> "025".
        mailer.Message.From.AsString = "joe@domain.com"

        ' For every even i (2, 4, ..., 100) we'll generate invalid e-mail
        ' address with missing "@" character to demonstrate what happens
        ' in case of an error.
        Dim at As String = IIf(i Mod 2 = 0, "", "@")
        mailer.Message.To.AsString = "user_" & s & at & "company.com"
        mailer.Message.Subject = "Message #" & s
        mailer.Message.BodyPlainText = "Text of message #" & s
        mailer.AddJob(s, Nothing, Nothing)
    End Sub

    ' In case if less than 100 e-mails have been made to the moment,
    ' create one more. To free memory, finished job won't be preserved.
    Sub OnJobReady(ByVal sender As Object, _
            ByVal e As SmtpFinishingJobEventArgs)
        Dim mailer As Smtp = CType(sender, Smtp)

        If i <= 100 Then
            AddEmailAsJob(mailer)
            i += 1
        End If

        If e.IsSuccessful Then
            Console.WriteLine(("Sent to " & e.Job.Recipients.ToString()))
        Else
            Console.WriteLine(e.Job.ErrorReason.Message)
        End If

        Console.WriteLine()

        ' We don't want the e-mail be kept in memory as we need to create
        ' subsequent e-mails, and the memory resource is limited.
        e.KeepIt = False
    End Sub

    Sub Main()
        Dim mailer As New Smtp()

        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Use SMTP relays with authentication. Both relay have the same
        ' priority and the load will be distributed equally between them.
        Dim server1 As SmtpServer = _
            mailer.SmtpServers.Add("smtp1.domain.com", "joe", "secret")
        Dim server2 As SmtpServer = _
            mailer.SmtpServers.Add("smtp2.domain.com", "joe", "secret")

        ' Configure 1st server for optimal performance. Actually,
        ' these are the default values so we list them here for
        ' demonstration purposes only.
        server1.PauseInterval = 0
        server1.MaxConnectionCount = -1
        server1.MaxSendPerSessionCount = -1

        ' Let's use up to 20 threads.
        mailer.MaxThreadCount = 20

        ' Feed Smtp object with 20 e-mails to be sent.
        ' This is the minimum count to feed all 20 threads.
        ' However, it's not a requirement, you can use any
        ' combinations of numbers of threads and jobs.
        For Module1.i = 1 To 20

            AddEmailAsJob(mailer)
        Next i

        ' Will use it to add more jobs when SendJobs is working.
        AddHandler mailer.FinishingJob, AddressOf OnJobReady

        ' This will send 100 e-mails in spite of we initially added only 20.
        mailer.SendJobs()
    End Sub
End Module

To learn how you can increase performance further, refer to Performance optimization topic.

Note that you cannot use some methods of Smtp class while in multi-threaded mode. See Smtp.IsSmtpContext property documentation for details.

Send through main SMTP relay server or through fail-over SMTP relay server if main server is down

You can assign different priorities to your SMTP relay servers so that some servers would be used only if primary servers are not available. In this sample, we use 1 primary and 1 backup server. You can use as many as you need. This is compatible with bulk mail too and you can still have multiple servers of the same priority to distribute the load amongst them.

So that you can have, let's say, a server farm of 5 primary servers of the top priority (priority=0), plus 10 secondary slow servers (priority=1) used when the primary servers are down, and a low-priority server or your ISP (priority=2) which will be used when the secondary servers go down too.

This sample sends a single e-mail through a primary SMTP relay server. If it fails, the secondary server is tried, and warning is saved into the log file:

  • C#
  • VB
Smtp mailer = new Smtp();

// You can see in the log what happens if the primary server
// is down and how the second server is being tried then.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

// Use SMTP relays with authentication.
SmtpServer server1 =
    mailer.SmtpServers.Add("smtp1.domain.com", "j.doe", "secret");
SmtpServer server2 =
    mailer.SmtpServers.Add("smtp2.domain.com", "j.doe", "secret");

// Simulate a problem with the primary server by giving it
// incorrect host name.
server1.Name = "nonsense";

// Lower the priority of 2nd server. MailBee.NET will use it
// only as a fail-over server when 1st server is down.
server2.Priority = 1;

mailer.Message.From.AsString = "John Doe <j.doe@domain.com>";
mailer.Message.To.AsString = "Jane Doe <jane@example.com>";
mailer.Message.Subject = "Important message for Jane";
mailer.Message.BodyPlainText = "Meet me tomorrow";

// Send through "nonsense". If it's down (and it certainly is),
// send through smtp2.domain.com then.
mailer.Send();

Dim mailer As New Smtp()

' You can see in the log what happens if the primary server
' is down and how the second server is being tried then.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relays with authentication.
Dim server1 As SmtpServer = _
    mailer.SmtpServers.Add("smtp1.domain.com", "j.doe", "secret")
Dim server2 As SmtpServer = _
    mailer.SmtpServers.Add("smtp2.domain.com", "j.doe", "secret")

' Simulate a problem with the primary server by giving it
' incorrect host name.
server1.Name = "nonsense"

' Lower the priority of 2nd server. MailBee.NET will use it
' only as a fail-over server when 1st server is down.
server2.Priority = 1

mailer.Message.From.AsString = "John Doe <j.doe@domain.com>"
mailer.Message.To.AsString = "Jane Doe <jane@example.com>"
mailer.Message.Subject = "Important message for Jane"
mailer.Message.BodyPlainText = "Meet me tomorrow"

' Send through "nonsense". If it's down (and it certainly is),
' send through smtp2.domain.com then.
mailer.Send()

If you would also like to monitor such non-critical failures with events, subscribe to Smtp.ErrorOccurred event. It occurs in many cases, including situations when MailBee.NET needs to switch to the fail-over server.

Send through SMTP relay server or use direct send if SMTP relay server is down

The topics above deal only with SMTP relay servers. However, you can mix the use of SMTP relay servers with direct send. To learn more on direct send, refer to Direct send without SMTP relay server guide.

For instance, let's assume you have:

  • 2 SMTP relay servers of priority=0.
  • 4 DNS servers of priority=0.
  • 1 SMTP relay server of priority=1.

In this case, bulk mail operations will distribute the load between 2 SMTP relays of top priority, downgrade to direct send and distribute the load of making DNS MX lookup queries between 4 DNS servers, and if they fail too, use the lowest priority SMTP relay server.

Thus, direct send can be both low or high priority in comparison to SMTP relay send, and you can build very complex and powerful fail-over schemas with this feature.

This sample sends a single e-mail through a primary SMTP relay server. If it fails, the direct send is tried, and warning is saved into the log file:

  • C#
  • VB
Smtp mailer = new Smtp();

// You can see in the log what happens if the primary server
// is down and how direct send via DNS MX lookup is tried then.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

// Use SMTP relay with authentication.
SmtpServer relay =
    mailer.SmtpServers.Add("smtp.domain.com", "j.doe", "secret");

if (!mailer.DnsServers.Autodetect())
{
    // Add DNS server manually if couldn't autodetect them
    // from the system.
    mailer.DnsServers.Add("192.168.0.1");
}

// We do not need to manually lower the priority for DNS servers
// to make them the backup method of sending because if SMTP and
// DNS servers have the same priority value (zero by default),
// SMTP server is always selected. However, in case if you need
// to change DNS server priority, that's how you can do this.
foreach (DnsServer dns in mailer.DnsServers)
{
    dns.Priority = 1;
}

// Simulate a problem with the primary server by giving it
// incorrect host name.
relay.Name = "nonsense";

mailer.Message.From.AsString = "John Doe <j.doe@domain.com>";
mailer.Message.To.AsString = "Jane Doe <jane@example.com>";
mailer.Message.Subject = "Important message for Jane";
mailer.Message.BodyPlainText = "Meet me tomorrow";

// Send through "nonsense". If it's down (and it certainly is),
// direct send will be used.
mailer.Send();

Dim mailer As New Smtp()

' You can see in the log what happens if the primary server
' is down and how direct send via DNS MX lookup is tried then.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay with authentication.
Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.domain.com", "j.doe", "secret")

If Not mailer.DnsServers.Autodetect() Then
    ' Add DNS server manually if couldn't autodetect them
    ' from the system.
    mailer.DnsServers.Add("192.168.0.1")
End If

' We do not need to manually lower the priority for DNS servers
' to make them the backup method of sending because if SMTP and
' DNS servers have the same priority value (zero by default),
' SMTP server is always selected. However, in case if you need
' to change DNS server priority, that's how you can do this.
Dim dns As DnsServer
For Each dns In mailer.DnsServers
    dns.Priority = 1
Next dns

' Simulate a problem with the primary server by giving it
' incorrect host name.
relay.Name = "nonsense"

mailer.Message.From.AsString = "John Doe <j.doe@domain.com>"
mailer.Message.To.AsString = "Jane Doe <jane@example.com>"
mailer.Message.Subject = "Important message for Jane"
mailer.Message.BodyPlainText = "Meet me tomorrow"

' Send through "nonsense". If it's down (and it certainly is),
' direct send will be used.
mailer.Send()

Note that you'll also need to import MailBee.DnsMX namespace to compile this sample.

Submit to MailBee.NET Queue for increased or limited throughput

The ultimate answer on the question "how to quickly and reliably send e-mails?" is using a mail queue. If your e-mail server is IIS SMTP or compatible, you can submit e-mails directly to its pickup folder bypassing the SMTP protocol at all. No need to make network connections, pass through firewalls and so on.

If you do not have a local SMTP server or it does not support the pickup folder service, you can use MailBee.NET Queue instead. In this case, you'll still need to have an SMTP relay server (MailBee.NET Queue can use direct send but a dedicated SMTP relay is much more preferable). Also, the firewall must allow connections from MailBee.NET Queue to the relay server. But the major benefit is that your application now off-loads the task of delivering e-mails to MailBee.NET Queue can can focus on other tasks.

MailBee.NET Queue can send with multi-threading for better performance, allows you to limit the throughput if your SMTP server requires this (for instance, limit the maximum number of e-mails being sent per minute). By the way, MailBee.NET Queue is shipped with the source code so you can use it as an advanced sample of building a high-performance e-mail sending application with MailBee.NET SMTP component.

You can also use MailBee.NET Queue as a fail-over method of sending e-mail in your application. For instance, if the relay server is down at the current moment, you can submit the message to the MailBee.NET Queue and proceed with other tasks. When the server is up again, MailBee.NET Queue will deliver the message.

Several Visual Studio sample projects demonstrating how to submit e-mails to MailBee.NET Queue (including mail merge) are shipped with MailBee.NET Queue itself. Once installed MailBee.NET Queue, you can find them in Samples section of Start /Programs / MailBee.NET Queue menu.

This sample below sends a e-mail to the SMTP relay server and switches to MailBee.NET Queue in case if the server is down.

Note that the sample does not switch to MailBee.NET Queue in case of some errors. For instance, if the server replied that the specified recipient's e-mail address is invalid, the server isn't down, it just that the message is bad and MailBee.NET Queue won't deliver it either. In such case when the problem is with the message itself, the sample throws an exception:

  • C#
  • VB
Smtp mailer = new Smtp();

// You can see in the log the difference between "the server is down"
// and "the server specially rejected the message".
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Use SMTP relay with authentication.
SmtpServer relay =
    mailer.SmtpServers.Add("smtp.domain.com", "j.doe", "secret");

// Simulate a problem with the relay server by giving it
// incorrect host name. Comment this to use the real server.
relay.Name = "nonsense";

// Note missing @ in To address. We demonstrate what happens
// if the server is OK but the e-mail isn't.
mailer.Message.To.AsString = "Jane Doe <janeexample.com>";

// Set other fields of the e-mail.
mailer.Message.From.AsString = "John Doe <j.doe@domain.com>";
mailer.Message.Subject = "Important message for Jane";
mailer.Message.BodyPlainText = "Meet me tomorrow";

// Send through "nonsense" if you haven't commented it out.
// If the relay server is down, will submit to MailBee.NET Queue.
bool useQueue = false;
try
{
    mailer.Send();
}
catch (MailBeeSmtpSendNegativeResponseException e)
{
    // If the server replied with a negative reply during sending
    // e-mail, this probably means the message is incorrect and we
    // should not retry with MailBee.NET Queue.

    // Check if the error is with the server, not with the message.
    // In theory, permanent error can also be the problem of the
    // server but if the server is configured correctly and we use
    // correct credentials for authentication, it should generate
    // permanent errors only for bad messages.
    if (e.IsTransientError)
    {
        // Temporary error, makes sense to try again later with
        // MailBee.NET Queue.
        useQueue = true;
    }
    else
    {
        // The message is probably bad, doesn't make sense to try
        // again with MailBee.NET Queue.
        throw;
    }
}
catch (MailBeeNetworkException)
{
    // The server is down or another error occurred but it does not
    // look to be related to the fact that the message is bad.
    useQueue = true;
}

// If could not send normally, submit the message as .EML file
// into the pickup folder of MailBee.NET Queue for later delivery.
// Or, we could have written into IIS SMTP Pickup folder.
if (useQueue)
{
    mailer.SubmitToPickupFolder(
        "C:\\MailBeeNetQueue Files\\Pickup", false);
}

Dim mailer As New Smtp()

' You can see in the log the difference between "the server is down"
' and "the server specially rejected the message".
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay with authentication.
Dim relay As SmtpServer = _
    mailer.SmtpServers.Add("smtp.domain.com", "j.doe", "secret")

' Simulate a problem with the relay server by giving it
' incorrect host name. Comment this to use the real server.
relay.Name = "nonsense"

' Note missing @ in To address. We demonstrate what happens
' if the server is OK but the e-mail isn't.
mailer.Message.To.AsString = "Jane Doe <janeexample.com>"

' Set other fields of the e-mail.
mailer.Message.From.AsString = "John Doe <j.doe@domain.com>"
mailer.Message.Subject = "Important message for Jane"
mailer.Message.BodyPlainText = "Meet me tomorrow"

' Send through "nonsense" if you haven't commented it out.
' If the relay server is down, will submit to MailBee.NET Queue.
Dim useQueue As Boolean = False
Try
    mailer.Send()
Catch e As MailBeeSmtpSendNegativeResponseException
    ' If the server replied with a negative reply during sending
    ' e-mail, this probably means the message is incorrect and we
    ' should not retry with MailBee.NET Queue.
    ' Check if the error is with the server, not with the message.
    ' In theory, permanent error can also be the problem of the
    ' server but if the server is configured correctly and we use
    ' correct credentials for authentication, it should generate
    ' permanent errors only for bad messages.
    If e.IsTransientError Then
        ' Temporary error, makes sense to try again later with
        ' MailBee.NET Queue.
        useQueue = True
    Else
        ' The message is probably bad, doesn't make sense to try
        ' again with MailBee.NET Queue.
        Throw
    End If
Catch e As MailBeeNetworkException
    ' The server is down or another error occurred but it does not
    ' look to be related to the fact that the message is bad.
    useQueue = True
End Try

' If could not send normally, submit the message as .EML file
' into the pickup folder of MailBee.NET Queue for later delivery.
' Or, we could have written into IIS SMTP Pickup folder.
If useQueue Then
    mailer.SubmitToPickupFolder( _
        "C:\MailBeeNetQueue Files\Pickup", False)
End If

In the sample above, you can also add handling of MailBeeSmtpMessageNotAllowedException if it occurs. It's usually thrown when the SMTP server won't accept the message because it's too big. What to do in this case, it's up to you to decide:

  • If your MailBee.NET Queue is configured to use the same SMTP relay which is used by your main application, it does not make sense to retry the same message with MailBee.NET Queue.
  • If your application and MailBee.NET Queue use different relay servers, it may help to retry with the queue if the other server has softer limitations.
  • It may also help if you're using not MailBee.NET Queue but the native queue of your e-mail server (like IIS SMTP Pickup service) because in that case the SMTP protocol is not used at all and the limitation of the maximum message size accepted by the given server does not apply.

In most cases, however, you'll probably use a mail queue like MailBee.NET Queue on its own, without using hybrid schemes (send via SMTP relay and fall back to MailBee.NET Queue) in a single application. Using a mail queue of any kind is especially effective if you send lots of e-mails, including mail merge.

The example of using MailBee.NET Queue with mail merge can be found at Submit e-mails generated with mail merge to MailBee.NET Queue topic.

Throttle throughput (limit sending rate)

You can limit the maximum number of e-mails being sent per second, the maximum simultaneous number of connections and so on if the SMTP server you're dealing with implies certain restrictions on these parameters. For instance, many servers do not allow more than 5 simultaneous connections from a single IP address.

You can set the following parameters:

  • SmtpServer.MaxConnectionCount - the maximum number of simultaneous connections to this SMTP server in multi-threaded sending mode.
  • SmtpServer.MaxSendPerSessionCount - the maximum number of e-mail messages which can be sent within a single connection with the server.
  • SmtpServer.PauseInterval - the amount of time (in milliseconds) between disconnect and next connect with the server.

For instance, if SmtpServer.MaxConnectionCount is 1, no simultaneous connections with this server will be made, even if Smtp.MaxThreadCount is not 1.

Another example. If SmtpServer.MaxSendPerSessionCount is 5 and SmtpServer.PauseInterval is 1000, MailBee.NET will send no more than 5 e-mails per second, and each new session will be established after 1 second since completion of the previous session.

Note that if you're using multiple relay servers (your Smtp.SmtpServers collection contains several SmtpServer objects), you can set sending limits individually for each server.

The code snippet below show how to configure these parameters for a relay server. We assume your have two relay servers at your disposal: the first one is your corporate server which does not imply any restrictions while another one is not intended for bulk mailing (such as your ISP's server), and used only as a backup server in case of any issues with the primary server:

  • C#
  • VB
Smtp mailer = new Smtp();

// Primary corp relay with no restrictions. Send as fast as we can.
SmtpServer corpRelay = mailer.SmtpServers.Add(
    "smtp.company.com", "user", "password");

// Fail-over ISP's relay with some restrictions.
SmtpServer ispRelay = mailer.SmtpServers.Add(
    "mail.provider.com", "joe@company.com", "secret");

// Decrease the priority from zero (highest) to 1. The ISP's relay
// will be used only when the primary corporate relay is not accessible.
ispRelay.Priority = 1;

// Let's imagine the relay server of your company's ISP has these limitations:
// only a single connection per IP address allowed (no concurrent connections),
// only a single e-mail per an SMTP connection can be sent, and no more than 10
// e-mails can be sent per minute. We can fit into this limitation only when
// sending single e-mails not more often than every 6 seconds.
ispRelay.MaxConnectionCount = 1;
ispRelay.MaxSendPerSessionCount = 1;
ispRelay.PauseInterval = 6000;

Dim mailer As New Smtp()

' Primary corp relay with no restrictions. Send as fast as we can.
Dim corpRelay As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.company.com", "user", "password")

' Fail-over ISP's relay with some restrictions.
Dim ispRelay As SmtpServer = mailer.SmtpServers.Add( _
    "mail.provider.com", "joe@company.com", "secret")

' Decrease the priority from zero (highest) to 1. The ISP's relay
' will be used only when the primary corporate relay is not accessible.
ispRelay.Priority = 1

' Let's imagine the relay server of your company's ISP has these limitations:
' only a single connection per IP address allowed (no concurrent connections),
' only a single e-mail per an SMTP connection can be sent, and no more than 10
' e-mails can be sent per minute. We can fit into this limitation only when
' sending single e-mails not more often than every 6 seconds.
ispRelay.MaxConnectionCount = 1
ispRelay.MaxSendPerSessionCount = 1
ispRelay.PauseInterval = 6000

MailBee.NET Queue uses these parameters to implement throttling. You can examine its source code (it's included with the product) to learn how they are used in a real-world application. Try to experiment with different values of these parameters in MailBee.NET Queue to see how they influence the overall sending performance. This will help you find which parameters are acceptable by your server (if you don't know them in the first place). Since MailBee.NET Queue uses the same Smtp class like your own app, you can then use the parameter values you previously determined with MailBee.NET Queue, in your app.

Performance optimization

A few hints on how you can improve performance, send e-mails faster and consume less resources. We assume you have full control over the SMTP relay server as well:

  • Reduce the number of sessions. 100 e-mails within a single session will be sent several times faster than 100 e-mails and 1 e-mail per session. Of course, the server must be configured to allow this. Don't worry what happens if you submitted 90 e-mails and the connection has been lost while you're sending 91-th. You won't need to re-submit these 90 next time.
  • You can set the local end point (SmtpServer.LocalEndPoint property) if the sending machine has more than one network adapter. Refer to Set local end point in case of multiple network adapters topic to learn how.
  • Do not use SSL (especially if you're sending through the SMTP relay which resides on the same network). SSL usually makes sense only if the client and the server connect through a public network and the confidential information is being transmitted. For instance, if you send out a public newsletter (anyone can freely sign up to receive it), what's the point of encrypting its content during the delivery process?

If everything is set up right, you can easily send more than a hundred of e-mails per second with MailBee.NET and a powerful e-mail server like MS Exchange. This results in more than a million of small e-mails per 3 hours.

Send feedback to AfterLogic


SMTP over SSL (Gmail.com, Live.com, certificates)

  • Features supported
  • Auto-detect SSL settings based on the port and host
  • Connect to dedicated SSL port
  • Connect to regular port and use STARTTLS to activate SSL
  • Advanced STARTTLS
  • Configure SSL protocol (Auto, TLS 1.2)
  • Supply client certificate and check server certificate
  • Validate server certificate selectively
  • Validate server certificate without throwing exception

If you just need to send an e-mail through SSL, refer to Send if server requires SSL (like Gmail) topic. The current guide provides the detailed explanation of SSL and TLS related matters and security certificates.

Features supported

MailBee.NET fully supports all types of SSL connections with e-mail servers. This includes:

  • Dedicated SSL port connections (port 465 for secure SMTP).
  • SSL connections on the regular ports 25 and 587 via STARTTLS command.
  • Non-standard SSL ports.
  • Auto-detection of SSL settings for some popular providers (Gmail.com and Live.com).
  • Client and server certificates (this requires MailBee.NET Security license, it's also covered by MailBee.NET Objects unified license).
  • Support of TLS 1.0, TLS 1.1 and TLS 1.2 protocols. Automatic selection of the best supported protocol, and manual selection.

Nowadays, SSL is usually not just an advanced option for those users which demand better security, it's a must. MS Exchange 2010 by default won't authenticate clients unless the connection is protected with SSL encryption, not to mention such major e-mail services like Gmail.com and Live.com.

Due to the above, all individual MailBee.NET components like Smtp provide basic SSL/TLS capabilities at no additional cost. You'll need MailBee.NET Security license only for advanced use (validate server's certificate, supply client's certificate, S/MIME, and so on).

Auto-detect SSL settings based on the port and host

By default, MailBee.Global.AutodetectPortAndSslMode is true which means the following:

  • If the SMTP relay host name is smtp.gmail.com or smtp.live.com, MailBee.NET will autodetect the proper SSL port and mode unless you explicitly specified the SSL mode. This also concerns smtp-mail.outlook.com and some other well-known domains.
  • If you explicitly specified the port 465 but haven't changed the SSL mode from the default value SslStartupMode.Manual, MailBee.NET will use SslStartupMode.OnConnect. The SSL mode is denoted by SmtpServer.SslModeproperty of the SmtpServer object which represents your SMTP relay server settings.
  • If you explicitly specified the port 587 but haven't changed the SSL mode from the default value SslStartupMode.Manual, MailBee.NET will use SslStartupMode.UseStartTlsIfSupported.

Some servers do not support STARTTLS on port 587. SslStartupMode.UseStartTlsIfSupported mode does not cause any problems with because MailBee.NET won't issue STARTTLS command in such case.

However, some servers require you to use STARTTLS even on port 25, but MailBee.NET never tries this automatically (SMTP protocol lets the client know if the server "supports" STARTTLS but not if the server "requires" it). If you need STARTTLS on port 25, you should explicitly set SmtpServer.SslMode property value to SslStartupMode.UseStartTlsIfSupported or SslStartupMode.UseStartTls, depending on whether SSL connection is optional or a must for your client.

You can disable the auto-detection by setting MailBee.Global.AutodetectPortAndSslMode to false. This might be required only special cases such as when the server runs a regular SMTP service on a dedicated SSL port (however, this usually means the server is configured incorrectly and ports 25 and 465 are mixed up). Another case if when you need full manual control over SSL mode. See Advanced STARTTLS topic for details.

Note for VB users. Since Global is a keyword in VB, we can't just use Global.AutodetectPortAndSslMode even if MailBee namespace is imported. Full type name with the namespace part is required. This concerns all properties of Global class. In C#, you can use both MailBee.Global.AutodetectPortAndSslMode and Global.AutodetectPortAndSslMode.

Connect to dedicated SSL port

In the default state (MailBee.Global.AutodetectPortAndSslMode is true), you just need to set the port number since the dedicated SSL port is never 25. Usually, it's 465. To see how, refer to Send if server requires SSL (like Gmail)topic.

In the current topic, let's not rely on MailBee.Global.AutodetectPortAndSslMode property value. It doesn't matter if it's true or false, this code snippet will properly configure the dedicated SSL port connection anyway:

  • C#
  • VB
Smtp mailer = new Smtp();
SmtpServer relay = mailer.SmtpServers.Add("mail.here.com", "joe", "secret");
relay.Port = 465;
relay.SslMode = SslStartupMode.OnConnect;

Dim mailer As New Smtp()
Dim relay As SmtpServer = mailer.SmtpServers.Add("mail.here.com", "joe", "secret")
relay.Port = 465
relay.SslMode = SslStartupMode.OnConnect

Here and below, we assume MailBee, MailBee.SmtpMail and MailBee.Security namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

Connect to regular port and use STARTTLS to activate SSL

MailBee.NET does not automatically use STARTTLS on port 25 even if it's supported so let's demonstrate how to enable it explicitly. There are two methods of how you can issue STARTTLS command:

  • Simple method which always works: set SmtpServer.SslMode property value to SslStartupMode.UseStartTlsIfSupported or SslStartupMode.UseStartTls.
  • Advanced method for special cases: explicitly call Smtp.StartTls method after you called Smtp.Connect and Smtp.Hello. Works only when you establish the connection with the server manually. It won't work if you just called Smtp.Send because MailBee.NET will connect, say hello, send and disconnect within a single procedure so you just won't have the moment when you can call any method, including Smtp.StartTls).

Simple method is really simple, we just need to set a single property:

  • C#
  • VB
Smtp mailer = new Smtp();
SmtpServer relay = mailer.SmtpServers.Add("smtp.here.com", "joe", "secret");
relay.SslMode = SslStartupMode.UseStartTlsIfSupported;

Dim mailer As New Smtp()
Dim relay As SmtpServer = mailer.SmtpServers.Add("smtp.here.com", "joe", "secret")
relay.SslMode = SslStartupMode.UseStartTlsIfSupported

Advanced STARTTLS

Advanced method makes sense if you don't know at the moment of connecting to the server if you will use STARTTLS or not. Let's imagine you don't want to use SSL connection unless absolutely required by the server (in the end, SSL is resource consuming).

Most servers even if support STARTTLS, let you not use it if you don't want to. However, some servers even do not allow you to authenticate until the connection is secured. They do this by advertising STARTTLS and not advertising any authentication methods in clear-text mode. You can use this as an indirect sign that the server wants STARTTLS, and issue it then:

  • C#
  • VB
// Disable SSL auto-detection as we need full manual control.
MailBee.Global.AutodetectPortAndSslMode = false;

Smtp mailer = new Smtp();

// You can view the log on what exactly your server advertizes
// in the supported capabilities before and after STARTTLS.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

// Add SMTP relay, use authentication but nothing special to SSL
// at this point. If your regular port is 587 rather than 25,
// you should add "relay.Port = 465" statement.
SmtpServer relay = mailer.SmtpServers.Add(
    "smtp.provider.com", "john.doe@company.com", "secret");

// Connect and say hello, will get the list of capabilities then.
mailer.Connect();
mailer.Hello();

// If STARTTLS is supported but no authentication methods are available,
// assume they will hopefully become available after STARTTLS.
if (mailer.GetExtension("starttls") != null &&
    mailer.GetSupportedAuthMethods() == AuthenticationMethods.None)
{
    mailer.StartTls();

    // Request which the capabilities are available under SSL layer.
    mailer.Hello();
}

if (mailer.GetSupportedAuthMethods() == AuthenticationMethods.None)
{
    // This is a rare case: the server does support STARTTLS and does not
    // advertize any authentication methods, but it does not hide its
    // supported authentication methods for a purpose (to urge us to use
    // STARTTLS). The server simply does not support authentication and
    // this has nothing to do with STARTTLS.
    Console.WriteLine("This server does not support authentication");
    mailer.Disconnect();
}
else
{
    // If we're here, authentication is available. Let's check
    // if it required to issue STARTTLS to make it available.
    if (mailer.IsSslConnection)
    {
        Console.WriteLine(
            "This server supports authentication in SSL mode only");
    }
    else
    {
        Console.WriteLine(
            "This server supports authentication in clear-text mode");
    }

    // Login should be possible now.
    mailer.Login();

    // Send an e-mail.
    mailer.From.Email = "john.doe@company.com";
    mailer.To.Add("jane@domain.com");
    mailer.Subject = "Test message";
    mailer.Send();

    // As we connected manually, we need to call disconnect.
    mailer.Disconnect();
}

' Disable SSL auto-detection as we need full manual control.
MailBee.Global.AutodetectPortAndSslMode = False

Dim mailer As New Smtp()

' You can view the log on what exactly your server advertizes
' in the supported capabilities before and after STARTTLS.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Add SMTP relay, use authentication but nothing special to SSL
' at this point. If your regular port is 587 rather than 25,
' you should add "relay.Port = 465" statement.
Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.provider.com", "john.doe@company.com", "secret")

' Connect and say hello, will get the list of capabilities then.
mailer.Connect()
mailer.Hello()

' If STARTTLS is supported but no authentication methods are available,
' assume they will hopefully become available after STARTTLS.
If Not (mailer.GetExtension("starttls") Is Nothing) And _
        mailer.GetSupportedAuthMethods() = AuthenticationMethods.None Then
    mailer.StartTls()

    ' Request which the capabilities are available under SSL layer.
    mailer.Hello()
End If

If mailer.GetSupportedAuthMethods() = AuthenticationMethods.None Then
    ' This is a rare case: the server does support STARTTLS and does not
    ' advertize any authentication methods, but it does not hide its
    ' supported authentication methods for a purpose (to urge us to use
    ' STARTTLS). The server simply does not support authentication and
    ' this has nothing to do with STARTTLS.
    Console.WriteLine("This server does not support authentication")
    mailer.Disconnect()
Else
    ' If we're here, authentication is available. Let's check
    ' if it required to issue STARTTLS to make it available.
    If mailer.IsSslConnection Then
        Console.WriteLine( _
            "This server supports authentication in SSL mode only")
    Else
        Console.WriteLine( _
            "This server supports authentication in clear-text mode")
    End If

    ' Login should be possible now.
    mailer.Login()

    ' Send an e-mail.
    mailer.From.Email = "john.doe@company.com"
    mailer.To.Add("jane@domain.com")
    mailer.Subject = "Test message"
    mailer.Send()

    ' As we connected manually, we need to call disconnect.
    mailer.Disconnect()
End If

Configure SSL protocol (Auto, TLS 1.2)

By default, MailBee.NET automatically uses the best available security protocol for SSL layer (in most cases, TLS 1.2). However, some servers do support TLS but do not let the client automatically select it as the best supported protocol. In such case, you'll need to specify the protocol manually. In extremely rare cases, the server may support TLS 1.0 only (inspite of they are considered weak). Or, you can force TLS 1.2 and never permit protocol degradation. That's how you can select it:

  • C#
  • VB
Smtp mailer = new Smtp();
SmtpServer relay = mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret");
relay.Port = 465;
relay.SslMode = SslStartupMode.OnConnect;

// Always require TLS 1.2 protocol.
relay.SslProtocol = SecurityProtocol.Tls12;

Dim mailer As New Smtp()
Dim relay As SmtpServer = mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret")
relay.Port = 465
relay.SslMode = SslStartupMode.OnConnect

' Always require TLS 1.2 protocol.
relay.SslProtocol = SecurityProtocol.Tls12

Supply client certificate and check server certificate

All previous topics in this guide assumed the situation when you just need to use SSL because it's required by the server. They didn't put the focus on security. On other hand, this topic highlights security-related matters.

In MailBee.NET licensing model, the advanced security features which fall outside the scope of sending e-mail (like validation of server certificates) require MailBee.NET Security license. This license covers all secure e-mail functions which deal with certificates, including SSL certificates (explained here) and S/MIME (refer to Sign and encrypt e-mail with S/MIME guide to learn more).

We assume that MailBee, MailBee.SmtpMail and MailBee.Security namespaces are already imported. Also, to unlock the certificates functionality, MailBee.Global.LicenseKey must include Security license in addition to SMTP license. MailBee.NET trial keys and MailBee.NET Objects unified keys include all the required licenses.

The sample below demonstrates the use of the client's private certificate to prove its identity to the server, and the validation of the server's public certificate by the client:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication and STARTTLS over port 25.
SmtpServer relay = mailer.SmtpServers.Add(
    "mail.company.com", "j.doe@company.com", "secret");
relay.SslMode = SslStartupMode.UseStartTls;

// Supply the client's certificate (taken from a file).
relay.SslCertificates.Client =
    new Certificate("C:\\Docs\\john.pfx", CertFileType.Pfx, "password");

// Will cause MailBee.NET to throw an exception if anything is wrong
// with the server's certificate.
relay.SslCertificates.AutoValidation = CertificateValidationFlags.All;

// You can view the log on what happens during SSL negotiation.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Send an e-mail.
mailer.From.Email = "j.doe@company.com";
mailer.To.Add("jane@domain.com");
mailer.Subject = "Test message";

// Try to send e-mail and validate the server's certificate
// during SSL negotiation procedure. If the certificate is
// incorrect, report all the problems we have found.
try
{
    mailer.Send();
}
catch (MailBeeCertificateValidationException e)
{
    // Server certificate is not valid.
    Console.WriteLine(e.Message);

    // Build a string which lists the names of all the flags
    // the certificate validation process has failed for.
    string reasons = string.Empty;
    CertificateValidationFlags flags = e.Status;
    int mask = 1;
    while (flags > 0)
    {
        CertificateValidationFlags flag =
            flags & (CertificateValidationFlags)mask;
        if (flag != CertificateValidationFlags.None)
        {
            if (reasons.Length > 0)
            {
                reasons += ", ";
            }
            reasons += flag.ToString();
            flags &= (CertificateValidationFlags)~mask;
        }
        mask <<= 1;
    }

    Console.WriteLine("Reasons: " + reasons);
}

Dim mailer As New Smtp()

' Use SMTP relay server with authentication and STARTTLS over port 25.
Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "mail.company.com", "j.doe@company.com", "secret")
relay.SslMode = SslStartupMode.UseStartTls

' Supply the client's certificate (taken from a file).
relay.SslCertificates.Client = _
    New Certificate("C:\Docs\john.pfx", CertFileType.Pfx, "password")

' Will cause MailBee.NET to throw an exception if anything is wrong
' with the server's certificate.
relay.SslCertificates.AutoValidation = CertificateValidationFlags.All

' You can view the log on what happens during SSL negotiation.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Send an e-mail.
mailer.From.Email = "j.doe@company.com"
mailer.To.Add("jane@domain.com")
mailer.Subject = "Test message"

' Try to send e-mail and validate the server's certificate
' during SSL negotiation procedure. If the certificate is
' incorrect, report all the problems we have found.
Try
   mailer.Send()
Catch e As MailBeeCertificateValidationException
   ' Server certificate is not valid.
   Console.WriteLine(e.Message)

   ' Build a string which lists the names of all the flags
   ' the certificate validation process has failed for.
   Dim reasons As String = String.Empty
   Dim flags As CertificateValidationFlags = e.Status
   Dim mask As Integer = 1
   While flags > 0
      Dim flag As CertificateValidationFlags = flags And _
            CType(mask, CertificateValidationFlags)
      If flag <> CertificateValidationFlags.None Then
         If reasons.Length > 0 Then
            reasons &= ", "
         End If
         reasons &= flag.ToString()
         flags = flags And CType(Not mask, CertificateValidationFlags)
      End If
      mask <<= 1
   End While

   Console.WriteLine("Reasons: " & reasons)
End Try

In this sample, the client's private certificate is taken from a file. To learn how to take it from the system store (Windows Registry), refer to ClientServerCertificates class documentation.

You can also use "supply client certificate" and "check server certificate" parts of this sample independently. For instance, a client can validate server certificates but never provide its own. This approach is used in the next sample.

Validate server certificate selectively

In the previous topic, MailBee.NET threw an exception on any certificate validation errors. In case if you want to ignore some errors, you can adjust this line:

  • C#
  • VB
relay.SslCertificates.AutoValidation = CertificateValidationFlags.All;

relay.SslCertificates.AutoValidation = CertificateValidationFlags.All

and replace it with somewhat like:

  • C#
  • VB
relay.SslCertificates.AutoValidation = (CertificateValidationFlags)
    (CertificateValidationFlags.All - CertificateValidationFlags.IsUntrustedRoot);

relay.SslCertificates.AutoValidation = CType( _
    CertificateValidationFlags.All - CertificateValidationFlags.IsUntrustedRoot, _
    CertificateValidationFlags)

The above will ignore "certificate is self-signed" errors (CertificateValidationFlags.IsUntrustedRoot flag will not be checked). All other certificate errors will still cause MailBee.NET to throw an exception.

Validate server certificate without throwing exception

You may want to validate the server's certificate without getting validation exceptions. For instance, you neither want to close the connection in case of a validation error nor want to ignore such errors. The most typical case is to show the discovered errors to the user so that it would he the user who decides whether to proceed.

In the previous sample, although you could narrow the list of certificate errors to be detected, you couldn't proceed if the error which is on that list has still been found in the certificate. It would be nice if you could examine which errors have been detected, ask the user, and continue the SMTP session without reconnection if the user decided to ignore these errors.

The sample below validates the server certificate in the "no-exceptions" way. The sample cancels the SMTP session in case if the server's certificate contains any critical errors but tolerates "certificate is self-signed" error. However, unlike the previous sample where this error was simply ignored, this sample warns the user if it has happened:

  • C#
  • VB
// Full manual control needed since we use Smtp.StartTls method.
MailBee.Global.AutodetectPortAndSslMode = false;

Smtp mailer = new Smtp();

// Log file is helpful for trouble-shooting.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Use SMTP relay server with authentication.
SmtpServer relay = mailer.SmtpServers.Add(
    "smtp.company.com", "j.doe@company.com", "secret");

// Send an e-mail.
mailer.From.Email = "j.doe@company.com";
mailer.To.Add("jane@domain.com");
mailer.Subject = "Test message";

mailer.Connect();
mailer.Hello();
mailer.StartTls();

// Validate the server's certificate. This does not throw validation
// exception though, just returns the status.
CertificateValidationFlags flags =
    relay.SslCertificates.Server.Validate();

if ((flags & ~CertificateValidationFlags.IsUntrustedRoot) > 0)
{
    // Build a string which lists the names of all the flags
    // the certificate validation process has failed for.
    string reasons = string.Empty;
    int mask = 1;
    while (flags > 0)
    {
        CertificateValidationFlags flag =
            flags & (CertificateValidationFlags)mask;
        if (flag != CertificateValidationFlags.None)
        {
            if (reasons.Length > 0)
            {
                reasons += ", ";
            }
            reasons += flag.ToString();
            flags &= (CertificateValidationFlags)~mask;
        }
        mask <<= 1;
    }

    // We don't want to proceed then. Just report the problems
    // to the user and disconnect then.
    Console.WriteLine("Server's certificate problems: " + reasons);
}
else
{
    // Warn the user about self-signed certificate but proceed.
    if ((flags & CertificateValidationFlags.IsUntrustedRoot) > 0)
    {
        Console.WriteLine(
            "Server's certificate is self-signed but the rest is OK");
    }
    else
    {
        Console.WriteLine(
            "Server's certificate is perfectly OK");
    }

    // After STARTTLS, must send hello again. Not required for dedicated
    // SSL port connections.
    mailer.Hello();

    // Authenticate through the secure and trusted channel. Note that you
    // usually need to provide the client's credentials and authenticate
    // only in case if you do not supply the client's certificate.
    mailer.Login();

    // Send through the secure and trusted channel.
    mailer.Send();
}

// As we connected manually, we need to call disconnect.
mailer.Disconnect();

' Full manual control needed since we use Smtp.StartTls method.
MailBee.Global.AutodetectPortAndSslMode = False

Dim mailer As New Smtp()

' Log file is helpful for trouble-shooting.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay server with authentication.
Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.company.com", "j.doe@company.com", "secret")

' Send an e-mail.
mailer.From.Email = "j.doe@company.com"
mailer.To.Add("jane@domain.com")
mailer.Subject = "Test message"

mailer.Connect()
mailer.Hello()
mailer.StartTls()

' Validate the server's certificate. This does not throw validation
' exception though, just returns the status.
Dim flags As CertificateValidationFlags = _
    relay.SslCertificates.Server.Validate()

If (flags And Not CertificateValidationFlags.IsUntrustedRoot) > 0 Then
    ' Build a string which lists the names of all the flags
    ' the certificate validation process has failed for.
    Dim reasons As String = String.Empty
    Dim mask As Integer = 1
    While flags > 0
        Dim flag As CertificateValidationFlags = flags And _
            CType(mask, CertificateValidationFlags)
        If flag <> CertificateValidationFlags.None Then
            If reasons.Length > 0 Then
                reasons &= ", "
            End If
            reasons &= flag.ToString()
            flags = flags And CType(Not mask, CertificateValidationFlags)
        End If
        mask <<= 1
    End While

    ' We don't want to proceed then. Just report the problems
    ' to the user and disconnect then.
    Console.WriteLine("Server's certificate problems: " & reasons)
Else
    ' Warn the user about self-signed certificate but proceed.
    If (flags And CertificateValidationFlags.IsUntrustedRoot) > 0 Then
        Console.WriteLine( _
            "Server's certificate is self-signed but the rest is OK")
    Else
        Console.WriteLine("Server's certificate is perfectly OK")
    End If

    ' After STARTTLS, must send hello again. Not required for dedicated
    ' SSL port connections.
    mailer.Hello()

    ' Authenticate through the secure and trusted channel. Note that you
    ' usually need to provide the client's credentials and authenticate
    ' only in case if you do not supply the client's certificate.
    mailer.Login()

    ' Send through the secure and trusted channel.
    mailer.Send()
End If

' As we connected manually, we need to call disconnect.
mailer.Disconnect()

With the approach above, you can implement really flexible processing and validation of server certificates.

Send feedback to AfterLogic


SMTP authentication in detail

  • SMTP authentication explained
  • POP-before-SMTP or ESMTP?
  • Authenticate with POP-before-SMTP
  • ESMTP authentication in more detail
  • Secure authentication
  • Use Integrated Windows Authentication (no username and password required)
  • Use OAuth 2.0 with Gmail, Outlook.com, Live.com or Hotmail.com
  • Fine-tune SMTP authentication process
  • Create your own authentication method

SMTP authentication explained

SMTP authentication allows the client to show the server that this client has permission to relay e-mail through this server.

In most cases, you can send without authentication to local e-mail addresses of this domain (i.e. send from bob@domain.com to alice@domain.com) because the server does not need to relay your e-mail to external servers. Authentication is required whenever the recipient is not of a local domain (i.e. send from joe@company.com to tom@example.com, provided that company.com and example.com use different e-mail servers).

Every rule has its exceptions. Some servers require the client to authenticate itself even when sending to a local domain. But more popular case is opposite - some servers do not support authentication but allow the client to send with no limitations (so called open relays). To avoid exploiting such server by spammers, it usually restricts the IP address list of allowed sender. Typical case if when your application resides on such server and the server allows unauthenticated servers to relay e-mail only if they connect from the server computer itself.

When authentication is enabled, you usually need to supply your login name and password on this server (although variants with other parameters exist as well, such as OAuth tokens). The login name is the most tricky part: it can be your account name, account@domain, domain\account, domain\account\alias (in MS Exchange), and so on. For instance, if you're using account name in Outlook (which uses MAPI instead of SMTP), the SMTP name for the same could be domain\account.

There are two types of SMTP authentication, both supported by MailBee.NET:

  • POP-before-SMTP authentication, now deprecated but still supported or even required by some very old servers.
  • ESMTP authentication via so-called SASL mechanism. All newer servers use this type.

POP-before-SMTP or ESMTP?

The only reason to use POP-before-SMTP authentication is the lack of support of ESMTP authentication by the server. However, if the server does not advertize ESMTP authentication support in response to EHLO command, it does not yet mean you have to use POP-before-SMTP.

Typical reasons why a newer server (which can support ESMTP authentication) might not advertize this capability to a client:

  • STARTTLS first. The server wants the authentication process to take place under the SSL layer. MS Exchange 2010 is an example.
  • The server may be configured to act as an open relay for the given IP address of the client. Typical case with intranet networks.
  • The server does not relay e-mail to external domains at all but only accepts e-mail from other hosts. SMTP services of large e-mail providers often have different SMTP relay servers for outgoing e-mail and SMTP MX servers for incoming e-mail.

If any of the above is the case, it does not make sense to use POP-before-SMTP as it won't work anyway.

Authenticate with POP-before-SMTP

Generally speaking, POP-before-SMTP authentication is just an awkward way to overcome the limitation of the original SMTP protocol which did not support any authentication mechanism (ESMTP authentication has been invented years later). The idea is to connect to the POP3 service of the same e-mail server, authenticate there, and then immediately connect via SMTP to the same server. The server will remember your IP address for a few moments, and the SMTP part of the server will know that you recently passed POP3 authentication on this server.

Of course, this is not very secure (many different clients can have the same IP address due to NATs and proxies), and requires the server run both POP3 and SMTP services on the same system.

Anyway, if you have to use POP-before-SMTP, that's how you can do it:

  • C#
  • VB
Smtp mailer = new Smtp();

// See in the log file what exactly happens during POP-before-SMTP.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Add SMTP relay, no ESMTP authentication.
mailer.SmtpServers.Add("smtp.domain.com");

// Authenticate with POP-before-SMTP.
mailer.AuthPopBeforeSmtp("pop.domain.com", 110, "jdoe", "secret");

// Compose and send an e-mail.
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("jane@example.com");
mailer.Subject = "Test message";
mailer.Send();

Dim mailer As New Smtp()

' See in the log file what exactly happens during POP-before-SMTP.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Add SMTP relay, no ESMTP authentication.
mailer.SmtpServers.Add("smtp.domain.com")

' Authenticate with POP-before-SMTP.
mailer.AuthPopBeforeSmtp("pop.domain.com", 110, "jdoe", "secret")

' Compose and send an e-mail.
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("jane@example.com")
mailer.Subject = "Test message"
mailer.Send()

Here and below, we assume MailBee and MailBee.SmtpMail namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

ESMTP authentication in more detail

ESMTP authentication itself is not a particular method or algorithm. It's rather a protocol (SASL over SMTP). There are lots of particular authentication method implementations, and the most popular are: LOGIN, PLAIN, CRAM-MD5, DIGEST-MD5, NTLM, GSSAPI, XOAUTH, XOAUTH2. MailBee.NET supports them all and also provides the mechanism to implement your own methods.

The server lists the supported authentication methods in AUTH lines of the reply to EHLO command. All authentication data is base64-encoded to avoid issues with special symbols which may appear in username and password strings.

All methods except of LOGIN and PLAIN are secure and use hash-based algorithms. If LOGIN or PLAIN is being used, SSL connection is recommended if security considerations apply for your case (and many servers simply do not allow you to use these methods unless the connection is SSL-encrypted).

NTLM and GSSAPI methods are widely used by Microsoft products like MS Exchange or IIS SMTP Service.

SPA (Secure Password Authentication) is another name for NTLM.

NTLM and GSSAPI are often used in so-called Integrated Windows Authentication mode when the sender automatically uses the login and password of the Windows user under whose context the application runs. The application does not need to know the password of the user in order to operate their e-mail account. See Use Integrated Windows Authentication (no username and password required) topic for details.

Integrated Windows Authentication, however, won't work with a web application unless it's executed under the context of an interactive user. Most web apps are executed under a system user's account, not an interactive user's account.

The e-mail account password is also not required by the application in case of XOAUTH or XOAUTH2 method. It implements OAuth technology which lets applications access restricted resources via authorization instead of authentication. See Use OAuth 2.0 with Gmail, Outlook.com, Live.com or Hotmail.com topic for details.

MailBee.NET can automatically select the best (the most secure) authentication method supported by the given server, and this is the default behaviour. However, some servers do not properly support secure authentication methods, and it may be required to fallback to simpler methods. By default, MailBee.NET then tries an insecure method if the secure method fails. If you can't afford using insecure methods for security reasons, you can set AuthenticationOptions.DisableSimpleMethodAfterSecure flag.

More specifically, the server may require you to pass different login name for different authentication methods. For instance, a simpler method may accept just an account name while a secure method may also require you to supply your domain name, workstation name, etc. See Fine-tune SMTP authentication process topic for more details on how to apply various AuthenticationOptions flags.

Secure authentication

By default, if the server supports secure authentication, MailBee.NET will use it automatically. No further action is required on your part.

However, if the server does not support any secure methods, MailBee.NET by default downgrades to insecure methods if supported by the server. If you cannot allow this for security reasons, you can explicitly specify which authentication methods to use. The sample below will connect to the e-mail server only if it supports secure authentication:

  • C#
  • VB
Smtp mailer = new Smtp();

// See in the log file what exactly happens during authentication.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Use SMTP relay with authentication (username in MS Exchange style).
SmtpServer relay = mailer.SmtpServers.Add(
    "smtp.here.com", "jdoe\\here.com", "secret");

// Allow secure authentication methods only.
relay.AuthMethods = AuthenticationMethods.SaslCramMD5 |
    AuthenticationMethods.SaslDigestMD5 |
    AuthenticationMethods.SaslGssApi |
    AuthenticationMethods.SaslNtlm;

// Compose and send an e-mail.
mailer.From.Email = "jdoe@here.com";
mailer.To.Add("jane@example.com");
mailer.Subject = "Test message";
mailer.Send();

Dim mailer As New Smtp()

' See in the log file what exactly happens during authentication.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay with authentication (username in MS Exchange style).
Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.here.com", "jdoe\here.com", "secret")

' Allow secure authentication methods only.
relay.AuthMethods = AuthenticationMethods.SaslCramMD5 Or _
    AuthenticationMethods.SaslDigestMD5 Or _
    AuthenticationMethods.SaslGssApi Or _
    AuthenticationMethods.SaslNtlm

' Compose and send an e-mail.
mailer.From.Email = "jdoe@here.com"
mailer.To.Add("jane@example.com")
mailer.Subject = "Test message"
mailer.Send()

If the server does not support any secure methods, MailBee.NET will throw MailBeeLoginNoSupportedMethodsException.

Note that we haven't included OAuth in the list of the allowed secure methods. OAuth, being the method of an authorization rather than authentication, is always used on its own because its parameters are not compatible with "real" authentication methods. MailBee.NET won't use OAuth unless it's the only method in the list of the allowed methods.

Use Integrated Windows Authentication (no username and password required)

NTLM and GSSAPI authentication methods can work in two modes:

  • The user specifies their credentials explicitly (like other authentication methods work), and MailBee.NET creates the authentication token from them.
  • Integrated Windows Authentication (IWA). The authentication token is created by Windows from the credentials of the currently logged Windows user. The application never deals with the account password. IWA mode provides increased security and spares the end user from entering their credentials.

IWA, however, cannot be used when the currently logged Windows user is not an interactive user. In web applications, you often deal with system users (like NETWORK SERVICE, ASPNET, etc). To be able to use IWA with MailBee.NET in an ASP.NET application, the application itself must run under the context of an interactive user (<authentication mode="Windows"/> in web.config).

Also, the user from whose context the authentication token is constructed, must have a valid mailbox on the e-mail server. This is an important note: even if the given user is registered in the Active Directory and can log in the domain, this does not necessarily mean that the system has already provisioned their mailbox.

Let's assume that the current user context denotes a user which has a mailbox on the e-mail server integrated with your Active Directory. The sample below authenticates using IWA and sends an e-mail:

  • C#
  • VB
Smtp mailer = new Smtp();

// See in the log file what exactly happens during authentication.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Use SMTP relay with authentication (take credentials from Windows).
SmtpServer relay = mailer.SmtpServers.Add(
    "mail.domain.com", null, null);

// Allow methods which can do Integrated Windows Authentication.
relay.AuthMethods = AuthenticationMethods.SaslNtlm |
    AuthenticationMethods.SaslGssApi;

// Compose and send an e-mail.
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("jane@example.com");
mailer.Subject = "Test message";
mailer.Send();

Dim mailer As New Smtp()

' See in the log file what exactly happens during authentication.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Use SMTP relay with authentication (take credentials from Windows).
Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "mail.domain.com", CType(Nothing, String), CType(Nothing, String))

' Allow methods which can do Integrated Windows Authentication.
relay.AuthMethods = AuthenticationMethods.SaslNtlm Or _
    AuthenticationMethods.SaslGssApi

' Compose and send an e-mail.
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("jane@example.com")
mailer.Subject = "Test message"
mailer.Send()

Use OAuth 2.0 with Gmail, Outlook.com, Live.com or Hotmail.com

OAuth addresses the common problem when the user does not want to give their password away to the external system which needs access to their data.

MailBee.NET provides the detailed tutorial and samples covering many aspects of OAuth 2.0 usage with Google and Microsoft providers. You can find it at OAuth 2.0 in Windows, .NET Core, and ASP.NET MVC apps page.

Fine-tune SMTP authentication process

MailBee.NET supports lots of parameters and options that affect the authentication process. The most important are:

  • AuthenticationOptions.PreferSimpleMethods - try insecure methods first instead of secure methods. Fixes problems with servers which declare support of secure methods but implement them incorrectly. By default, MailBee.NET then tries an insecure method but this may not work if the server aborts the connection instead of returning a negative reply in case of authentication error. This flag allows even not to try secure methods if less secure are available.
  • AuthenticationOptions.DisableSimpleMethodAfterSecure - set it if you don't want MailBee.NET to fall-back to an insecure method if the secure method failed.
  • SmtpServer.AccountDomain and SmtpServer.TargetName - used with NTLM and GSSAPI. You may need to set SmtpServer.AccountDomain and, sometimes, SmtpServer.TargetName when using MS Exchange (especially newer versions).
  • SmtpServer.IgnoreLoginFailure - try to send even if ESMTP or POP-before-SMTP authentication failed. There is still a chance the server will accept the message (for instance, if it's addressed to local recipients only) so that this setting makes some sense.

The code snippet below makes MailBee.NET to use an insecure method even if a secure method seems to be supported. MailBee.NET will still use a secure method when no insecure methods are supported by the server:

  • C#
  • VB
SmtpServer relay = mailer.SmtpServers.Add(
    "smtp.here.com", "joe", "secret");

relay.AuthOptions = AuthenticationOptions.PreferSimpleMethods;

Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.here.com", "joe", "secret")

relay.AuthOptions = AuthenticationOptions.PreferSimpleMethods

We assume mailer is an Smtp instance.

The next code snippet configures MailBee.NET to use GSSAPI/Kerberos authentication when using SMTP Service of Microsoft IIS 7 or higher:

  • C#
  • VB
SmtpServer relay = mailer.SmtpServers.Add(
    "mail.company.com", "joe", "secret");

relay.AccountDomain = "company.com";
relay.TargetName = "SmtpSvc/mail.company.com";
relay.AuthMethods = AuthenticationMethods.SaslGssApi;

Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "mail.company.com", "joe", "secret")

relay.AccountDomain = "company.com"
relay.TargetName = "SmtpSvc/mail.company.com"
relay.AuthMethods = AuthenticationMethods.SaslGssApi

You can explore AuthenticationOptions enumeration to learn which other options are available.

Create your own authentication method

To learn how create your own SASL method, refer to SaslMethod class documentation. It demonstrates creating a SASL method which is then used with Pop3 class but SASL methods are protocol-independent, so that you can use the same class you developed, with all protocols including SMTP.

The code snippet below indicates how to configure SmtpServer object so that MailBee.NET could use your custom method during the authentication process:

  • C#
  • VB
SmtpServer relay = mailer.SmtpServers.Add(
    "mail.company.com", "joe@domain.com", "secret");

relay.AuthMethods = AuthenticationMethods.SaslUserDefined;
relay.AuthUserDefined = new SaslLoginMethod();

Dim relay As SmtpServer = mailer.SmtpServers.Add( _
    "mail.company.com", "joe@domain.com", "secret")

relay.AuthMethods = AuthenticationMethods.SaslUserDefined
relay.AuthUserDefined = New SaslLoginMethod()

We assume mailer is an Smtp instance and SaslLoginMethod represents your custom authentication method as defined in SaslMethod class documentation.

You can also use your custom method together with the standard methods. For instance, you can leave relay.AuthMethods in its default AuthenticationMethods.Auto state. MailBee.NET will treat your custom method accordingly the same rules applied to other methods (i.e. try it first if it's secure, do not try if the server does not advertize this method as supported, etc).

Send feedback to AfterLogic


Advanced SMTP connections (proxy, extensions, custom hello, commands and ports)

  • Connect via proxy server (SOCKS4, SOCKS5, HTTP)
  • Connect to non-standard SMTP port
  • Set local end point in case of multiple network adapters or firewall
  • Send custom Hello message to server
  • Examine supported ESMTP extensions
  • Disable conflicting ESMTP extensions
  • Send custom command to server

MailBee.NET supports a number of advanced methods and options which allow you to tune your SMTP connections in different ways, send non-standard SMTP commands, enable or disable various ESMTP extensions, and so on.

This guide also demonstrates how you can examine the server's response and status codes, use ESMTP extensions which are not natively supported by MailBee.NET (such as ENHANCEDSTATUSCODES), etc.

Connect via proxy server (SOCKS4, SOCKS5, HTTP)

If you're behind a firewall and the network is configured to make it possible to use SMTP only through a proxy server, you can do it as follows:

  • C#
  • VB
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Proxy;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // See in the log file what happens when proxy is on.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = "C:\\Temp\\log.txt";
        mailer.Log.Clear();

        // Use SMTP relay with ESMTP authentication.
        SmtpServer server = mailer.SmtpServers.Add(
            "mail.domain.com", "jdoe", "secret");

        // We want to connect via this proxy server.
        server.Proxy.Name = "proxy.server.com";

        // SOCKS5 proxy.
        server.Proxy.Protocol = ProxyProtocol.Socks5;

        // Or, SOCKS4 proxy.
        // server.Proxy.Protocol = ProxyProtocol.Socks4;

        // Or, HTTP proxy.
        // server.Proxy.Protocol = ProxyProtocol.Http;
        // server.Proxy.Port = 808;

        // Authentication is used with SOCKS5 and HTTP.
        // Not required with SOCKS4.
        server.Proxy.AccountName = "proxy.user";
        server.Proxy.Password = "proxy.password";

        // Compose and send simple e-mail though the proxy.
        mailer.From.Email = "jdoe@domain.com";
        mailer.To.Add("jane@example.com");
        mailer.Subject = "Test message";
        mailer.Send();
    }
}

Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Proxy

Module Module1
    Sub Main()
        Dim mailer As New Smtp()

        ' See in the log file what happens when proxy is on.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Clear()

        ' Use SMTP relay with ESMTP authentication.
        Dim server As SmtpServer = mailer.SmtpServers.Add( _
            "mail.domain.com", "jdoe", "secret")

        ' We want to connect via this proxy server.
        server.Proxy.Name = "proxy.server.com"

        ' SOCKS5 proxy.
        server.Proxy.Protocol = ProxyProtocol.Socks5

        ' Or, SOCKS4 proxy.
        ' server.Proxy.Protocol = ProxyProtocol.Socks4

        ' Or, HTTP proxy.
        ' server.Proxy.Protocol = ProxyProtocol.Http
        ' server.Proxy.Port = 808

        ' Authentication is used with SOCKS5 and HTTP.
        ' Not required with SOCKS4.
        server.Proxy.AccountName = "proxy.user"
        server.Proxy.Password = "proxy.password"

        ' Compose and send simple e-mail though the proxy.
        mailer.From.Email = "jdoe@domain.com"
        mailer.To.Add("jane@example.com")
        mailer.Subject = "Test message"
        mailer.Send()
    End Sub
End Module

Here and below, we assume that MailBee.NET SMTP license key is already set in app.config, web.config, or Windows Registry. See Import namespaces and set license key topic for details.

If you haven't specified the port, 1080 will be used (the default for SOCKS4 and SOCKS5). HTTP proxies usually operate at port 808 so you'll need to specify the port manually in that case.

Connect to non-standard SMTP port

You'll typically need to change the port in case if you want to send to connect to a dedicated SSL port (usually, 465) or alternate non-SSL port (usually, 587).

If you want to use SSL, refer to Send if server requires SSL (like Gmail) topic. Alternate non-SSL port 587 is supported by some e-mail providers to let you send e-mails through in case if port 25 is blocked by your ISP.

This code snippet sends a simple e-mail through a non-SSL port 587:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with authentication.
SmtpServer server = mailer.SmtpServers.Add(
    "mail.provider.com", "jdoe@here.com", "secret");

// Use alternate SMTP port.
server.Port = 587;

mailer.SmtpServers.Add(server);

// Compose and send simple e-mail.
mailer.From.Email = "jdoe@here.com";
mailer.To.Add("jane@example.com");
mailer.Subject = "Test message";
mailer.Send();

Dim mailer As New Smtp()

' Use SMTP relay with authentication.
Dim server As SmtpServer = mailer.SmtpServers.Add( _
    "mail.provider.com", "jdoe@here.com", "secret")

' Use alternate SMTP port.
server.Port = 587

' Compose and send simple e-mail.
mailer.From.Email = "jdoe@here.com"
mailer.To.Add("jane@example.com")
mailer.Subject = "Test message"
mailer.Send()

Here and below, we assume MailBee.SmtpMail namespace is already imported in your code.

Set local end point in case of multiple network adapters or firewall

If the machine you're sending from is equipped with multiple networks adapters (each with its own IP address assigned), you may let MailBee.NET know which adapter to use. This may improve the overall performance is the appropriate adapter is used.

Another case is when you want to send from a particular local port (for instance, if your firewall requires this).

To set a local end point, assign SmtpServer.LocalEndPoint property. In case if you are doing "direct send" rather than "send through a relay server", use DirectSendServerConfig.LocalEndPoint property.

The sample below assigns a local end point and sends an e-mail to the SMTP relay server:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay with ESMTP authentication.
SmtpServer server = mailer.SmtpServers.Add(
    "smtp.company.com", "jdoe@company.com", "secret");

// Send from the adapter which has 192.168.1.2 address,
// and use 20051 as the local port.
server.LocalEndPoint = new System.Net.IPEndPoint(
    System.Net.IPAddress.Parse("192.168.1.2"), 20051);

// Compose and send simple e-mail.
mailer.From.Email = "jdoe@company.com";
mailer.To.Add("jane@example.com");
mailer.Subject = "Test message";
mailer.Send();

Dim mailer As New Smtp()

' Use SMTP relay with ESMTP authentication.
Dim server As SmtpServer = mailer.SmtpServers.Add( _
    "smtp.company.com", "jdoe@company.com", "secret")

' Send from the adapter which has 192.168.1.2 address,
' and use 20051 as the local port.
server.LocalEndPoint = New System.Net.IPEndPoint( _
    System.Net.IPAddress.Parse("192.168.1.2"), 20051)

' Compose and send simple e-mail.
mailer.From.Email = "jdoe@company.com"
mailer.To.Add("jane@example.com")
mailer.Subject = "Test message"
mailer.Send()

In case of "direct send" mode, the same local end point can be specified as:

  • C#
  • VB
Smtp mailer = new Smtp();

// Tell MailBee.NET which DNS servers to use for DNS MX lookup.
mailer.DnsServers.Autodetect();

// Send from the adapter which has 192.168.1.2 address,
// and use 20051 as the local port.
mailer.DirectSendDefaults.LocalEndPoint =
    new System.Net.IPEndPoint(
        System.Net.IPAddress.Parse("192.168.1.2"), 20051);

// Compose and send simple e-mail.
mailer.From.Email = "jdoe@company.com";
mailer.To.Add("jane@example.com");
mailer.Subject = "Test message";
mailer.Send();

Dim mailer As New Smtp()

' Tell MailBee.NET which DNS servers to use for DNS MX lookup.
mailer.DnsServers.Autodetect()

' Send from the adapter which has 192.168.1.2 address,
' and use 20051 as the local port.
mailer.DirectSendDefaults.LocalEndPoint = _
    New System.Net.IPEndPoint( _
        System.Net.IPAddress.Parse("192.168.1.2"), 20051)

' Compose and send simple e-mail.
mailer.From.Email = "jdoe@company.com"
mailer.To.Add("jane@example.com")
mailer.Subject = "Test message"
mailer.Send()

You can also specify zero as the second parameter of System.Net.IPEndPoint constructor in case if only care for the IP address and want to let the OS assign the local port number.

Send custom Hello message to server

By default, MailBee.NET uses the IPv4 address of the sending machine in the parameter of EHLO and HELO commands, or the local host name if the IPv4 address is not available.

Some servers perform reverse DNS check over the domain name or IP address listed in the EHLO/HELO parameter, and do not trust the connections which come from IP addresses not matching those specified in EHLO/HELO. MailBee.NET cannot always determine your external IP address (it's not possible if you're behind NAT) and thus your local IP address will be used. You can use SmtpServer.HelloDomain property to overcome this.

Note that if you specify the IP address instead of the domain name (although it's not recommended), you should enclose it in square brackets. Example: [15.16.23.42], so that the command to be sent would be EHLO [15.16.23.42].

That is, if the relay server you're sending through requires something special to be sent as a parameter of EHLO or HELO (usually, external IP address or the domain of the sending machine), you can set it as below:

  • C#
  • VB
// Use SMTP relay with ESMTP authentication.
SmtpServer server = mailer.SmtpServers.Add(
   "mail.company.com", "jdoe@company.com", "secret");

// Set the custom name MailBee.NET will use
// to represent the client to the server.
server.HelloDomain = "workstation.company.com";

' Use SMTP relay with ESMTP authentication.
Dim server As SmtpServer = mailer.SmtpServers.Add( _
    "mail.company.com", "jdoe@company.com", "secret")

' Set the custom name MailBee.NET will use
' to represent the client to the server.
server.HelloDomain = "workstation.company.com"

In case of direct send mode, setting the domain for HELO/EHLO is essential. Use the public domain name of the machine you're sending from. You can specify this parameter as follows:

  • C#
  • VB
// Set the custom name MailBee.NET will use to represent
// the sending host to MX servers of end recipients.
mailer.DirectSendDefaults.HelloDomain = "mail.company.com";

' Set the custom name MailBee.NET will use to represent
' the sending host to MX servers of end recipients.
mailer.DirectSendDefaults.HelloDomain = "mail.company.com"

We assume mailer is an Smtp instance. See the previous topic to learn how mailer is created and used with normal send and direct send.

Examine supported ESMTP extensions

If the logic of your code assumes different behavior in case if certain ESMTP extensions are available, you can check which extensions are supported by the given SMTP relay server.

Note that MailBee.NET supports many ESMTP extensions out-of-box. This spares you all the trouble of manual check and activation of the supported extensions. For instance, to check which authentication methods are supported by the given server, you can use Smtp.GetSupportedAuthMethods method.

If you need to determine whether the server supports STARTTLS and start the SSL session it if does, you can let MailBee.NET connect to the server, check if STARTTLS is supported, and issue STARTTLS automatically. SeeConnect to regular port and use STARTTLS to activate SSL topic for details.

However, sometimes you may need to check the supported extensions manually. For instance, Advanced STARTTLS topic contains a sample code which manually determines if STARTTLS is supported but issues this command if it's actually required by the server (not just supported).

DSN (Delivery Status Notification) is another example. MailBee.NET won't set DSN parameters during the SMTP session if the relay server does not support it. To determine if DSN is supported, see ESMTP DSN in detail topic.

The console sample below gets the list of all extensions supported by the server, and also checks the availability of ENHANCEDSTATUSCODES extension (RFC1893 and RFC2034). If it's supported, the code takes advantage of it. The code prints the detailed status of every operation (authentication and sending) and performs some exception handling as well:

  • C#
  • VB
using System;
using System.Collections.Specialized;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // Reports the status of the last completed SMTP command,
    // including Enhanced Status Code if available.
    static void ExamineCommandResults(Smtp mailer, bool useEnhancedCodes)
    {
        string lastResponse = mailer.GetServerResponse();
        if (lastResponse.EndsWith("\r\n"))
        {
            lastResponse = lastResponse.Substring(0, lastResponse.Length - 2);
        }
        int simpleCode = mailer.GetServerResponseCode();

        // Extract enhanced status code from the response.
        string enhancedCode = null;
        if (useEnhancedCodes && lastResponse.Length >= 9)
        {
            enhancedCode = lastResponse.Substring(4, 5);
        }

        Console.WriteLine("Last response was: " + lastResponse);
        Console.WriteLine("Simple status code: " + simpleCode.ToString());

        if (enhancedCode != null)
        {
            Console.WriteLine("Enhanced status code: " + enhancedCode);
        }
        else
        {
            Console.WriteLine("Enhanced status code not available");
        }

        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Log file can be helpful when dealing with low-level SMTP functions.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = "C:\\Temp\\log.txt";
        mailer.Log.Clear();

        // Use SMTP relay with authentication.
        mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret");

        // Compose a simple e-mail.
        mailer.From.Email = "john.doe@company.com";
        mailer.To.Add("jane@example.com");
        mailer.Subject = "Test message";

        // To determine if certain extension is supported, we need
        // to explicitly connect to the server and say hello. The server
        // responds with its capabilities to that.
        mailer.Connect();
        mailer.Hello();

        // Get the names and values of the supported extensions.
        // Some extensions have no parameters and their value is empty string.
        StringDictionary extensions =
            mailer.GetExtensions();

        if (extensions == null)
        {
            Console.WriteLine(
                "The given SMTP server does not support any ESMTP extensions");
        }
        else
        {
            // Print the list of the supported extensions.
            foreach (string extension in extensions.Keys)
            {
                string val = extensions[extension];
                if (val != string.Empty)
                {
                    // Print extension name and parameters.
                    Console.WriteLine(extension + " " + val);
                }
                else
                {
                    // For extension without parameters, print its name only.
                    Console.WriteLine(extension);
                }
            }
        }

        Console.WriteLine();

        // Check if ENHANCEDSTATUSCODES extension is available.
        bool useEnhancedCodes =
            (mailer.GetExtension("ENHANCEDSTATUSCODES") != null);

        try
        {
            // Try to authenticate.
            mailer.Login();

            // Report the results if succeeded.
            ExamineCommandResults(mailer, useEnhancedCodes);
        }
        catch (MailBeeSmtpNegativeResponseException e)
        {
            // Report the exception's message.
            Console.WriteLine(e.Message);
            Console.WriteLine();

            // Report the results if failed with a negative error code.
            ExamineCommandResults(mailer, useEnhancedCodes);

            throw;
        }

        try
        {
            // Try to send the message.
            mailer.Send();

            // Report the results if succeeded.
            ExamineCommandResults(mailer, useEnhancedCodes);
        }
        catch (MailBeeSmtpNegativeResponseException e)
        {
            // Report the exception's message.
            Console.WriteLine(e.Message);
            Console.WriteLine();

            // Report the results if failed with a negative error code.
            ExamineCommandResults(mailer, useEnhancedCodes);

            throw;
        }

        // Since we connected manually, we need to disconnect manually either.
        mailer.Disconnect();
    }
}

Imports System
Imports System.Collections.Specialized
Imports MailBee
Imports MailBee.SmtpMail

Module Module1
    ' Reports the status of the last completed SMTP command,
    ' including Enhanced Status Code if available.
    Sub ExamineCommandResults(ByVal mailer As Smtp, _
            ByVal useEnhancedCodes As Boolean)
        Dim lastResponse As String = mailer.GetServerResponse()
        If lastResponse.EndsWith(vbCrLf) Then
            lastResponse = lastResponse.Substring(0, lastResponse.Length - 2)
        End If
        Dim simpleCode As Integer = mailer.GetServerResponseCode()

        ' Extract enhanced status code from the response.
        Dim enhancedCode As String = Nothing
        If useEnhancedCodes And lastResponse.Length >= 9 Then
            enhancedCode = lastResponse.Substring(4, 5)
        End If

        Console.WriteLine("Last response was: " & lastResponse)
        Console.WriteLine("Simple status code: " & simpleCode.ToString())

        If Not (enhancedCode Is Nothing) Then
            Console.WriteLine("Enhanced status code: " & enhancedCode)
        Else
            Console.WriteLine("Enhanced status code not available")
        End If

        Console.WriteLine()
    End Sub

    Sub Main()
        Dim mailer As New Smtp()

        ' Log file can be helpful when dealing with low-level SMTP functions.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Clear()

        ' Use SMTP relay with authentication.
        mailer.SmtpServers.Add("mail.company.com", "john.doe", "secret")

        ' Compose a simple e-mail.
        mailer.From.Email = "john.doe@company.com"
        mailer.To.Add("jane@example.com")
        mailer.Subject = "Test message"

        ' To determine if certain extension is supported, we need
        ' to explicitly connect to the server and say hello. The server
        ' responds with its capabilities to that.
        mailer.Connect()
        mailer.Hello()

        ' Get the names and values of the supported extensions.
        ' Some extensions have no parameters and their value is empty string.
        Dim extensions As StringDictionary = mailer.GetExtensions()

        If extensions Is Nothing Then
            Console.WriteLine( _
                "The given SMTP server does not support any ESMTP extensions")
        Else
            ' Print the list of the supported extensions.
            Dim extension As String
            For Each extension In extensions.Keys
                Dim val As String = extensions(extension)
                If val <> String.Empty Then
                    ' Print extension name and parameters.
                    Console.WriteLine(extension & " " & val)
                Else
                    ' For extension without parameters, print its name only.
                    Console.WriteLine(extension)
                End If
            Next extension
        End If

        Console.WriteLine()

        ' Check if ENHANCEDSTATUSCODES extension is available.
        Dim useEnhancedCodes As Boolean = Not _
            (mailer.GetExtension("ENHANCEDSTATUSCODES") Is Nothing)

        Try
            ' Try to authenticate.
            mailer.Login()

            ' Report the results if succeeded.
            ExamineCommandResults(mailer, useEnhancedCodes)
        Catch e As MailBeeSmtpNegativeResponseException
            ' Report the exception's message.
            Console.WriteLine(e.Message)
            Console.WriteLine()

            ' Report the results if failed with a negative error code.
            ExamineCommandResults(mailer, useEnhancedCodes)

            Throw
        End Try

        Try
            ' Try to send the message.
            mailer.Send()

            ' Report the results if succeeded.
            ExamineCommandResults(mailer, useEnhancedCodes)
        Catch e As MailBeeSmtpNegativeResponseException
            ' Report the exception's message.
            Console.WriteLine(e.Message)
            Console.WriteLine()

            ' Report the results if failed with a negative error code.
            ExamineCommandResults(mailer, useEnhancedCodes)

            Throw
        End Try

        ' Since we connected manually, we need to disconnect manually either.
        mailer.Disconnect()
    End Sub
End Module

Note that you can use the methods like Smtp.GetServerResponse only with a single connection. In case of multiple simultaneous connections or "direct send" mode, such methods make no sense as would not be clear for which of the current connections the method must return the results. If unsure, use Smtp.IsSmtpContext property to determine if you can currently use the methods which can operate in a single-connection mode only.

Disable conflicting ESMTP extensions

Extensions to SMTP protocol can improve performance or add features. However, they are not the essential part of the SMTP standard and may cause issues sometimes. Even though MailBee.NET never enables extensions which are not advertized by the server in EHLO response.

The typical example of a problematic extension is CHUNKING. It should speed up sending performance but it sometimes causes problems with SMTP traffic filters (like e-mail anti-virus) which intercept all the SMTP traffic. If the relay server itself supports CHUNKING and declares this in EHLO response, MailBee.NET then take advantage of it. However, the SMTP filter in the middle might not support CHUNKING and cause the entire transmission to hang or slow down.

Issues with ESMTP extensions can even happen intentionally. MS Exchange supports CHUNKING but works very slowly with it when SMTP Tar Pitting is enabled. MS Exchange does this because CHUNKING is very fast, and that's why many programs for sending spam widely use it, but most desktop e-mail clients still do not. So, if the server sees you're using CHUNKING, it intentionally slows the connection down thinking that you may be a spammer.

See MS Exchange SMTP issues topic on how to disable CHUNKING. Or, just disable SMTP Tar Pitting on the server.

PIPELINING extension allows the client to join several commands in a batch (especially efficient in case of many recipients in the message). If it causes problems with your relay server (although it happens extremely rarely), you can disable it as below:

  • C#
  • VB
mailer.SmtpServers.Add("smtp.domain.com", "joe", "secret").Pipelining = false;

mailer.SmtpServers.Add("smtp.domain.com", "joe", "secret").Pipelining = False

And for "direct send" mode:

  • C#
  • VB
mailer.DirectSendDefaults.Pipelining = false;

mailer.DirectSendDefaults.Pipelining = False

Another case is the very old SMTP servers which don't understand EHLO command and close the connection if they receive an unknown command. Normally, MailBee.NET immediately sends HELO if the server responded to EHLO with a negative reply. But if the server closes the connection instead, you'll have to disable EHLO in MailBee.NET.

The sample below disables EHLO and thus configures the relay server for classic SMTP mode:

  • C#
  • VB
// Use SMTP relay without ESMTP authentication, configured
// to use HELO instead of EHLO. All extensions are disabled.
mailer.SmtpServers.Add("mail.server.com").SmtpOptions =
    ExtendedSmtpOptions.ClassicSmtpMode;

' Use SMTP relay without ESMTP authentication, configured
' to use HELO instead of EHLO. All extensions are disabled.
mailer.SmtpServers.Add("mail.server.com").SmtpOptions = _
    ExtendedSmtpOptions.ClassicSmtpMode

Note we haven't specified the username and password for ESMTP authentication. If your server requires authentication but does not support EHLO, you should probably use POP-before-SMTP authentication. See Authenticate with POP-before-SMTP topic for details.

With "direct send" mode, you can disable EHLO using DirectSendServerConfig.SmtpOptions property which is accessible through Smtp.DirectSendDefaults object:

  • C#
  • VB
mailer.DirectSendDefaults.SmtpOptions = ExtendedSmtpOptions.ClassicSmtpMode;

mailer.DirectSendDefaults.SmtpOptions = ExtendedSmtpOptions.ClassicSmtpMode

We assume mailer is an Smtp instance.

Send custom command to server

You can send user-defined commands to an SMTP server and examine the server's response.

The sample below sends VRFY command to check if the e-mail address is valid. Unfortunately, most e-mail servers nowadays do not let you actually check if the specified address is valid on the given server (spammers started to use it to collect e-mail addresses) so we use this command just for demonstration purposes:

  • C#
  • VB
Smtp mailer = new Smtp();

// Log file can be helpful when dealing with low-level SMTP functions.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

// Do not use authentication here. VRFY command does not require us
// to authenticate first. With other commands, that can be different.
mailer.SmtpServers.Add("smtp.domain.com");

mailer.Connect();
mailer.Hello();

try
{
    // Do not forget CRLF at the end of the command!
    mailer.ExecuteCustomCommand("VRFY user@domain.com\r\n");
}
catch (MailBeeSmtpNegativeResponseException e)
{
    // Perhaps, unknown command or unknown user account.
    Console.WriteLine("Oops...");
    Console.WriteLine(e.Message);
    Console.WriteLine();
}

Console.WriteLine("Server replied: " + mailer.GetServerResponse());
Console.WriteLine("Status code is: " + mailer.GetServerResponseCode().ToString());

// Since we connected manually, we need to disconnect manually either.
mailer.Disconnect();

Dim mailer As New Smtp()

' Log file can be helpful when dealing with low-level SMTP functions.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Do not use authentication here. VRFY command does not require us
' to authenticate first. With other commands, that can be different.
mailer.SmtpServers.Add("smtp.domain.com")

mailer.Connect()
mailer.Hello()

Try
    ' Do not forget CRLF at the end of the command!
    mailer.ExecuteCustomCommand("VRFY user@domain.com" & vbCrLf)
Catch e As MailBeeSmtpNegativeResponseException
    ' Perhaps, unknown command or unknown user account.
    Console.WriteLine("Oops...")
    Console.WriteLine(e.Message)
    Console.WriteLine()
End Try

Console.WriteLine("Server replied: " & mailer.GetServerResponse())
Console.WriteLine("Status code is: " & mailer.GetServerResponseCode().ToString())

' Since we connected manually, we need to disconnect manually either.
mailer.Disconnect()

You can also find the async version of this sample in Smtp.BeginExecuteCustomCommand method documentation.

Send feedback to AfterLogic


SMTP with filesystem, POP3, IMAP (forward from POP3, send to SMTP and IMAP)

  • Introduction
  • Load e-mail from file and send it
  • Send e-mail and save it to Sent Items on IMAP server
  • Send e-mail and save it to file stream
  • Receive e-mail with POP3, forward it as attachment of another e-mail and send with SMTP
  • Receive e-mail with IMAP, reply to it and send via SMTP

Introduction

MailBee.NET SMTP component allows you not only compose e-mails but also load them from other sources like files in MIME format, memory, e-mail messages received from a POP3 or IMAP server, and so on.

For instance, you can receive an e-mail from a POP3 or IMAP server, adjust it and send it again. Or, you can send an e-mail and also upload it into a folder on an IMAP server. You can save the e-mail into a file, read it back another time and send it, and so on.

Using MailBee.NET Outlook component, you can also load e-mails from Outlook .MSG and .PST files. This component is the part of MailBee.NET assembly, see PstReader and MsgConvert classes if interested.

Load e-mail from file and send it

Let's assume you have a file containing an e-mail message in MIME format (i.e. any valid .EML file). That's how you can read it from disk and send it out:

  • C#
  • VB
Smtp mailer = new Smtp();

// Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.here.com", "joe", "secret");

mailer.Message.LoadMessage("C:\\Docs\\message.eml");
mailer.Send();

Dim mailer As New Smtp()

' Use SMTP relay server with authentication.
mailer.SmtpServers.Add("mail.here.com", "joe", "secret")

mailer.Message.LoadMessage("C:\Docs\message.eml")
mailer.Send()

We assume MailBee, MailBee.Mime, and MailBee.SmtpMail namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

The above sends a single e-mail. What if you got 1000 e-mails to be sent from files? You can use MailBee.NET Queue for that (it's a separate application with its own installer, not a part of MailBee.NET assembly).

If for some reason you can't use MailBee.NET Queue directly, you can still examine its source code to find how to efficiently use MailBee.NET to read e-mails from files and send them (MailBee.NET Queue comes with the full source code).

In particular, MailBee.NET Queue internally uses Smtp.AddJob (string, string, bool, string, EmailAddressCollection) method which allows the application to load from files and send out large volumes of e-mails without loading them all into memory at once.

You can also alter the e-mail which you loaded from a file, no limitations here. Add, remove or change any header or any part.

On other hand, you may want to completely disable MailBee.NET to alter the e-mail you read from a file. For instance, when a message gets sent, MailBee.NET by default changes its "Date" to the timestamp of the current moment, sets the unique Message-ID, can generate plain-text alternate body for HMTL-only e-mail, etc. To disable this, use the properties of MessageBuilderConfig class, like MessageBuilderConfig.SetDateOnSend property.

To access MessageBuilderConfig object of the message attached to the Smtp object (denoted by mailer instance), use MailMessage.Builder property. For instance, to disable automatic setting of "Date" header:

  • C#
  • VB
mailer.Message.Builder.SetDateOnSend = false;

mailer.Message.Builder.SetDateOnSend = false

The above applies to any methods of loading messages from external source (from file, stream, memory array, etc).

Send e-mail and save it to Sent Items on IMAP server

If you need to upload the e-mail you've just sent into a folder on your IMAP server, that's how:

  • C#
  • VB
Smtp mailer = new Smtp();

// First part of the log is all about SMTP session.
mailer.Log.Enabled = true;
mailer.Log.Filename = "C:\\Temp\\log.txt";
mailer.Log.Clear();

mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret");

mailer.Message.From.AsString = "Joe D. <joe@here.com>";
mailer.Message.To.AsString = "Carl S. <carl@there.com>";
mailer.Message.Subject = "Greetings from Joe";
mailer.Message.BodyPlainText = "Hi there!";

mailer.Send();

Console.WriteLine("Sent successfully");

Imap imp = new Imap();

// Second part of the log represents IMAP session.
imp.Log.Enabled = true;
imp.Log.Filename = "C:\\Temp\\log.txt";

imp.Connect("imap.here.com");
imp.Login("joe@here.com", "secret");

try
{
    imp.UploadMessage(mailer.Message, "Sent");
    Console.WriteLine("Uploaded successfully");
}
catch (MailBeeImapNegativeResponseException e)
{
    Console.WriteLine("Perhaps, can't select folder");
    if (!string.IsNullOrEmpty(e.HumanReadable))
    {
        Console.WriteLine("Server reported: " + e.HumanReadable);
    }
    Console.WriteLine();
    Console.WriteLine("The folders available are:");
    FolderCollection folders = imp.DownloadFolders();
    foreach (Folder fold in folders)
    {
        Console.WriteLine(fold.Name);
    }
}

imp.Disconnect();

Dim mailer As New Smtp()

' First part of the log is all about SMTP session.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret")

mailer.Message.From.AsString = "Joe D. <joe@here.com>"
mailer.Message.To.AsString = "Carl S. <carl@there.com>"
mailer.Message.Subject = "Greetings from Joe"
mailer.Message.BodyPlainText = "Hi there!"

mailer.Send()

Console.WriteLine("Sent successfully")

Dim imp As New Imap()

' Second part of the log represents IMAP session.
imp.Log.Enabled = True
imp.Log.Filename = "C:\Temp\log.txt"

imp.Connect("imap.here.com")
imp.Login("joe@here.com", "secret")

Try
    imp.UploadMessage(mailer.Message, "Sent")
    Console.WriteLine("Uploaded successfully")
Catch e As MailBeeImapNegativeResponseException
    Console.WriteLine("Perhaps, can't select folder")
    If Not String.IsNullOrEmpty(e.HumanReadable) Then
        Console.WriteLine("Server reported: " & e.HumanReadable)
    End If
    Console.WriteLine()
    Console.WriteLine("The folders available are:")
    Dim folders As FolderCollection = imp.DownloadFolders()
    Dim fold As Folder
    For Each fold In folders
        Console.WriteLine(fold.Name)
    Next fold
End Try

imp.Disconnect()

We assume your license key covers not only Smtp class but Imap as well. You also need to import MailBee.ImapMail namespace.

Send e-mail and save it to file stream

The sample below sends an e-mail and saves it into a stream.

We're using the file stream here but this is for demonstration purposes only. You can save directly in files with MailBee.NET (see the commented piece of the code). With streams, however, you can output the message data anywhere.

To compile this sample, you'll need to import System.IO namespace as well:

  • C#
  • VB
Smtp mailer = new Smtp();

mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret");

mailer.Message.From.AsString = "Joe D. <joe@here.com>";
mailer.Message.To.AsString = "Carl S. <carl@there.com>";
mailer.Message.Subject = "Greetings from Joe";
mailer.Message.BodyPlainText = "Hi there!";

mailer.Send();

// Use stream to save e-mail to disk.
FileStream fs = new FileStream("C:\\Temp\\message.eml", FileMode.Create);
mailer.Message.SaveMessage(fs);
fs.Close();

// Simpler method to save e-mail to disk.
// mailer.Message.SaveMessage("C:\\Temp\\message.eml");

Console.WriteLine("Sent and saved");

Dim mailer As New Smtp()

mailer.SmtpServers.Add("smtp.here.com", "joe@here.com", "secret")

mailer.Message.From.AsString = "Joe D. <joe@here.com>"
mailer.Message.To.AsString = "Carl S. <carl@there.com>"
mailer.Message.Subject = "Greetings from Joe"
mailer.Message.BodyPlainText = "Hi there!"

mailer.Send()

' Use stream to save e-mail to disk.
Dim fs As New FileStream("C:\Temp\message.eml", FileMode.Create)
mailer.Message.SaveMessage(fs)
fs.Close()

' Simpler method to save e-mail to disk.
' mailer.Message.SaveMessage("C:\\Temp\\message.eml")

Console.WriteLine("Sent and saved")

Receive e-mail with POP3, forward it as attachment of another e-mail and send with SMTP

Individual MailBee.NET components can efficiently interoperate with each other. For instance, you can get an existing e-mail (for example, receive it from a POP3 server), alter it in some way or even build a new e-mail from it, and send the resulting e-mail out (or, upload it to an IMAP server, save it into a file or whatever).

This sample receives an e-mail from a POP3 server, creates a new e-mail, attaches the previously received e-mail to the new e-mail in "forward as attachment" way (it does this twice to demonstrate different methods of this), and submits the resulting e-mail to the SMTP relay server:

  • C#
  • VB
// Get the most recent message in Inbox.
MailMessage msg = Pop3.QuickDownloadMessage(
    "pop.domain.com", "joe", "secret", -1);

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("smtp.domain.com", "joe", "secret");

// Build forwarded message, method #1 (simpler).
// Creates new message and attaches old message.
mailer.Message = msg.ForwardAsAttachment();

// Build forwarded message, method #2 (allows adding multiple forwarded
// messages). Adds the message being forwarded to an existing message.
mailer.Message.Attachments.Add(msg, string.Empty, null, null, null,
    NewAttachmentOptions.Inline, MailTransferEncoding.None);

mailer.Message.From.AsString = "Joe D. <joe@domain.com>";
mailer.Message.To.AsString = "Carl S. <carl@there.com>";
mailer.Message.Subject = "FW: message";
mailer.Message.BodyPlainText = "See the forwarded message";

mailer.Send();

' Get the most recent message in Inbox.
Dim msg As MailMessage = Pop3.QuickDownloadMessage( _
    "pop.domain.com", "joe", "secret", -1)

Dim mailer As New Smtp()
mailer.SmtpServers.Add("smtp.domain.com", "joe", "secret")

' Build forwarded message, method #1 (simpler).
' Creates new message and attaches old message.
mailer.Message = msg.ForwardAsAttachment()

' Build forwarded message, method #2 (allows adding multiple forwarded
' messages). Adds the message being forwarded to an existing message.
mailer.Message.Attachments.Add(msg, String.Empty, Nothing, Nothing, Nothing, _
    NewAttachmentOptions.Inline, MailTransferEncoding.None)

mailer.Message.From.AsString = "Joe D. <joe@domain.com>"
mailer.Message.To.AsString = "Carl S. <carl@there.com>"
mailer.Message.Subject = "FW: message"
mailer.Message.BodyPlainText = "See the forwarded message"

mailer.Send()

We assume the license key covers not only Smtp class but Pop3 as well. You also need to import MailBee.Pop3Mail namespace.

Receive e-mail with IMAP, reply to it and send via SMTP

Replying and forwarding inline (not as attachment) in the general case is complicated if you want to keep the original message text in the reply. This is because there is not single standard for this and each e-mail client uses different methods for this. Replying to HTML and plain-text messages may also be different.

This sample makes a reply in a pretty simple way. The original body is put in behind the new text, and a separator is inserted in between. If the source message is HTML-only, plain-text is generated from it first as the sample creates the reply in plain-text:

  • C#
  • VB
// Get the most recent message in Inbox.
MailMessage msg = Imap.QuickDownloadMessage(
    "mail.provider.com", "joe@here.com", "secret", "Inbox", -1);

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.provider.com", "joe@here.com", "secret");

// Make sure we've got plain-text body of the original,
// even if the original message didn't have it.
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;

// Set the reply body.
mailer.Message.BodyPlainText =
    "This is reply, the original follows...\r\n\r\n" +
    "--------------------------------------\r\n\r\n" +
    msg.BodyPlainText;

// Set "To" from "Reply-To" or "From" of the original.
if (msg.ReplyTo.Count > 0)
{
    mailer.Message.To.Add(msg.ReplyTo);
}
else
{
    mailer.Message.To.Add(msg.From);
}

// Add In-Reply-To to make it easier for the receiving side
// to match this reply and the original message.
mailer.Message.Headers["In-Reply-To"] = msg.MessageID;

// Set other headers. For demonstration purposes, in "From" field,
// specify display name and e-mail address separately.
mailer.Message.From = new EmailAddress("Joe D.", "joe@here.com");
mailer.Message.Subject = "Re: " + msg.Subject;

mailer.Send();

' Get the most recent message in Inbox.
Dim msg As MailMessage = Imap.QuickDownloadMessage( _
    "mail.provider.com", "joe@here.com", "secret", "Inbox", -1)

Dim mailer As New Smtp()
mailer.SmtpServers.Add("mail.provider.com", "joe@here.com", "secret")

' Make sure we've got plain-text body of the original,
' even if the original message didn't have it.
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain

' Set the reply body.
mailer.Message.BodyPlainText = _
    "This is reply, the original follows..." & vbCrLf & vbCrLf & _
    "--------------------------------------" & vbCrLf & vbCrLf & _
    msg.BodyPlainText

' Set "To" from "Reply-To" or "From" of the original.
If msg.ReplyTo.Count > 0 Then
    mailer.Message.To.Add(msg.ReplyTo)
Else
    mailer.Message.To.Add(msg.From)
End If

' Add In-Reply-To to make it easier for the receiving side
' to match this reply and the original message.
mailer.Message.Headers("In-Reply-To") = msg.MessageID

' Set other headers. For demonstration purposes, in "From" field,
' specify display name and e-mail address separately.
mailer.Message.From = New EmailAddress("Joe D.", "joe@here.com")
mailer.Message.Subject = "Re: " & msg.Subject

mailer.Send()

We assume your license key covers not only Smtp class but Imap as well. You also need to import MailBee.ImapMail namespace.

Send feedback to AfterLogic


Use events to control MailBee.NET execution and monitor SMTP activities

  • Introduction
  • Monitor progress of SMTP session with events
  • Alter e-mail message during sending
  • Cancel sending process

Introduction

Smtp object provides lots of events you can subscribe to. This gives you a great control over the entire process how the message is sent.

You can track every byte being transmitted over the network and every step of the connection, alter the e-mail being sent just before it gets submitted to the server (useful for mail merge), and so on.

Some events of Smtp object mainly make sense for bulk sending mode when multiple e-mails get sent within a single method call. They are MergingMessage, SendingMessage, MessageSent, MessageNotSent,SubmittingMessageToPickupFolder, MessageSubmittedToPickupFolder, and FinishingJob .

It should be also stated that MailBee.NET provides a protected On<EventName> method for every event. This allows you to derive your own class from Smtp class and implement your own handlers for events. This can be useful in some special cases such as handling events when the message loop thread is blocked (can happen in desktop applications). See Smtp.OnConnected method documentation for details.

Monitor progress of SMTP session with events

This console sample subscribes to a few events to control the key points of the SMTP session: establishing the connection, submitting the sender and every recipient, the upload progress of the message data:

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    private static void OnConnected(object sender,
        ConnectedEventArgs e)
    {
        Console.WriteLine("The server accepted the connection.");
    }

    private static void OnSenderOK(object sender,
        SmtpMessageSenderSubmittedEventArgs e)
    {
        Console.WriteLine(e.SenderEmail + " accepted as sender.");
    }

    private static void OnRecipientOK(object sender,
        SmtpMessageRecipientSubmittedEventArgs e)
    {
        Console.WriteLine(e.RecipientEmail + " accepted as recipient");
    }

    private static void OnDataChunkSent(object sender,
        SmtpMessageDataChunkSentEventArgs e)
    {
        Console.WriteLine(string.Format("{0} of {1} bytes sent",
            e.TotalBytesSent.ToString(), e.DataTotalLength.ToString()));
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "john.doe", "secret");

        // Set From, To and CC as strings (with friendly names).
        mailer.Message.From.AsString = "John Doe <john.doe@here.com>";
        mailer.Message.To.AsString = "Jane Doe <jane.doe@there.com>";
        mailer.Message.Cc.AsString = "John Smith <j.smith@elsewhere.com>";

        mailer.Message.Subject = "Test message";
        mailer.Message.BodyPlainText = "This is a test message";

        // Subscribe to events.
        mailer.Connected += new ConnectedEventHandler(OnConnected);
        mailer.MessageSenderSubmitted +=
            new SmtpMessageSenderSubmittedEventHandler(OnSenderOK);
        mailer.MessageRecipientSubmitted +=
            new SmtpMessageRecipientSubmittedEventHandler(OnRecipientOK);
        mailer.MessageDataChunkSent +=
            new SmtpMessageDataChunkSentEventHandler(OnDataChunkSent);

        mailer.Send();
    }
}

Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    Private Sub OnConnected(ByVal sender As Object, _
            ByVal e As ConnectedEventArgs)

        Console.WriteLine("The server accepted the connection.")
    End Sub

    Private Sub OnSenderOK(ByVal sender As Object, _
            ByVal e As SmtpMessageSenderSubmittedEventArgs)

        Console.WriteLine(e.SenderEmail + " accepted as sender.")
    End Sub

    Private Sub OnRecipientOK(ByVal sender As Object, _
            ByVal e As SmtpMessageRecipientSubmittedEventArgs)

        Console.WriteLine(e.RecipientEmail + " accepted as recipient")
    End Sub

    Private Sub OnDataChunkSent(ByVal sender As Object, _
            ByVal e As SmtpMessageDataChunkSentEventArgs)

        Console.WriteLine(String.Format("{0} of {1} bytes sent", _
          e.TotalBytesSent.ToString(), _
          e.DataTotalLength.ToString()))
    End Sub

    Sub Main()
        Dim mailer As Smtp = New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "john.doe", "secret")

        ' Set From, To and CC as strings (with friendly names).
        mailer.Message.From.AsString = "John Doe <john.doe@here.com>"
        mailer.Message.To.AsString = "Jane Doe <jane.doe@there.com>"
        mailer.Message.Cc.AsString = "John Smith <j.smith@elsewhere.com>"

        mailer.Message.Subject = "Test message"
        mailer.Message.BodyPlainText = "This is a test message"

        ' Subscribe to events.
        AddHandler mailer.Connected, AddressOf OnConnected
        AddHandler mailer.MessageSenderSubmitted, AddressOf OnSenderOK
        AddHandler mailer.MessageRecipientSubmitted, AddressOf OnRecipientOK
        AddHandler mailer.MessageDataChunkSent, AddressOf OnDataChunkSent

        mailer.Send()
    End Sub
End Module

The samples throughout this guide assume that MailBee.NET SMTP license key is already set. See Import namespaces and set license key topic for details.

Alter e-mail message during sending

MergingMessage, SendingMessage and SubmittingMessageToPickupFolder events of Smtp object allow you to pre-process the e-mail before it gets sent (in case of MergingMessage, before the e-mail is created from the template).

Consider the following mail merge scenario. You've set the template and the data source and started the mail merge process. For every row of the data source, mail merge procedure generates an e-mail and sends it. All is great until you find out that you need to "touch" every message a bit.

When sending a single e-mail, you can fine-tune it as you need before calling Smtp.Send method. But during mail merge all e-mails get generated automatically. In this case, you can use SendingMessage event. This will work with a single e-mail as well.

The console sample below performs mail merge and uses SendingMessage event to sign every outgoing message with a DKIM signature:

  • C#
  • VB
using System;
using System.Data;
using System.IO;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;
using MailBee.Security;

class Sample
{
    private static void OnSendingMessage(object sender,
        SmtpSendingMessageEventArgs e)
    {
        // Sign each outgoing e-mail with DKIM signature.
        e.MailMessage.DomainKeysSign(
            false, null, privateKey, false, "dk", DomainKeysTypes.DKIM);
    }

    static string privateKey = null;

    static void Main(string[] args)
    {
        // Describe the data source for the mail merge.
        // In real apps, you'll connect to the database.
        DataTable workTable = new DataTable("customers");

        DataColumn workCol = workTable.Columns.Add("id", typeof(int));
        workCol.AllowDBNull = false;
        workCol.Unique = true;

        workTable.Columns.Add("name", typeof(string));
        workTable.Columns.Add("email", typeof(string));

        // Add two rows to the data source. This way, the mail merge
        // procedure will generate two e-mails.
        DataRow row = workTable.NewRow();
        row["id"] = 1;
        row["name"] = "John Doe";
        row["email"] = "john.doe@company.com";
        workTable.Rows.Add(row);

        row = workTable.NewRow();
        row["id"] = 2;
        row["name"] = "Bob Brown";
        row["email"] = "bob.brown@example.com";
        workTable.Rows.Add(row);

        // To avoid re-reading private key for each message,
        // we read it once and then use memory copy.
        privateKey = File.ReadAllText(@"C:\Temp\rsa512.private");

        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret");

        // Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>";
        mailer.Message.Subject = "Greetings";

        // Set templates for To and body.
        mailer.Message.To.AsString = "##name## <##email##>";
        mailer.Message.BodyPlainText = "Message for ##name##";

        // Subscribe to SendingMessage event.
        mailer.SendingMessage +=
            new SmtpSendingMessageEventHandler(OnSendingMessage);

        // Generate and send e-mails.
        mailer.SendMailMerge(null, null, workTable);
    }
}

Imports System
Imports System.Data
Imports System.IO
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports MailBee.Security

Module Module1
    Private Sub OnSendingMessage(ByVal sender As Object, _
            ByVal e As SmtpSendingMessageEventArgs)

        ' Sign each outgoing e-mail with DKIM signature.
        e.MailMessage.DomainKeysSign(False, Nothing, privateKey, _
        False, "dk", DomainKeysTypes.DKIM)
    End Sub

    Private privateKey As String = Nothing

    Sub Main()
        ' Describe the data source for the mail merge.
        ' In real apps, you'll connect to the database.
        Dim workTable As New DataTable("customers")

        Dim workCol As DataColumn = _
        workTable.Columns.Add("id", GetType(Integer))
        workCol.AllowDBNull = False
        workCol.Unique = True

        workTable.Columns.Add("name", GetType(String))
        workTable.Columns.Add("email", GetType(String))

        ' Add two rows to the data source. This way, the mail merge
        ' procedure will generate two e-mails.
        Dim row As DataRow = workTable.NewRow()
        row("id") = 1
        row("name") = "John Doe"
        row("email") = "john.doe@company.com"
        workTable.Rows.Add(row)

        row = workTable.NewRow()
        row("id") = 2
        row("name") = "Bob Brown"
        row("email") = "bob.brown@example.com"
        workTable.Rows.Add(row)

        ' To avoid re-reading private key for each message,
        ' we read it once and then use memory copy.
        privateKey = File.ReadAllText("C:\Temp\rsa512.private")

        Dim mailer As Smtp = New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret")

        ' Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>"
        mailer.Message.Subject = "Greetings"

        ' Set templates for To and body.
        mailer.Message.To.AsString = "##name## <##email##>"
        mailer.Message.BodyPlainText = "Message for ##name##"

        ' Subscribe to SendingMessage event.
        AddHandler mailer.SendingMessage, AddressOf OnSendingMessage

        ' Generate and send e-mails.
        mailer.SendMailMerge(Nothing, Nothing, workTable)
    End Sub
End Module

Cancel sending process

In any event handler (or in any thread), you can call mailer.Abort to immediately close the connection (mailer denotes Smtp instance which raised this event).

"Any event handler" is not limited to "any MailBee.NET event handler". For instance, you can call mailer.Abort in Form_Closing event handler of your main form (this will abort MailBee.NET immediately when the user closes the application). Just make sure you declared mailer on the global level so that Form_Closing could access it.

Also, MergingMessage, SendingMessage and SubmittingMessageToPickupFolder events of Smtp object allow you to skip the particular message but continue to subsequent messages.

With MessageRecipientSubmitted event, you can cancel the sending process in case if the e-mail address of a certain important recipient gets rejected by the SMTP server. See Use events to track successful and failed recipients during sending e-mail topic for details.

And there is Smtp.StopJobs method (can be used with mail merge or whenever you send bulk mail). It stops bulk mail process more gracefully than Smtp.Abort because it first completes sending of the e-mail currently being sent and simply does not continue processing other pending e-mails.

The code snippet below contains the handler of SendingMessage event, which skips messages if they are greater than 100KB in size. It also aborts the entire process if certain external variable aborted becomes true:

  • C#
  • VB
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static bool aborted = false;
    static Smtp mailer = new Smtp();

    static void OnSendingMessage(object sender,
        SmtpSendingMessageEventArgs e)
    {
        if (aborted)
        {
            mailer.Abort();
        }
        else if (e.MailMessage.Size > 1024 * 100)
        {
            e.SendIt = false;
        }
    }

    static void Main(string[] args)
    {
        // Attach event handler.
        mailer.SendingMessage +=
            new SmtpSendingMessageEventHandler(OnSendingMessage);

        // The rest of your code...
    }
}

Imports System
Imports MailBee
Imports MailBee.SmtpMail

Module Module1
    Private aborted As Boolean = False
    Private mailer As New Smtp()

    Sub OnSendingMessage(ByVal sender As Object, _
            ByVal e As SmtpSendingMessageEventArgs)
        If aborted Then
            mailer.Abort()
        Else
            If e.MailMessage.Size > 1024 * 100 Then
                e.SendIt = False
            End If
        End If
    End Sub

    Sub Main()
        ' Attach event handler.
        AddHandler mailer.SendingMessage, AddressOf OnSendingMessage

        ' The rest of your code...
    End Sub
End Module

We assume the main code uses mailer object to send bulk mail and sets aborted to true when it wants MailBee.NET not to send any more messages and close the connection.

It's understood that the connection won't be closed immediately when you set aborted to true. OnSendingMessage handler will be able to respond to this only when SendingMessage event gets raised. If you want to abort the connection immediately, call mailer.Abort.

Send feedback to AfterLogic


Handle exceptions and errors

  • Introduction
  • Error codes and localization of error messages
  • Connection-level and protocol-level exceptions
  • Final errors, warnings, and ErrorOccurred event
  • Exceptions and async methods
  • TestSend example

Introduction

In case of an error, Smtp class by default throws an exception (like all other classes of MailBee.NET do). Although you can disable exceptions using Smtp.ThrowExceptions property if you don't like them, it's not recommended as it may hide some errors which would remain untrapped.

This guide mainly contains the technical background. For the code samples, see Exceptions and errors and TestSend example topics.

MailBee.NET provides an extremely manifold system of exceptions. This lets you programmatically catch exceptions you expect and leave other exceptions unhandled (so that if an unexpected exception occurs, you'd see the program break on it instead of erroneous behavior when this exception is caught by the handler intended for other exception, and unpredictable results occur).

The base is MailBeeException. Some of its descendants such as MailBeeInvalidArgumentException and MailBeeInvalidStateException usually indicate errors in your code and cannot be disabled even if you set Smtp.ThrowExceptions property value to false. Other exceptions can occur due to external factors like network, file I/O and data format errors.

Some exceptions provide a lot of additional information besides the human-readable message. This allows your application to respond to the exception programmatically (for instance, the application can display the text of an error message from the server or the numeric error code of a Win32 error).

Error codes and localization of error messages

All exceptions deriving from MailBeeException support MailBeeException.ErrorCode property which is another method of how you can determine which error occurred. The list of error codes is available in ErrorCodes class.

Note that some exceptions can have more than one error code associated with them (and thus an error code can be more specific to the particular error than just an exception type). See TestSend Example topic for the sample code.

Error messages associated with error codes are defined in Resources class. This class can be inherited so that you can adjust some (or all) error codes along with other strings like log file messages. For instance, you may want to translate the error messages to your local language. Of course, only MailBee.NET's own messages can be translated. Many exceptions include in their text the messages from their inner exceptions and these inner exceptions are thrown by .NET Framework itself. Their language will depend on the localization of the particular .NET Framework installation.

MailBeeException.ErrorCode property can be not the only error code associated with the given exception. Some exceptions provide additional codes specific to their context. For instance,MailBeeSmtpNegativeResponseException.ResponseCode property gets the SMTP error code of the last response from the server.

Connection-level and protocol-level exceptions

Network-related exceptions can be of two kinds:

  • Connection-level errors which make it impossible to continue the current session. The connection with the e-mail server has to be closed then.
  • Protocol-level exceptions which indicate the server responded with a negative reply. The connection itself remains valid and we can send another command (for instance, try again with another password if the server refused one).

To check if the connection is still valid after the exception, you can use Smtp.IsConnected property. Also, all exceptions which indicate the connection is no longer usable implement IMailBeeSocketMustCloseException interface (after such exceptions, Smtp.IsConnected is always false).

If the connection is valid after the exception, you can send other commands if you wish. If you don't, you should issue Smtp.Disconnect method in case if you manually called Smtp.Connect to start the SMTP session (i.e. the same procedure to follow as if no exception would have occurred at all).

In other words, a protocol-level exception does not leave any negative impact on the connection and if you caught it, you can continue as if nothing had happened.

However, please note that some servers drop the connection in addition to returning a negative reply. If this happens, you'll of course need to reconnect.

Final errors, warnings, and ErrorOccurred event

When you send a single e-mail through a single SMTP relay server, any error is a show stopper (aside from the case when SmtpServer.IgnoreLoginFailure is true and the authentication error occurs).

However, if you send through multiple servers (mailer.SmtpServers.Count > 1, assuming mailer is an Smtp instance) or send multiple e-mails with a method like Smtp.SendJobs, a single error does not yet indicate the entire operation has failed.

MailBee.NET won't throw an exception if the occurred problem either affects only a particular operation within the complex process or it can be overcome with another attempt (for instance, backup SMTP relay server was able to successfully deliver the message, the DNS server has responded at the second time, etc).

Still, to inform you that things are not perfectly good, MailBee.NET raises Smtp.ErrorOccurred event in every case when an internal exception occurs and gets caught by MailBee.NET itself. Also, MailBee.NET raises this event in case of a "real" exception which will then be re-thrown to your application.

Thus, two kinds of Smtp.ErrorOccurred events exist:

  • Some represent the issues MailBee.NET will take care of on its own.
  • Others denote the problems MailBee.NET can't work around, they are followed by an exception thrown.

To let the application distinguish between those kinds of Smtp.ErrorOccurred events, its event argument includes ErrorEventArgs.IsFinalError property. If IsFinalError is false, this is just a warning, not a real error yet.

The meaning of warning, however, is quite relative. If you call Smtp.Send to send a single e-mail, it would be a warning if the message failed to be sent through the main relay server (but we have a backup server still to try). But if the e-mail fails completely (e.g. we have no backup server or it failed either), this will be a real error. However, in case of Smtp.SendJobs which can send multiple e-mails, even the total failure of a single e-mail won't stop the entire process and will be considered warning.

If you need to know exactly if certain e-mail in a series has been sent or not, use Smtp.MessageSent, Smtp.MessageNotSent, or Smtp.FinishingJob events. We assume that the method you're using to send the series of e-mails is a method like Smtp.SendJobs or Smtp.SendMailMerge (rather than multiple calls of Smtp.Send method).

For the sample code, refer to Monitor mail merge progress and track successful and failed sendings topic.

In the event handler, you can access the exception which prevented the e-mail from being sent to all or some recipients, via Reason property of the event parameters object (for instance, SmtpMessageNotSentEventArgs.Reason in case of Smtp.MessageNotSent event and ErrorEventArgs.Reason for Smtp.ErrorOccurred event).

Also, in case of Smtp.SendJobs and similar methods, the exception objects are saved in SendMailJob.ErrorReason property of every job in Smtp.JobsFailed collection (which you can examine during or after execution of Smtp.SendJobs method). Thus, you can analyze failures even not using events at all, just by iterating through this collection.

Exceptions and async methods

When using deprecated BeginXXX/EndXXX async methods and callback functions, it's important to catch exceptions. If you don't catch exceptions, the async callback will silently terminate in case of an error. This happens because an unhandled exception which occurred on a worker thread terminates only that thread, not the entire application and its main thread. The application will never know what happened. To avoid this, all samples is this guide do catch exceptions.

The same is true for modern async/await methods (with XXXAsync names). Although they are easier to use in many aspects, not handling an exception may have the effect when the current action (such as button click) does seemingly nothing to the user.

TestSend example

The console sample below was created from the internal implementation of Smtp.TestSend method. It shows the meaning of various exceptions and error codes of MailBee.NET and how they match TestSendResult values:

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Pop3Mail;
using MailBee.DnsMX;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // To make an exception get thrown, use wrong password.
        mailer.SmtpServers.Add("smtp.here.com", "joe", "bad password");

        // Prepare a simple e-mail.
        mailer.Message.From = new EmailAddress("joe@here.com");
        mailer.Message.To.Add("bill@there.com");
        mailer.Message.Subject = "Test message";

        TestSendResult result = TestSendResult.OK;
        try
        {
            // And try to send it.
            mailer.Send();
        }
        catch (MailBeeInvalidArgumentException e)
        {
            if (e.ErrorCode == ErrorCodes.NoSender)
            {
                result = TestSendResult.NoSender;
            }
            else if (e.ErrorCode == ErrorCodes.NoRecipients)
            {
                result = TestSendResult.NoRecipients;
            }
            else if (e.ErrorCode == ErrorCodes.EmptyHostNameForDnsQuery)
            {
                result = TestSendResult.NoDomainInRecipientEmail;
            }
            else
            {
                result = TestSendResult.UnknownError;
            }
        }
        catch (MailBeeSmtpRefusedSenderException)
        {
            result = TestSendResult.BadSender;
        }
        catch (MailBeeSmtpRefusedRecipientException)
        {
            result = TestSendResult.BadRecipient;
        }
        catch (MailBeeSmtpNoAcceptedRecipientsException)
        {
            result = TestSendResult.NoAcceptedRecipients;
        }
        catch (MailBeeLoginNoCredentialsException)
        {
            result = TestSendResult.NoCredentials;
        }
        catch (MailBeeLoginNoSupportedMethodsException)
        {
            result = TestSendResult.NoSupportedAuth;
        }
        catch (MailBeeSmtpLoginBadMethodException)
        {
            result = TestSendResult.BadAuthMethod;
        }
        catch (MailBeeSmtpLoginBadCredentialsException)
        {
            result = TestSendResult.BadCredentials;
        }
        catch (MailBeePop3LoginBadCredentialsException)
        {
            result = TestSendResult.BadCredentials;
        }
        catch (MailBeeSmtpNegativeResponseException)
        {
            result = TestSendResult.NegativeSmtpResponse;
        }
        catch (MailBeePop3NegativeResponseException)
        {
            result = TestSendResult.NegativePop3Response;
        }
        catch (MailBeeDnsNameErrorException)
        {
            result = TestSendResult.NoMXRecord;
        }
        catch (MailBeeDnsProtocolException)
        {
            result = TestSendResult.DnsProtocolError;
        }
        catch (MailBeeConnectionException e)
        {
            switch (e.Protocol)
            {
                case TopLevelProtocolType.Smtp:
                    result = TestSendResult.SmtpConnectionError;
                    break;
                case TopLevelProtocolType.Dns:
                    result = TestSendResult.DnsConnectionError;
                    break;
                case TopLevelProtocolType.Pop3:
                    result = TestSendResult.Pop3ConnectionError;
                    break;
                default:
                    result = TestSendResult.UnknownError;
                    break;
            }
        }
        catch (MailBeeGetRemoteHostNameException e)
        {
            switch (e.HostProtocol)
            {
                case TopLevelProtocolType.Smtp:
                    result = TestSendResult.SmtpResolveHostError;
                    break;
                case TopLevelProtocolType.Pop3:
                    result = TestSendResult.Pop3ResolveHostError;
                    break;
                default:
                    result = TestSendResult.UnknownError;
                    break;
            }
        }
        catch (MailBeeException)
        {
            result = TestSendResult.UnknownError;
        }

        // Display the result of sending attempt.
        // For instance, if the client successfully connects with
        // the server but the server says the login or password
        // is incorrect, will display BadCredentials.
        Console.WriteLine(result.ToString());
    }
}

Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pop3Mail
Imports MailBee.DnsMX
Imports MailBee.SmtpMail

Module Module1
    Sub Main()
        Dim mailer As New Smtp()

        ' To make an exception get thrown, use wrong password.
        mailer.SmtpServers.Add("smtp.here.com", "joe", "bad password")

        ' Prepare a simple e-mail.
        mailer.Message.From = New EmailAddress("joe@here.com")
        mailer.Message.To.Add("bill@there.com")
        mailer.Message.Subject = "Test message"

        Dim result As TestSendResult = TestSendResult.OK
        Try
            ' And try to send it.
            mailer.Send()
        Catch e As MailBeeInvalidArgumentException
            If e.ErrorCode = ErrorCodes.NoSender Then
                result = TestSendResult.NoSender
            Else
                If e.ErrorCode = ErrorCodes.NoRecipients Then
                    result = TestSendResult.NoRecipients
                Else
                    If e.ErrorCode = ErrorCodes.EmptyHostNameForDnsQuery Then
                        result = TestSendResult.NoDomainInRecipientEmail
                    Else
                        result = TestSendResult.UnknownError
                    End If
                End If
            End If
        Catch e As MailBeeSmtpRefusedSenderException
            result = TestSendResult.BadSender
        Catch e As MailBeeSmtpRefusedRecipientException
            result = TestSendResult.BadRecipient
        Catch e As MailBeeSmtpNoAcceptedRecipientsException
            result = TestSendResult.NoAcceptedRecipients
        Catch e As MailBeeLoginNoCredentialsException
            result = TestSendResult.NoCredentials
        Catch e As MailBeeLoginNoSupportedMethodsException
            result = TestSendResult.NoSupportedAuth
        Catch e As MailBeeSmtpLoginBadMethodException
            result = TestSendResult.BadAuthMethod
        Catch e As MailBeeSmtpLoginBadCredentialsException
            result = TestSendResult.BadCredentials
        Catch e As MailBeePop3LoginBadCredentialsException
            result = TestSendResult.BadCredentials
        Catch e As MailBeeSmtpNegativeResponseException
            result = TestSendResult.NegativeSmtpResponse
        Catch e As MailBeePop3NegativeResponseException
            result = TestSendResult.NegativePop3Response
        Catch e As MailBeeDnsNameErrorException
            result = TestSendResult.NoMXRecord
        Catch e As MailBeeDnsProtocolException
            result = TestSendResult.DnsProtocolError
        Catch e As MailBeeConnectionException
            Select Case e.Protocol
                Case TopLevelProtocolType.Smtp
                    result = TestSendResult.SmtpConnectionError
                Case TopLevelProtocolType.Dns
                    result = TestSendResult.DnsConnectionError
                Case TopLevelProtocolType.Pop3
                    result = TestSendResult.Pop3ConnectionError
                Case Else
                    result = TestSendResult.UnknownError
            End Select
        Catch e As MailBeeGetRemoteHostNameException
            Select Case e.HostProtocol
                Case TopLevelProtocolType.Smtp
                    result = TestSendResult.SmtpResolveHostError
                Case TopLevelProtocolType.Pop3
                    result = TestSendResult.Pop3ResolveHostError
                Case Else
                    result = TestSendResult.UnknownError
            End Select
        Catch e As MailBeeException
            result = TestSendResult.UnknownError
        End Try

        ' Display the result of sending attempt.
        ' For instance, if the client successfully connects with
        ' the server but the server says the login or password
        ' is incorrect, will display BadCredentials.
        Console.WriteLine(result.ToString())
    End Sub
End Module

This code above is for demonstration purposes only, you don't need it for testing e-mail addresses as you can use Smtp.TestSend method itself (or EmailAddressValidator component if you need to verify lots of addresses).

You can find more examples of exception processing with MailBee.NET in Exceptions and errors, Get DNS MX records, Send single e-mail asynchronously topics.

Send feedback to AfterLogic


Asynchronous methods of Smtp class

  • Introduction
  • Send single e-mail asynchronously
  • Send multiple e-mails asynchronously

Introduction

Async/await methods of Smtp class allow your application to send e-mails in the background using lightweight I/O worker threads.

Actually, MailBee.NET library also has two sets of async methods: - MethodNameAsync - truly async methods, supported in .NET 4.5 and higher. They are fast, scalable and easy to use with async/await pattern. This tutorial focuses on async/await approach. - BeginMethodName/EndMethodName pairs - they create CPU-bound worker threads. They are not as efficient and now considered deprecated. Use them only if you're bound to an older version of .NET Framework (prior to v4.5). You can find examples of these methods in MailBee.NET library class reference (such as Smtp.BeginSend) and in .NET 2.0+ versions of sample projects (see below).

Note that there is a difference between multi-threaded mode (see Smtp.MaxThreadCount property) and async methods. For instance, multi-threading can be used by a regular synchronous method as long as an async method can send e-mails in a single worker thread (without multi-threading).

An async method just allows your application to proceed immediately with other tasks not waiting for completion of the operation started. However, you cannot start another async operation on the same instance of Smtp class until the previous operation has finished. If you planned to use async operations to send multiple e-mails simultaneously, use jobs instead (see Send bulk e-mail through two SMTP relay servers for increased throughput topic for details).

Besides the samples below, there is a complete WinForms sample project SMTP Demo 2 which sends an e-mail asynchronously and carefully handles exceptions. It's installed with the product among other sample projects in "My Documents\MailBee.NET Objects\Samples\WinForms" folder. The project is available in both C# and VB versions, for .NET 2.0+ (BeginSend-based) and .NET 4.5+ (SendAsync-based).

Another useful sample project there is AddressValidator Demo. Although it's for another MailBee.NET's component EmailAddressValidator, the idea of using async methods and handling exceptions is all the same for all MailBee.NET components.

Send single e-mail asynchronously

This is a simple console sample of sending an e-mail in async way:

  • C#
  • VB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MailBee.SmtpMail;

class Program
{
    private static async Task DoAsyncWork()
    {
        Smtp mailer = new Smtp();

        // Use SMTP relay with authentication.
        mailer.SmtpServers.Add("mail.here.com", "joe", "secret");

        // Set other fields of the e-mail.
        mailer.Message.From.AsString = "Joe D. <joe@here.com>";
        mailer.Message.To.AsString = "jane@example.com";
        mailer.Message.Subject = "Message subject";
        mailer.Message.BodyHtmlText = "<html>Message text</html>";

        // Send asynchronously.
        await mailer.SendAsync();

        Console.WriteLine("The e-mail was sent to: " +
            mailer.GetAcceptedRecipients().ToString());
    }

    static void Main(string[] args)
    {
        DoAsyncWork().Wait();
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports MailBee.SmtpMail

Module Module1
    Private Async Function DoAsyncWork() As Task
        Dim mailer As New Smtp()

        ' Use SMTP relay with authentication.
        mailer.SmtpServers.Add("mail.here.com", "joe", "secret")

        ' Set other fields of the e-mail.
        mailer.Message.From.AsString = "Joe D. <joe@here.com>"
        mailer.Message.To.AsString = "jane@example.com"
        mailer.Message.Subject = "Message subject"
        mailer.Message.BodyHtmlText = "<html>Message text</html>"

        ' Send asynchronously.
        Await mailer.SendAsync()

        Console.WriteLine("The e-mail was sent to: " & mailer.GetAcceptedRecipients().ToString())
    End Function

    Sub Main(args As String())
        DoAsyncWork().Wait()
        Console.WriteLine("Press any key to exit")
        Console.ReadKey()
    End Sub
End Module

We assume MailBee.NET SMTP license key is already set in app.config or Windows registry. See Import namespaces and set license key topic for details.

You can find more complex WinForms sample suitable for use in a desktop application at Smtp.BeginSend method documentation.

Also, as mentioned above, the complete WinForms sample project SMTP Demo 2 which uses Smtp.BeginSend method is installed with the product.

Send multiple e-mails asynchronously

To send more than one e-mail or perform mail merge, use Smtp.BeginSendJobs method. The sample below is an async version of a similar code from Send series of e-mails based on template and database topic:

  • C#
  • VB
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Program
{
    // Create DataTable with some data. In real-world apps,
    // you'll get the data from external sources like SQL query.
    private static DataTable GetData()
    {
        DataTable workTable = new DataTable("customers");

        DataColumn workCol = workTable.Columns.Add("id", typeof(int));
        workCol.AllowDBNull = false;
        workCol.Unique = true;

        workTable.Columns.Add("name", typeof(string));
        workTable.Columns.Add("email", typeof(string));
        workTable.Columns.Add("doc_id", typeof(int));
        workTable.Columns.Add("doc_name", typeof(string));

        // Add two rows to the data source. This way,
        // the mail merge procedure will generate two e-mails.
        DataRow row = workTable.NewRow();
        row["id"] = 1;
        row["name"] = "John Doe";
        row["email"] = "john.doe@company.com";
        row["doc_id"] = 637;
        row["doc_name"] = "annual report.xls";
        workTable.Rows.Add(row);

        row = workTable.NewRow();
        row["id"] = 2;
        row["name"] = "Bob Brown";
        row["email"] = "bob.brown@example.com";
        row["doc_id"] = 2358;
        row["doc_name"] = "agreement draft.pdf";
        workTable.Rows.Add(row);

        return workTable;
    }

    private static async Task DoAsyncWork()
    {
        Smtp mailer = new Smtp();

        // Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret");

        // Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>";
        mailer.Message.Subject = "Information";

        // Set templates for To, body, and attachment.
        mailer.Message.To.AsString = "##name## <##email##>";
        mailer.Message.BodyPlainText = "Attachment for ##name##";
        mailer.Message.Merge.AddAttachmentPattern(@"C:\Docs\##doc_name##");

        // Enqueue mail merge job.
        mailer.AddJob("async mail merge sample", null, null, GetData());

        await mailer.SendJobsAsync();

        Console.WriteLine("The newsletter was sent to: " +
            mailer.JobsSuccessful.Count.ToString() + " addresses");

        Console.WriteLine("The newsletter wasn't sent to: " +
            mailer.JobsFailed.Count.ToString() + " addresses");
    }

    static void Main(string[] args)
    {
        DoAsyncWork().Wait();
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

Imports System.Collections.Generic
Imports System.Data
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports MailBee.SmtpMail

Module Module1
    ' Create DataTable with some data. In real-world apps,
    ' you'll get the data from external sources like SQL query.
    Private Function GetData() As DataTable
        Dim workTable As New DataTable("customers")

        Dim workCol As DataColumn = _
            workTable.Columns.Add("id", GetType(Integer))
        workCol.AllowDBNull = False
        workCol.Unique = True

        workTable.Columns.Add("name", GetType(String))
        workTable.Columns.Add("email", GetType(String))
        workTable.Columns.Add("doc_id", GetType(Integer))
        workTable.Columns.Add("doc_name", GetType(String))

        ' Add two rows to the data source. This way,
        ' the mail merge procedure will generate two e-mails.
        Dim row As DataRow = workTable.NewRow()
        row("id") = 1
        row("name") = "John Doe"
        row("email") = "john.doe@company.com"
        row("doc_id") = 637
        row("doc_name") = "annual report.xls"
        workTable.Rows.Add(row)

        row = workTable.NewRow()
        row("id") = 2
        row("name") = "Bob Brown"
        row("email") = "bob.brown@example.com"
        row("doc_id") = 2358
        row("doc_name") = "agreement draft.pdf"
        workTable.Rows.Add(row)

        Return workTable
    End Function

    Private Async Function DoAsyncWork() As Task
        Dim mailer As New Smtp()

        ' Use SMTP relay server with authentication.
        mailer.SmtpServers.Add("mail.here.com", "jane.doe", "secret")

        ' Set static From and Subject.
        mailer.Message.From.AsString = "Jane Doe <jane.doe@here.com>"
        mailer.Message.Subject = "Information"

        ' Set templates for To, body, and attachment.
        mailer.Message.To.AsString = "##name## <##email##>"
        mailer.Message.BodyPlainText = "Attachment for ##name##"
        mailer.Message.Merge.AddAttachmentPattern("C:\Docs\##doc_name##")

        ' Enqueue mail merge job.
        mailer.AddJob("async mail merge sample", Nothing, Nothing, GetData())

        ' Start mail merge asynchronously.
        Await mailer.SendJobsAsync()

        Console.WriteLine("The newsletter was sent to: " & _
            mailer.JobsSuccessful.Count.ToString() & " addresses")

        Console.WriteLine("The newsletter wasn't sent to: " & _
            mailer.JobsFailed.Count.ToString() & " addresses")
    End Function

    Sub Main(args As String())
        DoAsyncWork().Wait()
        Console.WriteLine("Press any key to exit")
        Console.ReadKey()
    End Sub
End Module

With async methods, you can also use events and all other features which are available for synchronous methods. However, be sure that the main thread of the application (message loop thread) is not blocked. Otherwise, events won't get a chance to get processed and the application will hang.

Async methods available for all synchronous methods (i.e. Smtp.ConnectAsync for Smtp.Connect, Smtp.ExecuteCustomCommandAsync for Smtp.ExecuteCustomCommand, and so on). Their usage is very similar to synchronous methods.

Send feedback to AfterLogic


Log files and memory logs in detail

  • Logger settings and options
  • Synchronize access to log file of multiple instances of Smtp class
  • LogNewEntry event

Logging is essential for trouble-shooting, activity tracking, and audit. MailBee.NET provides extensive (and extensible!) file and memory logging facilities available to your applications.

You can adjust a lot of parameters, control how the log expands and truncate the oldest part, control which messages are added to the log and which are not, add your own messages or redirect the log output to another place like database or Windows Event Log.

Logger settings and options

All e-mail components of MailBee.NET family, including Smtp component, support Log property (e.g. Smtp.Log). This property provides access to an instance of Logger class which controls logging. That's how you can enable logging into a file and clear this file:

  • C#
  • VB
Smtp mailer = new Smtp();

mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

Dim mailer As Smtp = New Smtp()

mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

We assume mailer is an Smtp object instance. In addition to that, for all the samples in this guide we assume MailBee, MailBee.Mime, and MailBee.SmtpMail namespaces are imported and the license key is set. See Import namespaces and set license key topic for details.

Note that your application must have permission to write into the specified location (this especially concerns ASP.NET web applications which are typically run under the context of a user which does not have much permissions to access the filesystem).

If you want to have file logging in place but don't want to have your application crash in case of a logging error (such as a lack of permission), you can tell MailBee.NET to disable logging in case if logging error occurs:

  • C#
  • VB
mailer.Log.DisableOnException = true;

mailer.Log.DisableOnException = True

More elegant solution in case if file logging is not allowed would be using other types of logging, such as memory log:

  • C#
  • VB
mailer.Log.MemoryLog = true;

mailer.Log.MemoryLog = True

To see memory logging in place, check OAuth 2.0 ASP.NET projects installed by MailBee.NET Objects setup in My Documents\MailBee.NET Objects\Samples\ASP.NET folder. C# project is cs_2013_oauth_samples and VB version is vb_2013_oauth_samples.

To read the current contents of the memory log, use Logger.GetMemoryLog method:

  • C#
  • VB
Console.WriteLine(mailer.Log.GetMemoryLog());

Console.WriteLine(mailer.Log.GetMemoryLog())

It's up to you when to display the memory log to the user (or save it somewhere like database). For instance, you can do this at the moment when an exception occurs.

Logger.Clear method can be used to clear the memory log as well as the file log. However, if in case of a file log you usually use this method to tidy up the file so that the log contents of previous sessions of your application would not mess with the new data, in case of a memory log you'll call this method multiple times during a single session of your application to avoid unnecessary growth of the data.

For instance, you may consider clearing the memory log each time your application passes certain key point and the previous log data becomes no longer important or relevant.

MailBee.NET also provides an automatic way to keep the log small (this concerns both file and memory logs). Set Logger.MaxSize property for that. The oldest half of the log history will be automatically removed from the log each time its size is going to exceed the maximum size limit you set. And you'll always have the most recent information there (because the 2nd half of the log with newer items remains).

Another way to keep the log file relatively small is to use Logger.OldFilename property. This lets you still use Logger.MaxSize but instead of deleting the old half of the data the existing log is just renamed. Thus, all the history remains but it becomes split into smaller files.

Logger.KeepLogFileOpen property allows for better performance of file logging. By default, MailBee.NET opens and closes the log file each time a log record is created. This allows for concurrent access to the file, the file is available to other applications, and so on. But in case of frequent write operations, it's slower. Set Logger.KeepLogFileOpen property to true to tell MailBee.NET not to close the log file on each writing.

In the end, when the application is about to be closed (or you just no longer need the log), you should set Logger.KeepLogFileOpen back to false to close the file. You'll also need to disable logging with Logger.Enabled set to false in case if you know that from the current point your application may still perform some actions which could write into the log.

Logger.Format property allows you to tune the format of each log record.

For instance, if you're using Smtp component in multi-threaded mode, adding the current thread and context information makes it easier to read this log then. This code enables the context information in the log by settingLogFormatOptions.AddContextInfo flag:

  • C#
  • VB
mailer.Log.Format = LogFormatOptions.AddContextInfo;

mailer.Log.Format = LogFormatOptions.AddContextInfo

Note that MailBee.NET properly implements the concurrent access of multiple threads to the same log file (in case if all these threads were spawned by the same Smtp class instance). In case if you have multiple instances of Smtp class working simultaneously, you should use Logger.SyncRoot property to synchronize the access. The next topic explains this.

You can also add your own log messages into the log using Logger.WriteLine method. If you need more control (such as avoid having a particular message to be added into the log), use Smtp.LogNewEntry event. To learn more, refer to LogNewEntry event topic.

If the log may contain international characters in a codepage different from the computer's default codepage, you can use Logger.FileEncoding property to set the codepage of the log file.

Logger.HidePasswords property lets you control whether password should be displayed as-is (not secure!) or replaced with asterisks. By default, passwords are not displayed for security reasons.

Log messages (along with error messages) can be customized. For instance, if you want to translate them into your local language or otherwise adjust any or all of them, you can use Resources class for that.

Synchronize access to log file of multiple instances of Smtp class

In case if you're using multiple instances of Smtp class and they all need to write into the same log file, create an object and set Smtp.Log.SyncRoot property of every Smtp instance to this object:

  • C#
  • VB
// Create a synchronization object. It can be of any type.
object syncObject = new object();

Smtp mailer1 = new Smtp();

// mailer1 writes into C:\Temp\log.txt.
mailer1.Log.Enabled = true;
mailer1.Log.Filename = "C:\\Temp\\log.txt";

mailer1.Log.SyncRoot = syncObject;

// mailer2 writes into C:\Temp\log.txt either.
Smtp mailer2 = new Smtp();

mailer2.Log.Enabled = true;
mailer2.Log.Filename = "C:\\Temp\\log.txt";

mailer2.Log.SyncRoot = syncObject;

' Create a synchronization object. It can be of any type.
Dim syncObject As New Object()

Dim mailer1 As New Smtp()

' mailer1 writes into C:\Temp\log.txt.
mailer1.Log.Enabled = True
mailer1.Log.Filename = "C:\Temp\log.txt"

mailer1.Log.SyncRoot = syncObject

' mailer2 writes into C:\Temp\log.txt either.
Dim mailer2 As New Smtp()

mailer2.Log.Enabled = True
mailer2.Log.Filename = "C:\Temp\log.txt"

mailer2.Log.SyncRoot = syncObject

The instances can be of different classes (not only two Smtp instances, like in the sample above, but Smtp and Imap and Pop3 as well). And you can have any number of instances being synchronized.

However, in case if you are willing to use multiple instances of Smtp class to send e-mails concurrently, consider using Smtp.AddJob(string, string, EmailAddressCollection) method and its overloads to feed Smtp component with multiple e-mails to be sent, and set Smtp.MaxThreadCount property to enable multi-threading. See Send bulk e-mail through two SMTP relay servers for increased throughput topic for details.

LogNewEntry event

Smtp component raises Smtp.LogNewEntry event each time a new log record is about to be created and saved into the file or memory log.

This event gives you full control over the logging process. You can:

  • Decide which log messages will be written and which ones will be filtered out. See the example in the event documentation.
  • Alter any incoming log message (e.g. change its text).
  • Write log messages into your own storage (database, XML, log file of your own format, etc).

And you can log your own messages with Logger.WriteLine method. Please note that messages added with that method do not cause Smtp.LogNewEntry event to get raised. Thus, it's safe to call Logger.WriteLine even in Smtp.LogNewEntry event handler, you won't get endless recursion.

This console sample redirects all the logging output into Windows Event Log (which you can then examine with Event Viewer tool):

  • C#
  • VB
using System;
using System.Diagnostics;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    static void OnLogNewEntry(object sender, LogNewEntryEventArgs e)
    {
        // Suppress adding this log entry into the log file.
        e.NewEntry.AddThisEntry = false;

        // The default log entry type.
        EventLogEntryType entryType = EventLogEntryType.Information;

        // Check if the entry is an error or warning.
        if (e.NewEntry.MessageType == LogMessageType.Info)
        {
            if (e.NewEntry.MessageText.StartsWith("Error"))
            {
                entryType = EventLogEntryType.Error;
            }
            else if (e.NewEntry.MessageText.StartsWith("Warning"))
            {
                entryType = EventLogEntryType.Warning;
            }
        }

        // Save the entry in Windows Event Log.
        EventLog.WriteEntry("Application", e.NewEntry.MessageText, entryType);
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Attach event handler and enable logging.
        mailer.LogNewEntry += new LogNewEntryEventHandler(OnLogNewEntry);
        mailer.Log.Enabled = true;

        // To demonstrate Error entry in Event Log, use wrong password.
        mailer.SmtpServers.Add("mail.provider.com", "joe", "bad password");

        // Send a simple e-mail.
        mailer.Message.From = new EmailAddress("joe@here.com");
        mailer.Message.To.Add("bill@there.com");
        mailer.Message.Subject = "Test message";
        mailer.Send();
    }
}

Imports System
Imports System.Diagnostics
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Module Module1
    Sub OnLogNewEntry(ByVal sender As Object, ByVal e As LogNewEntryEventArgs)
        ' Suppress adding this log entry into the log file.
        e.NewEntry.AddThisEntry = False

        ' The default log entry type.
        Dim entryType As EventLogEntryType = EventLogEntryType.Information

        ' Check if the entry is an error or warning.
        If e.NewEntry.MessageType = LogMessageType.Info Then
            If e.NewEntry.MessageText.StartsWith("Error") Then
                entryType = EventLogEntryType.Error
            Else
                If e.NewEntry.MessageText.StartsWith("Warning") Then
                    entryType = EventLogEntryType.Warning
                End If
            End If
        End If

        ' Save the entry in Windows Event Log.
        EventLog.WriteEntry("Application", e.NewEntry.MessageText, entryType)
    End Sub

    Sub Main()
        Dim mailer As New Smtp()

        ' Attach event handler and enable logging.
        AddHandler mailer.LogNewEntry, AddressOf OnLogNewEntry
        mailer.Log.Enabled = True

        ' To demonstrate Error entry in Event Log, use wrong password.
        mailer.SmtpServers.Add("mail.provider.com", "joe", "bad password")

        ' Send a simple e-mail.
        mailer.Message.From = New EmailAddress("joe@here.com")
        mailer.Message.To.Add("bill@there.com")
        mailer.Message.Subject = "Test message"
        mailer.Send()
    End Sub
End Module

Of course, real-world applications should not write so many records into Windows Event Log (you should log only error messages or very important events).

Note that each record you added in Windows Event Log might have a warning like "The description for Event ID ( 0 ) in Source ( Application ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer."

To avoid this, you'll need to prepare an event source before writing into Windows Event Log (such as with EventLog.CreateEventSource method).

Send feedback to AfterLogic


Verify e-mail addresses with Address Validator

  • Introduction
  • Import namespaces and set license key
  • Usage basics
  • Understanding validation levels
  • Examining the results
  • Getting data from SqlDataReader or any other IDataReader
  • DNS servers, caching, local endpoints, SMTP settings
  • WinForms sample project

Introduction

EmailAddressValidator component lets you verify e-mail addresses for correct syntax and, optionally, for existence. The component can check both single addresses and bulks of hundreds of thousands.

Address Validator supports multi-threading (up to 60 threads) which greatly improves performance and enables up to 100.000 address checks per hour in the most accurate validation mode, SendAttempt. You can enable it with setting EmailAddressValidator.MaxThreadCount property. Another important performance optimization, DNS caching, is also supported, and enabled by default. As for memory usage, it stays stable and won't increase even if you run the check for many hours or even days validating millions of addresses.

In .NET Core and UWP editions, only single addresses can be checked at a time. Bulk operations are not supported yet.

The following validation levels can be set with EmailAddressValidator.ValidationLevel property (defined by AddressValidationLevel enum):

  • RegexCheck - syntax check of the e-mail address string.
  • DnsQuery - DNS MX lookup for domain part of the the e-mail address string, to find out the SMTP MX host responsible for e-mail delivery to the domain.
  • SmtpConnection - test connection to the SMTP MX host.
  • SendAttempt - test connection, sending EHLO/HELO and MAIL FROM commands, and submitting the given e-mail address string in RCPT TO command. This mimics normal send attempt, just without sending actual message data. If the server accepts the recipient and says "Yes, I'm ready to receive message data", the component just resets the connection and disconnects, reporting that the address is correct.

To start with Address Validator, you need to add a reference to MailBee.NET.dll, import namespaces and unlock the component.

Import namespaces and set license key

To learn how to add a reference to MailBee.NET.dll (or MailBee.NET.45.dll in .NET 4.5+ case), see similar topic in MailBee.NET SMTP guide.

Then, import the required namespaces at the top of your code file:

  • C#
  • VB
using MailBee;
using MailBee.AddressCheck;
using MailBee.SmtpMail;

Imports MailBee
Imports MailBee.AddressCheck
Imports MailBee.SmtpMail

Note that MailBee and MailBee.SmtpMail namespaces do not directly belong to Address Validator but the classes in these namespaces are commonly used with Address Validator classes.

After importing namespaces, unlock the component with your trial or permanent license key. The key can be specified in the code, in app.config/web.config, in the registry.

Option A - specify license key directly in code

Before the first use and creating any instances of EmailAddressValidator class, set the static MailBee.Global.LicenseKey property to assign the license key (if you haven't done this before). It's assumed you've already imported MailBee.AddressCheck namespace with using (C#) or Imports (VB) directives.

  • C#
  • VB
MailBee.Global.LicenseKey = "MN110-0123456789ABCDEF-0123";

MailBee.Global.LicenseKey = "MN110-0123456789ABCDEF-0123"

You can also create and unlock an instance of EmailAddressValidator class, passing the license key as a parameter of EmailAddressValidator(string) constructor. Again, it's assumed you've already imported MailBee.AddressCheck namespace.

  • C#
  • VB
EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

Dim valid As New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

Option B - put license key in app.config or web.config

Alternatively, in app.config locate <appSettings> entry in <configuration> section (if it's not there, create it), and add MailBee.NET license key as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="MailBee.Global.LicenseKey" value="MN110-0123456789ABCDEF-0123"/>
  </appSettings>
</configuration>

If <appSettings> originally looked as <appSettings/> (self-closing tag syntax), you'll need to unfold it to <appSettings></appSettings> so that you could insert <add key .../> there.

The above also applies to ASP.NET application and web.config.

If you do not yet have app.config or web.config, see Import namespaces and set license key in MailBee.NET SMTP guide on how to add it.

You can also specify the key in machine.config file. This will enable access to the license key to all applications on the computer so that there will be no need to specify the license key in each application separately. For instance, this is the preferred way if you a hosting provider willing to let your hosting clients create and run applications which use MailBee.NET without disclosing your license key to them.

Usage basics

The topics below assume you have already referenced MailBee.NET assembly. Code snippets which are not complete programs assume you have imported MailBee and MailBee.AddressCheck namespace, unlocked the license and created a new EmailAddressValidator instance named valid.

To verify a single e-mail address, use Verify(string) overload.

By default, EmailAddressValidator.ValidationLevel is already SendAttempt (the most advanced e-mail address check available). Therefore we don't need to explicitly set this mode to perform all the checks possible against a single e-mail address.

  • C#
  • VB
using System;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN100-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        AddressValidationLevel result = valid.Verify("jdoe@company.com");
        Console.WriteLine(result.ToString());
    }
}

Imports MailBee
Imports MailBee.AddressCheck

Class Program
    Shared Sub Main()
        Dim valid As New EmailAddressValidator("MN100-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        Dim result As AddressValidationLevel = valid.Verify("jdoe@company.com")
        Console.WriteLine(result.ToString())
    End Sub
End Class

To verify a bulk of addresses, subscribe to Verified event, start verification with Verify(DataTable, string) or Verify(string[]) overload, and examine event arguments (the event raises each time an address is verified, with either positive or negative result).

  • C#
  • VB
using System;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        Console.WriteLine("*** Verified ***");
        Console.WriteLine("Email: " + e.Email);
        Console.WriteLine("Result: " + e.Result.ToString());
        if (e.Reason != null)
        {
            Console.WriteLine("Reason: " + e.Reason.Message);
        }
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN100-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to event.
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // Populate an array with some e-mails. You can also use DataTable as a source.
        string[] emails = new string[] { "jdoe@company.com", "bob@example.com", "alice@domain.com" };

        // Run the verification in single-threaded mode.
        valid.Verify(emails);
    }
}

Imports MailBee
Imports MailBee.AddressCheck

Class Program
    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Console.WriteLine("*** Verified ***")
        Console.WriteLine(("Email: " & e.Email))
        Console.WriteLine(("Result: " & e.Result.ToString))
        If (Not (e.Reason) Is Nothing) Then
            Console.WriteLine(("Reason: " & e.Reason.Message))
        End If
        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim valid As EmailAddressValidator = New EmailAddressValidator("MN100-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to event.
        AddHandler valid.Verified, AddressOf valid_Verified

        ' Populate an array with some e-mails. You can also use DataTable as a source.
        Dim emails() As String = New String() {"jdoe@company.com", "bob@example.com", "alice@domain.com"}

        ' Run the verification in single-threaded mode.
        valid.Verify(emails)
    End Sub
End Class

The previous sample checked addresses one by one. Now let's enable multi-threading to make things faster.

The next sample processes 10 addresses instead of 3, but completes faster. Also, it demonstrates using a DataTable rather than a string array. Actually, in this sample we build this DataTable from a string array but you can populate it from elsewhere, such as database.

Although the sample below uses multi-threading, it does not do any thread synchronizing in Verified event handler (despite the fact that in multi-threaded mode this event can occur simultaneously on many threads). This is because we're not using any thread-unsafe things in event handlers. But most .NET classes are thread-unsafe. If you need to use thread-unsafe class there, see Verify sample on how to synchronize threads.

Note that if you're using Visual Studio 2010 or earlier, you may be experiencing sudden lockups when debugging a multi-threaded application. Upgrading to Visual Studio 2012 or newer solves the issue. SeeEmailAddressValidator.MaxThreadCount topic for other options.

  • C#
  • VB
using System;
using System.Data;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        Console.WriteLine("*** Verified ***");
        Console.WriteLine("Email: " + e.Email);
        Console.WriteLine("Result: " + e.Result.ToString());
        if (e.Reason != null)
        {
            Console.WriteLine("Reason: " + e.Reason.Message);
        }
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN100-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        // Since this sample is multi-threaded, we also set AddContextInfo option
        // to make it easier analyze the log (each record will be tagged with a thread ID).
        valid.Log.Enabled = true;
        valid.Log.Format = LogFormatOptions.AddContextInfo;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to event.
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // In this sample, we'll build DataTable manually from a string array.
        string[] emails = new string[10];
        for (int i = 0; i < emails.Length; i++)
        {
            // Make user0@domain0.com, user1@domain1.com, ..., user9@domain9.com.
            emails[i] = string.Format("user{0}@domain{0}.com", i.ToString());
        }

        // In real apps, you'll get data from database. For now, populate data from
        // string array by putting all the data into a table with one column "email".
        DataTable data = valid.ArrayToDataTable(emails);

        // If you comment the next code line out, the whole thing will be dead slow.
        // Checking each address usually involves a test connection, and the time required to understand
        // that there is no living host at the other side (for e-mail addresses with non-existent domains)
        // may exceed 20 seconds. For 10 addresses in this sample, if run one-by-one, this will take minutes.
        // Multi-threading, however, will make all the e-mail addresses in list list be checked
        // simultaneously (MailBee can do up to 60 of simultaneous queries). The total time won't exceed
        // the time required for a single address be checked (which maxes out at 20 seconds or so).
        valid.MaxThreadCount = -1;

        // Run the verification in multi-threaded mode.
        valid.Verify(data, "email");
    }
}

Imports System.Data
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Console.WriteLine("*** Verified ***")
        Console.WriteLine("Email: " & e.Email)
        Console.WriteLine("Result: " & e.Result.ToString())
        If e.Reason IsNot Nothing Then
            Console.WriteLine("Reason: " & e.Reason.Message)
        End If
        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args As String())
        Dim valid As New EmailAddressValidator("MN100-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        ' Since this sample is multi-threaded, we also set AddContextInfo option
        ' to make it easier analyze the log (each record will be tagged with a thread ID).
        valid.Log.Enabled = True
        valid.Log.Format = LogFormatOptions.AddContextInfo
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to event.
        AddHandler valid.Verified, AddressOf valid_Verified

        ' In this sample, we'll build DataTable manually from a string array.
        Dim emails As String() = New String(9) {}
        For i As Integer = 0 To emails.Length - 1
            ' Make user0@domain0.com, user1@domain1.com, ..., user9@domain9.com.
            emails(i) = String.Format("user{0}@domain{0}.com", i.ToString())
        Next

        ' In real apps, you'll get data from database. For now, populate data from
        ' string array by putting all the data into a table with one column "email".
        Dim data As DataTable = valid.ArrayToDataTable(emails)

        ' If you comment the next code line out, the whole thing will be dead slow.
        ' Checking each address usually involves a test connection, and the time required to understand
        ' that there is no living host at the other side (for e-mail addresses with non-existent domains)
        ' may exceed 20 seconds. For 10 addresses in this sample, if run one-by-one, this will take minutes.
        ' Multi-threading, however, will make all the e-mail addresses in list list be checked
        ' simultaneously (MailBee can do up to 60 of simultaneous queries). The total time won't exceed
        ' the time required for a single address be checked (which maxes out at 20 seconds or so).
        valid.MaxThreadCount = -1

        ' Run the verification in multi-threaded mode.
        valid.Verify(data, "email")
    End Sub
End Class

As all the addresses in these samples are fake, the verification of them all will deliver negative results (not AddressValidationLevel.OK).

In general case, however, If the result of an e-mail address verification is negative, you should analyze it in more detail. This is because the failed check does not necessarily indicate that the e-mail address is invalid, see Examining the results to see why this happens and what you can do with this.

All the samples above used the maximum (and default) validation level available, AddressValidationLevel.SendAttempt. In real apps, it's not always the best choice, especially if for some reason you cannot run the check on a machine which has a public IP address with a properly configured rDNS record (and, ideally, MX and SPF), running SMTP service, and so on. Read the next topic to learn which validation method better suits your case.

Understanding validation levels

Each next level includes all the previous levels. The higher level is, the more accurate check is. However, for SmtpConnection and SendAttempt levels be sure that the host from which you're running Address Validator has a public IP address with a valid reverse DNS record, not black-listed by popular RBLs and so on. Otherwise, many MX hosts will reject submissions of e-mail addresses even if they are correct. This is because the receiving host may think you're a spammer willing to send spam to its users. Read below for more details.

RegexCheck

Syntax check is the basic level. It does regular expression test to check if the address is at least syntactically correct. If required, the regular expression can be adjusted (EmailAddressValidator.RegexPattern property). It's very fast as no network connections are made, and very simple.

On the one hand, this check filters out only certainly invalid addresses which have broken syntax, no checking of actual existence of the domain or the account is made - this is drawback. On the other hand, if this check says the address is invalid - it's invalid (at least if the regular expression stays the same). It won't change in two hours or tomorrow. It does not depend on anything. More advanced validation levels are not that simple and may require multiple checks to be made in different days to prove that the address is really non-existent.

DnsQuery

DNS MX lookup, in addition to syntax check, also extracts the domain part from the e-mail address string and makes a query to the DNS servers listed in EmailAddressValidator.DnsServers collection, to find out which SMTP MX hosts accept e-mail for that domain. This lets MailBee find out that the given domain actually exists and can, at least in theory, accept e-mail. Still, there is no guarantee that the SMTP MX hosts found are actually online. Neither it's known if the account part of the e-mail address denotes the valid mailbox on that server.

The DNS MX lookup check involves making network queries, and thus heavily utilizes network resources. For better performance and reliability, you can specify multiple servers in EmailAddressValidator.DnsServers, MailBee will automatically distribute load between them. Also, MailBee extensively uses DNS caching to reduce load on DNS servers (because many domains may appear in e-mail address many times, like gmail.com, yahoo.com, and others). If you need to turn DNS caching off for some reason, use MailBee.DnsMX.DnsCache.Enabled property.

In many cases, DNS MX lookup represents reasonable trade between the rate of false positives and false negatives. On the one hand, this method cannot actually tell if MX hosts are dead or alive or if the given account actually exists. On the other hand, this method won't tell you that some address is invalid just because it's SMTP MX host is temporarily down or currently rejects connections from you as you somehow got into some RBL blacklist.

In terms of reproducibility, DNS MX lookup is pretty close to syntax check - the same e-mail address will likely deliver the same result, no matter what day you're running the test. This assumes, however, the DNS servers being used are properly configured and do not report false data to the application.

SmtpConnection

In addition to DNS MX lookup, this method will also do a connection to port 25 of the SMTP MX server found during the DNS MX lookup. As a domain can have more than one MX servers with different priorities, MailBee can try them accordingly their priorities in case if higher-priority servers seem to be down.

A test connection does the following: connects to the server, receives the initial response, executes EHLO command (HELO for very old servers which don't understand EHLO), then executes QUIT command to close the connection. It's recommended to set the appropriate domain name MailBee will pass as EHLO argument. Use the external domain name of the machine running MailBee. For instance, if the check is being run on afterlogic.com server, set EmailAddressValidator.HelloDomain to "afterlogic.com" value.

If the test connection succeeds, this means the host can actually accept e-mail for the given domain. This ensures the corresponding SMTP MX server is actually alive. However, if your IP address is in the black-list of the given server, the connection may not go through and MailBee will report the address as "failed".

This method requires more network resources than DNS MX query check, and also your firewall and your ISP's firewall must pass outgoing connections to port 25. Many ISPs block this, so make sure it's not an issue for you.

Also, it's recommended to have a valid PTR (rDNS) record on your IP address (having MX and SPF records would be another plus), and have a working SMTP server there (some hosts only allow connections from hosts which are SMTP servers themselves). It's not necessary to have the SMTP server at the same computer. They just should have the same IP address (for instance, an SMTP server is an Internet gate either while MailBee machine is in internal network and "sees" Internet through this gate). Other working scenarios are possible too. The main idea is to make other servers think you're one of them, not just one of home computers infected by a virus and sending spam, with no public IP address, PTR record, MX record, or SMTP service running.

Even if the connection succeeds, there is no guarantee the SMTP MX host would accept e-mail for the given account name. At this point, all we know is that the e-mail address syntax is correct, the domain is valid, the SMTP MX host for this domain is online.

SendAttempt

This method not just connects to the SMTP MX host and sends QUIT like the previous method does. It also submits the sender in MAIL FROM command and the e-mail address being checked, in RCPT TO command.

As a sender, MailBee uses user@domain.com string by default but you can change it to anything you want with EmailAddressValidator.MailFrom property. Recommend setting is an e-mail address which exists on your SMTP server (which should run at the same IP address as external IP address of MailBee machine). Or, at least the domain part of should be valid. This way the receiving host will see that the sending host does not use sender's e-mail which does not belong to its domain. In case if your network does not have an SMTP server, the e-mail address checking quality will degrade a bit due to a number of false negatives.

Shortly, if you don't have an SMTP service, some hosts will tell that the e-mail address being submitted is invalid even if it's OK.

Once MailBee did RCPT TO command passing the e-mail address being verified as a parameter and the server replied OK, MailBee sends RSET command to reset the connection (because otherwise the server would wait for the DATA command and message data to be submitted). Then, MailBee sends QUIT and this closes the connection. The e-mail address is considered to be valid.

Still, false positives may exist (in addition to false negatives explained earlier). Many servers say that an address is correct even if it's not. They just accept any address and say OK (this way spammers cannot find out which addresses exist or not by trying all popular names and checking what server reply to each name).

With such servers, if the address is incorrect and you send an e-mail there. you'll get bounce later (maybe, in a minute, or in a few hours). There is no workaround unless to monitor your mailbox for bounces, parse them, and remove invalid address from your database (see DeliveryStatusParser class for this purpose). However, preliminary check for invalid addresses with Address Validator greatly reduces the amount of bounces as many bad address are still filtered out before you start bulk sending.

Examining the results

If for certain e-mail address the result was not AddressValidationLevel.OK, this alone means nothing. As explained above, there can be false negatives. This applies to AddressValidationLevel.SmtpConnection andAddressValidationLevel.SendAttempt modes.

You should not just check the return value for OK, you should analyze the result in a complex pattern:

  • RegexCheck - the e-mail address is really bad, no doubts.
  • DnsQuery - DNS MX lookup failed. Usually, means the address is wrong, but if your network had DNS issue… A safer way is to mark the address in the database as suspicious. If next time (perhaps, in a few days), the same error occurs again, you may remove it from the database. Also, if suddenly all addresses started to appear invalid with this error, this certainly means something is wrong with DNS.
  • SmtpConnection - often indicates the MX host is temporarily down. You should not remove the address by a single occurrence of this error (use the pattern from the above). Also, if it occurs for all the addresses, you have port 25 blocked somewhere. For bulk operations, you can also check Reason property of the Verified event arguments or the log file to check what exactly happened.
  • SendAttempt - often indicates greylisting (a popular spam prevention technique when the server always says something like "try again later" on the first sending attempt but remembers your IP address for some time). Examining Reason property may help to find if this is the case. If it's indeed the case, you may, literally, run the check for the addresses with this status again, such as in an hour.

The sample below shows the idea how to address some of these issues. We run the check 3 times. Each time, we refine the results determined during previous checks. Thus, if the server or domain for some e-mail address was not not available on certain attempt, we mark the address as "suspicious", and during the next check we either prove this (and mark the address as Bad) or restore it to Good.

We have to kinds of "Suspicious" statuses: ProbablyBad status for DNS errors and SMTP connection failures, and transient SMTP errors for which we set the status to "greylisting is possibly in action" (ProbablyGreylisted). If ProbablyBad repeats on next attempt, we mark this address as Bad, if ProbablyGreylisted repeats - mark it as ProbablyBad.

Note that in real apps the time interval between checks should be at least one day. If the server accepting e-mail for the given e-mail address was offline during the current check, it won't likely go back online in a few seconds. Should you make a second attempt immediately after the first one, you'd probably get the same results. BUT! If the server reported a transient error (ProbablyGreylisted), this often indicates greylisting. In this case, the second attempt for ProbablyGreylisted addresses should occur earlier, within an hour (10-15 minutes would be great). If the second attempt failed too, it wasn't greylisting but rather a real problem with the server, and we should try again next day or so.

  • C#
  • VB
using System;
using System.Data;
using MailBee;
using MailBee.AddressCheck;
using MailBee.SmtpMail;

class Program
{
    // This enum defines the status of an e-mail address in our data table.
    enum AddressStatus
    {
        Good = 0,
        ProbablyGreylisted = 1,
        ProbablyBad = 2,
        Bad = 3
    }

    const string EmailColumn = "email";
    const string StatusColumn = "status";

    // In real apps, you'll get this data table from your database.
    // In the sample, we build it directly in the code.
    private static DataTable GetDataTable()
    {
        DataTable workTable = new DataTable();
        workTable.Columns.Add(EmailColumn, typeof(string));
        workTable.Columns.Add(StatusColumn, typeof(AddressStatus));

        // Populate the data table with several addresses (some are surely wrong)
        // and initially mark them Good. We believe they are good until proven otherwise.
        string[] emails = new string[] { "jdoe@company.com", "no.dot.in@domain",
            "bob@example.com", "user@nonexistent.domain", "alice@domain.com" };
        foreach (string email in emails)
        {
            DataRow row = workTable.NewRow();
            row[EmailColumn] = email;
            row[StatusColumn] = AddressStatus.Good;
            workTable.Rows.Add(row);
        }

        return workTable;
    }

    // This method executes when the e-mail address is about to be checked.
    private static void valid_Verifying(object sender, VerifyingEventArgs e)
    {
        // In this sample, we won't check addresses which have already proven to be bad.
        // You can use the same idea to skip any other addresses you wish, such as
        // to implement black-listing or white-listing.
        if ((AddressStatus)e.Row[StatusColumn] == AddressStatus.Bad)
        {
            e.VerifyIt = false;
        }
    }

    // This method executes after the e-mail address was checked.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        // Nothing new in this part.
        Console.WriteLine("*** Verified ***");
        Console.WriteLine("Email: " + e.Email);
        Console.WriteLine("Result: " + e.Result.ToString());
        if (e.Reason != null)
        {
            Console.WriteLine("Reason: " + e.Reason.Message);
        }

        // Interesting part starts here.
        AddressStatus previousStatus = (AddressStatus)e.Row[StatusColumn];
        AddressStatus newStatus = previousStatus;

        switch (e.Result)
        {
            case AddressValidationLevel.OK:
                // If the address was Good, it stays Good. If it was Probably"Something",
                // it has now cleared our suspicions, congrats!
                if (previousStatus != AddressStatus.Good)
                {
                    newStatus = AddressStatus.Good;
                }
                break;
            case AddressValidationLevel.RegexCheck:
                // If the address failed regex check, it just had bad syntax.
                // Does not make sense to give it a second chance.
                newStatus = AddressStatus.Bad;
                break;
            case AddressValidationLevel.DnsQuery:
                if (previousStatus == AddressStatus.Good ||
                    previousStatus == AddressStatus.ProbablyGreylisted)
                {
                    // Give the address which was good before, a second chance. We also do this for
                    // "probably greylisted" addresses because from DNS MX point of view they are good
                    // (valid MX host, running SMTP service) and DNS error is something new for them,
                    // so there is a chance it's a temporary issue.
                    newStatus = AddressStatus.ProbablyBad;
                }
                else
                {
                    // The address had already been given second chance before and thus had ProbablyBad status.
                    // Execute it. No mercy this time. But in real apps you better take this decision on at least
                    // 3rd failed attempt, and at least 3 days should pass since the first attempt. Give
                    // the e-mail service of the recipient some time to fix the issues they may be experiencing,
                    // or the mailbox was just full and the user had no time to get some free space there.
                    newStatus = AddressStatus.Bad;
                }
                break;
            case AddressValidationLevel.SmtpConnection:
                // In this sample, we take the same decisions in SmtpConnection case like we do for DnsQuery.
                // This is because the reasons are pretty similar in most cases. The domain could go down due
                // to the name server issue, the same can happen with a SMTP MX e-mail server. This differs
                // from the situation when the SMTP MX server does respond but says "No" (see below).
                if (previousStatus == AddressStatus.Good ||
                    previousStatus == AddressStatus.ProbablyGreylisted)
                {
                    newStatus = AddressStatus.ProbablyBad;
                }
                else
                {
                    newStatus = AddressStatus.Bad;
                }
                break;
            case AddressValidationLevel.SendAttempt:
                // Did the connection simply break or did the server actually say "No"?
                // Connection break may indicate a temporary issue with the SMTP MX server.
                IMailBeeNegativeSmtpResponseException negativeResponseEx;
                negativeResponseEx = e.Reason as IMailBeeNegativeSmtpResponseException;
                bool isNegativeReply = (negativeResponseEx != null);

                // For No errors, we need to make sure this is the final verdict of the SMTP MX server.
                // If the error is transient rather than the final verdict, it leaves us a second chance to try.
                if (isNegativeReply && !negativeResponseEx.IsTransientError)
                {
                    // The SMTP MX server which is charge for the given e-mail address said us strict "No".
                    // We don't know the exact reason (maybe, your IP address is blacklisted by some RBLs),
                    // but under the current circumstances the given e-mail address cannot receive e-mail from us.
                    newStatus = AddressStatus.Bad;
                    break;
                }

                // At this point, we have only temporary SMTP MX errors left, such as broken connections or
                // greylisting ("Try again later" responses). For such errors, giving second chances does make sense.

                if (previousStatus == AddressStatus.Good)
                {
                    if (isNegativeReply)
                    {
                        // The server replied "No, but try again later". It's legit thing, so there is a good
                        // chance there IS a real e-mail account under the given name there.
                        newStatus = AddressStatus.ProbablyGreylisted;
                    }
                    else
                    {
                        // The server suddenly broke the connection. Give it one second chance, but no more.
                        newStatus = AddressStatus.ProbablyBad;
                    }
                }
                else if (previousStatus == AddressStatus.ProbablyGreylisted)
                {
                    // The server said "Try again later" or broke the connection?
                    if (isNegativeReply)
                    {
                        // Greylisting returned the same result second time in a row. Maybe, it wasn't greylisting
                        // at all? Give this e-mail address one more chance, but our patience is nearly over.
                        newStatus = AddressStatus.ProbablyBad;
                    }
                    else
                    {
                        // Well, "If isNegativeReply" is actually redundant here. If the server broke the connection
                        // instead of saying "Better luck next time", our assumption remains the same. There is
                        // still a small chance that the server will accept the given address next time, so give it
                        // one more shot to try. In your apps, however, you may consider different logic here.
                        newStatus = AddressStatus.ProbablyBad;
                    }
                }
                else
                {
                    // We're tired of all that "Try again later" occurring 3 times in a row and repetitive
                    // disconnects during send attempts. Consider the e-mail address dead.
                    newStatus = AddressStatus.Bad;
                }
                break;
        }

        if (previousStatus != newStatus)
        {
            // Update the status in the data table. You may also need to do Commit, Update
            // or whatever is required to apply the changes to your database.
            e.Row[StatusColumn] = newStatus;
        }

        Console.WriteLine();
    }

    // Dumps the contents of the data table to console. We use it how the statuses change
    // over the time with making new attempts to verify the corresponding e-mails addresses.
    private static void DisplayDataTable(DataTable data)
    {
        foreach (DataRow row in data.Rows)
        {
            Console.WriteLine(string.Format("{0}={1}",
                row[EmailColumn].ToString(), ((AddressStatus)row[StatusColumn]).ToString()));
        }
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        // Common initialization, like in previous samples.
        EmailAddressValidator valid = new EmailAddressValidator("MN100-0123456789ABCDEF-0123");
        valid.DnsServers.Autodetect();
        valid.Log.Enabled = true;
        valid.Log.Format = LogFormatOptions.AddContextInfo;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();
        valid.Verifying += new VerifyingEventHandler(valid_Verifying);
        valid.Verified += new VerifiedEventHandler(valid_Verified);
        valid.MaxThreadCount = -1;

        DataTable data = GetDataTable();

        valid.Verify(data, EmailColumn);
        DisplayDataTable(data);

        Console.WriteLine("Press any key to continue to the 2nd run");
        Console.ReadKey(true);

        valid.Verify(data, EmailColumn);
        DisplayDataTable(data);

        Console.WriteLine("Press any key to continue to the 3rd run");
        Console.ReadKey(true);

        valid.Verify(data, EmailColumn);
        DisplayDataTable(data);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey(true);
    }
}

Imports System.Data
Imports MailBee
Imports MailBee.AddressCheck
Imports MailBee.SmtpMail

Class Program
    ' This enum defines the status of an e-mail address in our data table.
    Private Enum AddressStatus
        Good = 0
        ProbablyGreylisted = 1
        ProbablyBad = 2
        Bad = 3
    End Enum

    Const EmailColumn As String = "email"
    Const StatusColumn As String = "status"

    ' In real apps, you'll get this data table from your database.
    ' In the sample, we build it directly in the code.
    Private Shared Function GetDataTable() As DataTable
        Dim workTable As New DataTable()
        workTable.Columns.Add(EmailColumn, GetType(String))
        workTable.Columns.Add(StatusColumn, GetType(AddressStatus))

        ' Populate the data table with several addresses (some are surely wrong)
        ' and initially mark them Good. We believe they are good until proven otherwise.
        Dim emails As String() = New String() {"jdoe@company.com", "no.dot.in@domain", _
         "bob@example.com", "user@nonexistent.domain", "alice@domain.com"}
        For Each email As String In emails
            Dim row As DataRow = workTable.NewRow()
            row(EmailColumn) = email
            row(StatusColumn) = AddressStatus.Good
            workTable.Rows.Add(row)
        Next

        Return workTable
    End Function

    ' This method executes when the e-mail address is about to be checked.
    Private Shared Sub valid_Verifying(ByVal sender As Object, ByVal e As VerifyingEventArgs)
        ' In this sample, we won't check addresses which have already proven to be bad.
        ' You can use the same idea to skip any other addresses you wish, such as
        ' to implement black-listing or white-listing.
        If CType(e.Row(StatusColumn), AddressStatus) = AddressStatus.Bad Then
            e.VerifyIt = False
        End If
    End Sub

    ' This method executes after the e-mail address was checked.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        ' Nothing new in this part.
        Console.WriteLine("*** Verified ***")
        Console.WriteLine("Email: " & e.Email)
        Console.WriteLine("Result: " & e.Result.ToString())
        If e.Reason IsNot Nothing Then
            Console.WriteLine("Reason: " & e.Reason.Message)
        End If

        ' Interesting part starts here.
        Dim previousStatus As AddressStatus = CType(e.Row(StatusColumn), AddressStatus)
        Dim newStatus As AddressStatus = previousStatus

        Select Case e.Result
            Case AddressValidationLevel.OK
                ' If the address was Good, it stays Good. If it was Probably"Something",
                ' it has now cleared our suspicions, congrats!
                If previousStatus <> AddressStatus.Good Then
                    newStatus = AddressStatus.Good
                End If
                Exit Select
            Case AddressValidationLevel.RegexCheck
                ' If the address failed regex check, it just had bad syntax.
                ' Does not make sense to give it a second chance.
                newStatus = AddressStatus.Bad
                Exit Select
            Case AddressValidationLevel.DnsQuery
                If previousStatus = AddressStatus.Good OrElse previousStatus = AddressStatus.ProbablyGreylisted Then
                    ' Give the address which was good before, a second chance. We also do this for
                    ' "probably greylisted" addresses because from DNS MX point of view they are good
                    ' (valid MX host, running SMTP service) and DNS error is something new for them,
                    ' so there is a chance it's a temporary issue.
                    newStatus = AddressStatus.ProbablyBad
                Else
                    ' The address had already been given second chance before and thus had ProbablyBad status.
                    ' Execute it. No mercy this time. But in real apps you better take this decision on at least
                    ' 3rd failed attempt, and at least 3 days should pass since the first attempt. Give
                    ' the e-mail service of the recipient some time to fix the issues they may be experiencing,
                    ' or the mailbox was just full and the user had no time to get some free space there.
                    newStatus = AddressStatus.Bad
                End If
                Exit Select
            Case AddressValidationLevel.SmtpConnection
                ' In this sample, we take the same decisions in SmtpConnection case like we do for DnsQuery.
                ' This is because the reasons are pretty similar in most cases. The domain could go down due
                ' to the name server issue, the same can happen with a SMTP MX e-mail server. This differs
                ' from the situation when the SMTP MX server does respond but says "No" (see below).
                If previousStatus = AddressStatus.Good OrElse previousStatus = AddressStatus.ProbablyGreylisted Then
                    newStatus = AddressStatus.ProbablyBad
                Else
                    newStatus = AddressStatus.Bad
                End If
                Exit Select
            Case AddressValidationLevel.SendAttempt
                ' Did the connection simply break or did the server actually say "No"?
                ' Connection break may indicate a temporary issue with the SMTP MX server.
                Dim negativeResponseEx As IMailBeeNegativeSmtpResponseException
                negativeResponseEx = TryCast(e.Reason, IMailBeeNegativeSmtpResponseException)
                Dim isNegativeReply As Boolean = (negativeResponseEx IsNot Nothing)

                ' For No errors, we need to make sure this is the final verdict of the SMTP MX server.
                ' If the error is transient rather than the final verdict, it leaves us a second chance to try.
                If isNegativeReply AndAlso Not negativeResponseEx.IsTransientError Then
                    ' The SMTP MX server which is charge for the given e-mail address said us strict "No".
                    ' We don't know the exact reason (maybe, your IP address is blacklisted by some RBLs),
                    ' but under the current circumstances the given e-mail address cannot receive e-mail from us.
                    newStatus = AddressStatus.Bad
                    Exit Select
                End If

                ' At this point, we have only temporary SMTP MX errors left, such as broken connections or
                ' greylisting ("Try again later" responses). For such errors, giving second chances does make sense.

                If previousStatus = AddressStatus.Good Then
                    If isNegativeReply Then
                        ' The server replied "No, but try again later". It's legit thing, so there is a good
                        ' chance there IS a real e-mail account under the given name there.
                        newStatus = AddressStatus.ProbablyGreylisted
                    Else
                        ' The server suddenly broke the connection. Give it one second chance, but no more.
                        newStatus = AddressStatus.ProbablyBad
                    End If
                ElseIf previousStatus = AddressStatus.ProbablyGreylisted Then
                    ' The server said "Try again later" or broke the connection?
                    If isNegativeReply Then
                        ' Greylisting returned the same result second time in a row. Maybe, it wasn't greylisting
                        ' at all? Give this e-mail address one more chance, but our patience is nearly over.
                        newStatus = AddressStatus.ProbablyBad
                    Else
                        ' Well, "If isNegativeReply" is actually redundant here. If the server broke the connection
                        ' instead of saying "Better luck next time", our assumption remains the same. There is
                        ' still a small chance that the server will accept the given address next time, so give it
                        ' one more shot to try. In your apps, however, you may consider different logic here.
                        newStatus = AddressStatus.ProbablyBad
                    End If
                Else
                    ' We're tired of all that "Try again later" occurring 3 times in a row and repetitive
                    ' disconnects during send attempts. Consider the e-mail address dead.
                    newStatus = AddressStatus.Bad
                End If
                Exit Select
        End Select

        If previousStatus <> newStatus Then
            ' Update the status in the data table. You may also need to do Commit, Update
            ' or whatever is required to apply the changes to your database.
            e.Row(StatusColumn) = newStatus
        End If

        Console.WriteLine()
    End Sub

    ' Dumps the contents of the data table to console. We use it how the statuses change
    ' over the time with making new attempts to verify the corresponding e-mails addresses.
    Private Shared Sub DisplayDataTable(ByVal data As DataTable)
        For Each row As DataRow In data.Rows
            Console.WriteLine(String.Format("{0}={1}", _
             row(EmailColumn).ToString(), CType(row(StatusColumn), AddressStatus).ToString()))
        Next
        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args As String())
        ' Common initialization, like in previous samples.
        Dim valid As New EmailAddressValidator("MN100-0123456789ABCDEF-0123")
        valid.DnsServers.Autodetect()
        valid.Log.Enabled = True
        valid.Log.Format = LogFormatOptions.AddContextInfo
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()
        AddHandler valid.Verifying, AddressOf valid_Verifying
        AddHandler valid.Verified, AddressOf valid_Verified
        valid.MaxThreadCount = -1

        Dim data As DataTable = GetDataTable()

        valid.Verify(data, EmailColumn)
        DisplayDataTable(data)

        Console.WriteLine("Press any key to continue to the 2nd run")
        Console.ReadKey(True)

        valid.Verify(data, EmailColumn)
        DisplayDataTable(data)

        Console.WriteLine("Press any key to continue to the 3rd run")
        Console.ReadKey(True)

        valid.Verify(data, EmailColumn)
        DisplayDataTable(data)

        Console.WriteLine("Press any key to exit")
        Console.ReadKey(True)
    End Sub
End Class

Of course, if you're blacklisted, you'll get numerous false positives. Examining error messages from the servers may help to find out if it's true. For instance, a typical response can include Spamhaus hit - http://www.spamhaus.org/query/bl?ip=10.20.30.40, Please contact your Internet service provider since part of their network is on our block list., Denied by policy, etc.

MailBee cannot understand these text messages as there is no SMTP error code or anything like that to find out that you're black-listed. However, MailBee provides you with their text so you can make some assumptions based on it. The samples in this tutorial print all the error messages to the console so you can use them to learn how to access the error information.

Getting data from SqlDataReader or any other IDataReader

You can pass IDataReader instance instead of DataTable as data source. This can be handy if you're getting data from SQL table and cannot afford loading data from into DataTable (such as with DataTable.Load method) because your dataset is too big (such as millions of records).

Passing IDataReader is faster and consumes less memory as only one row at a time is loaded. But some limitations apply in this case if you're running the validation in multi-threaded mode. In event handlers, you cannot access data from IDataReader directly because other threads may already advance the reader further. However, when processing a row, MailBee copies the row fields from the current row for temporary use. If for some reason you need to access them in EmailAddressValidator events, use DataReaderRowValues property of Verifying event. The same property is available for Verified event as well.

AddressValidatorDemo WinForms sample project contains sophisticated logic utilizing SqlDataReader as a data source of e-mail addresses.

DNS servers, caching, local endpoints, SMTP settings

This topic highlights some advanced matters for specific needs.

To perform DNS MX lookup, Address Validator uses DNS servers you specified in DnsServers collection. Usually, you'll use Autodetect method to populate this collection. But you can add DNS servers there manually, if you wish. See Add method and its overloads.

By default, MailBee caches DNS MX information for the domains which have already been queried (see more in DnsQuery section of Understanding validation levels topic. DnsCache class provides a number of other options, see it reference for details. The most important thing about the cache is that it's shared by all the instances of EmailAddressValidator class if you create many of them (and even Smtp class if you send e-mail after validating addresses). This also improves performance.

If your machine has multiple network adapters, you may want to bind MailBee to certain IP address or port. This may improve performance as network packets will follow shorter route. Use LocalEndPoint property for that.

Pipelining property lets you disable SMTP pipelining which provides better performance but can cause problems with some servers (although this occurs extremely rarely).

HelloDomain property lets you manually specify the domain argument for EHLO/EHLO commands. Setting it is highly recommended. If not set, MailBee will use the autodetected name or IP address of the current machine which in most cases will be local, not external. The hosts to which MailBee connects to are able to check only external domain name and compare it with EHLO argument, and it would be great to match that name. Name mismatch will increase the chance of being rejected by the target server.

SmtpTimeout can be increased if some SMTP MX servers you're dealing with are slow. Or, you can decrease it for debugging purposes to test how the app behaves when encounters sudden connection breaks.

Note that we're not dealing with SSL/TLS, authentication, and so on here. These matters do not apply to checking e-mail addresses. All connections between SMTP servers are made on plain port 25, without authentication (because servers do not know passwords of each other). Moreover, if you get "authentication required" in the logs, this means the given server cannot accept e-mail from you under the current circumstances (you're blacklisted, the account does not exist, or the MX record for the domain is incorrect and points to the SMTP relay server of that domain rather than to its MX SMTP server). No secure data is being transmitted either.

WinForms sample project

Sample projects which are installed in My Documents\MailBee.NET Objects\Samples\WinForms folder include AddressValidatorDemo project, available in both C# and VB versions, for .NET 2.0+ and .NET 4.0+. This project provides a complex example of bulk e-mail validation including multiple passes to refine results, blacklists and whitelists, MS SQL Server and file storage backends, live tracking of the operation's progress, dealing with multi-threading issues like race conditions and raising events from worker threads, and much more.

Send feedback to AfterLogic


Getting started with IMAP and POP3 components

  • Introduction
  • Feature map, as IMAP vs POP3 comparison
  • IMAP and POP3 limitations (e.g. change password feature)
  • Import namespaces and set license key
  • Retrieve e-mail in a single line of code
  • Save all attachments of downloaded e-mail
  • Display HTML e-mail with embedded pictures
  • Display international e-mail addresses (IDN domains)
  • Make IMAP version from POP3 code
  • Retrieve and parse headers for all e-mails in Inbox
  • Retrieve ranges of e-mails
  • Detect and retrieve new e-mails
  • Delete e-mails from server
  • Upload e-mails to IMAP server
  • Access e-mail in IMAP folders besides Inbox
  • Retrieve e-mail from server which requires SSL
  • Gmail IMAP and POP3 issues
  • MS Exchange IMAP and POP3 issues
  • Log file of IMAP and POP3 session
  • Troubleshoot common errors and problems

Introduction

To retrieve messages from e-mail servers, you can use MailBee.NET IMAP and MailBee.NET POP3 components. Their main classes are Imap and Pop3, respectively.

These classes can also be used to manage e-mails and folders, such as delete messages, move them between folders, upload into a folder, search messages for various criteria, manage folders, and so on. Some of this extra functionality is available only with IMAP.

E-mail messages can be downloaded completely (with all the text bodies and attachments), header-only, and mixed mode (such as headers and text body but no attachments). Again, only IMAP provides the full set of features.

Once the e-mail is downloaded, you can parse it, examine any of its properties, work with attachments, embedded pictures and other linked resources , save it into a file or stream, and process it in any other way. And you can send it again (for instance, create a reply to the message and then send the reply with MailBee.NET SMTP component).

The file format of e-mails which is used by SMTP, IMAP and POP3 protocols is called MIME. Therefore, the main class which represents an e-mail message in MailBee.NET is MailBee.Mime.MailMessage. This class can both parse and build e-mails in MIME format.

Imap and Pop3 classes return downloaded e-mails as MailMessage objects (for single e-mails) and collections (for ranges of e-mails).

Also, IMAP protocol can return some additional information with the message, which is called envelope. Thus, when using Imap class, you'll be mostly dealing with collections of envelopes rather than messages. Of course, an IMAP envelope provides access to the contained e-mail message as well.

Feature map, as IMAP vs POP3 comparison

The POP3 protocol is very simple and provides only basic features of e-mail retrieval.

The IMAP protocol (also known as IMAP4) provides much more functions and should be used whenever possible.

The only reason to prefer POP3 is if your server simply does not support IMAP (for instance, built-in e-mail server of MS Windows Server 2003/2008).

Note that MS Exchange DOES support IMAP (although it can be turned off by default, but the same is true for POP3). Moreover, some popular services like Gmail.com simply do not work with POP3 correctly.

E-mail retrieval and management | IMAP | POP3
Get entire message with attachments | + | +
Get multiple entire messages | + | +
Get message header of one or multiple e-mails | + | +
Get message header and the beginning of body section (body preview) | + | +
Detect attachments without downloading entire e-mail | + | +/-
Discover attachment filenames without downloading entire e-mail | + |
Get text body without downloading entire e-mail | + |
Get particular attachments without downloading entire e-mail | + |
Search for new e-mails | + | +/-
Search for any criteria | + |
Message flags (Seen, Answered, Flagged, etc) | + |
Server folders other than Inbox (Drafts, Trash, etc) | + |
E-mail push (instant notification on new e-mail arrival - IDLE) | +/? |
Message envelope (e.g. e-mail arrival date) | + |
Get mailbox quota | +/? |
Upload e-mail to server | + |
Copy or move e-mails between folders | + |
Custom commands | + | +
Secure authentication | + | +
Integrated Windows Authentication | + | +
OAuth 2.0 with Gmail | + | +
OAuth 2.0 with Outlook.com, Live.com, Hotmail.com | + |
Connection via proxy (SOCKS4, SOCKS5, HTTP) | + | +
Exceptions and error codes | + | +
Monitor progress with events | + | +
File and memory logging of session with e-mail server | + | +
Can be used in web (ASP.NET), desktop and console applications | + | +

+/- The feature is available with significant limitations.

+/? The feature is optional to the protocol implementation.

As soon as the e-mail has been downloaded from the server, MailMessage object comes into play and it's no longer important with which protocol the message was retrieved from the server. The capabilities of e-mail parsing and further processing are protocol-independent.

Some features require licenses for other components of MailBee.NET family. Note that MailBee.NET Objects license includes all individual component licenses.

E-mail parsing and post-processing | License required
Parse entire e-mail with header section, text bodies, and attachments |
Parse e-mail received in header-only mode |
Parse e-mail received as header + incomplete body (body preview) |
Parse standalone text body part or attachment received via IMAP |
Load e-mail from file, memory, stream, Outlook, XML, System.Net.Mail.MailMessage |
Access all headers, sender and recipients, text bodies, linked resources, and attachments |
Make plain-text version of HTML-only e-mail |
Extract linked resources (e.g. embedded pictures) |
Get HTML body and save linked resources as files |
Get HTML body and create dynamic URLs to linked resources (for web apps) |
Save any plain-text or HTML e-mail as message.htm and linked files |
Adjust HTML body (e.g. make links open in a new window) |
Remove unsafe content from HTML (e.g. scripts) |
Analyze HTML (e.g. find and process all external images) |
Non-Latin characters in headers, body, attachment filenames (e.g. UTF-8) |
Save all or selected attachments |
Save attachment to file, stream or memory |
Decode winmail.dat (MS TNEF) and extract all attachments and RTF body |
Date, DateReceived, Importance, Priority, Sensitivity |
From, ReplyTo, To, CC, and BCC (as collection and as string) |
Serialize e-mail to XML |
Save MIME data of e-mail to file, stream, memory |
Convert e-mail to Outlook .MSG format | Outlook
Convert e-mail to System.Net.Mail.MailMessage |
Re-send via SMTP or upload back to IMAP server | SMTP or IMAP
Check DKIM and DomainKeys signature |
Check if e-mail is SPAM | AntiSpam
Check S/MIME signature and decrypt encrypted e-mail | Security
Check if e-mail is bounced message or delivery report |
Access to every MIME part, time stamps (Received headers), full e-mail size, and UID |

As you can see, all the functions of parsing and processing e-mail are also available if you load e-mail from file or memory (it's not necessary to download e-mail only from IMAP or POP3 server). And you can also load e-mails from XML, System.Net.Mail.MailMessage, Outlook .MSG or .PST file.

IMAP and POP3 limitations (e.g. change password feature)

A word on things you should not expect from IMAP and POP3:

  • Create or delete e-mail account.
  • Change e-mail account password.
  • Set auto-responder (vacation message), configure forwarding e-mail to other addresses, etc.

IMAP and POP3 protocols are all about managing e-mail in the account but not about managing the account itself.

To change e-mail account password or otherwise manage an account, you'll need to check if your e-mail server supports some kind of a proprietary API for this. It can be ActiveX/COM based, REST, specialized network protocol, and so on.

For instance, some e-mail servers like Plesk Panel support POPPASSD service running at port 106, which lets you remotely change the password with POP3-alike commands.

Import namespaces and set license key

Reference MailBee.NET.dll

To start using MailBee.NET in your projects, add MailBee.NET Objects reference to your project. You can use NuGet Packager Manager console for that:

Install-Package MailBee.NET

If NuGet is not an option (for instance, you have older version of Visual Studio), see below.

The example below is for Visual Studio 2010, but the idea remains the same for any other version. For instance, Import namespaces and set license key topic of SMTP guide features similar actions in their Visual Studio 2008 version.

In Project menu (Website menu for ASP.NET project), click Add a reference:

If Website menu does not appear in the menu bar, you should select your ASP.NET project in Solution Explorer first. This will replace Project menu with Website menu.

In Visual Studio 2010, Add Reference dialog may look differently for desktop/console and ASP.NET web applications. The below is for desktop/console. The ASP.NET version may look pretty much like in Visual Studio 2008.

Under Assemblies/Extensions tab, locate MailBee.NET:

In newer versions of Visual Studio, path to the dll is not shown by default so you may need to hover mouse cursor over to see the path (and determine the version). In this case, it's .NET 4.5 version of MailBee.NET.dll:

Click Add Reference and then Close. MailBee.NET entry should appear in References list of your project.

Import MailBee.NET namespaces

Now, import MailBee.NET namespaces to the beginning of your source code files where you'll use MailBee.NET.

When working with IMAP or POP3, you'll typically need some of these namespaces:

  • C#
  • VB
using MailBee;
using MailBee.Mime;
using MailBee.ImapMail;
using MailBee.Pop3Mail;

Imports MailBee
Imports MailBee.Mime
Imports MailBee.ImapMail
Imports MailBee.Pop3Mail

If you're using other components (e.g. S/MIME functionality, HTML processor, bounce e-mail parser, etc), you may also need to import their namespaces as well. For instance:

  • C#
  • VB
using MailBee.Security;
using MailBee.Html;
using MailBee.BounceMail;

Imports MailBee.Security
Imports MailBee.Html
Imports MailBee.BounceMail

Obtain license key

Now, you need to specify your trial or permanent MailBee.NET license key to unlock the product. If you do not yet have a key, you can generate the trial key with "Get a Trial Key" utility (available in Programs / MailBee.NET Objects menu).

You can specify the key in a number of ways (Windows registry, app.config or web.config file, directly in the code). This guide shows two methods of that: hard-coded key and key stored in app.config (web.config for ASP.NET).

Using Windows registry is not recommended as your application may be lacking permission to access the required registry branches. If you still need to use the registry (e.g. if your application is distributed with the source code so that you cannot embed the key there), refer to Using License Keys topic in MailBee.NET Objects documentation for details.

Option A - specify license key directly in code

Before the first use and creating any instances of Imap or Pop3 classes, set the static MailBee.Global.LicenseKey property to assign the license key. It's assumed you've already imported MailBee.ImapMail (or MailBee.Pop3Mail) namespace with using (C#) or Imports (VB) directives.

  • C#
  • VB
MailBee.Global.LicenseKey = "MN100-0123456789ABCDEF-0123";

MailBee.Global.LicenseKey = "MN100-0123456789ABCDEF-0123"

You can also create and unlock instances of Imap and Pop3 classes, passing the license key as a parameter of a constructor, such as Imap(string). Again, it's assumed you've already imported MailBee.ImapMail (or MailBee.Pop3Mail) namespace.

  • C#
  • VB
Imap imp = newImap("MN100-0123456789ABCDEF-0123");

Dim imp As New Imap("MN100-0123456789ABCDEF-0123")

Option B - put license key in app.config or web.config

Alternatively, you can add app.config to your project (if you do not already have it there) and specify MailBee.NET SMTP license key there.

For ASP.NET application, web.config is always available so that you can immediately edit it, but for other application types you may have to add app.config manually.

The below we are using Visual Studio 2010. For a Visual Studio 2008 version, refer to a similar topic in SMTP guide.

In Projects menu, click Add New Item:

Select Application Configuration File and click Add:

In app.config, locate <appSettings/> entry in <configuration> section (if it's not there, create it), and add MailBee.NET license key as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="MailBee.Global.LicenseKey" value="MN100-0123456789ABCDEF-0123"/>
  </appSettings>
</configuration>

Note that <appSettings> may also appear as <applicationSettings> in your case.

If <appSettings> originally looked as <appSettings/> (self-closing tag syntax), you'll need to unfold it to <appSettings></appSettings> so that you could insert <add key .../> there.

The above also applies to ASP.NET application and web.config.

You can also specify the key in machine.config file. This will enable access to the license key to all applications on the computer so that there will be no need to specify the license key in each application separately. For instance, this is the preferred way if you a hosting provider willing to let your hosting clients create and run applications which use MailBee.NET without disclosing your license key to them.

Retrieve e-mail with a single line of code

You can download e-mails in a single of code using these static methods of Imap or Pop3 classes:

  • Imap.QuickDownloadMessage and Pop3.QuickDownloadMessage to download a single e-mail or its header.
  • Imap.QuickDownloadMessages and Pop3.QuickDownloadMessages to download all e-mails in the folder, or their headers.

For all the samples in this guide, we assume the license key is already set (such as in app.config file), and these namespaces are imported: MailBee.Mime, and MailBee.ImapMail or MailBee.Pop3Mail.

This sample downloads the last e-mail in Inbox via POP3, and displays its HTML body text if any:

  • C#
  • VB
MailMessage msg = Pop3.QuickDownloadMessage("pop.domain.com", "jdoe", "secret", -1);
Console.WriteLine(msg.BodyHtmlText);

Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop.domain.com", "jdoe", "secret", -1)
Console.WriteLine(msg.BodyHtmlText)

Note that you'll get an exception in case if the Inbox is empty.

You may also get an exception if the server requires SSL. See Retrieve e-mail from server which requires SSL for details.

The next sample downloads the first e-mail in Inbox via IMAP, and displays its plain-text body. If the e-mail contains only HMTL body, MailBee.NET will convert the HMTL into plain-text automatically:

  • C#
  • VB
MailMessage msg = Imap.QuickDownloadMessage("imap.domain.com", "jdoe", "secret", "Inbox", 1);
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;
Console.WriteLine(msg.BodyPlainText);

Dim msg As MailMessage = Imap.QuickDownloadMessage("imap.domain.com", "jdoe", "secret", "Inbox", 1)
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain
Console.WriteLine(msg.BodyPlainText)

If the Inbox is empty, you'll get an exception.

The sample below downloads headers for all e-mails in a POP3 inbox, and displays their subjects:

  • C#
  • VB
MailMessageCollection msgs =
    Pop3.QuickDownloadMessages("pop.company.com", "jdoe@company.com", "secret", 0);

if (msgs.Count > 0)
{
    foreach (MailMessage msg in msgs)
    {
        Console.WriteLine(msg.Subject);
    }
}
else
{
    Console.WriteLine("Inbox is empty");
}

Dim msgs As MailMessageCollection = _
    Pop3.QuickDownloadMessages("pop.company.com", "jdoe@company.com", "secret", 0)

If msgs.Count > 0 Then
   Dim msg As MailMessage
   For Each msg In  msgs
      Console.WriteLine(msg.Subject)
   Next msg
Else
   Console.WriteLine("Inbox is empty")
End If

As you can see, this sample can handle the situation when the Inbox is empty.

The next sample completely downloads all e-mails in IMAP inbox, and displays the size of every attachment found (making no difference between real attachments and linked resources):

  • C#
  • VB
MailMessageCollection msgs =
    Imap.QuickDownloadMessages("pop.company.com", "jdoe@company.com", "secret", "Inbox");

if (msgs.Count > 0)
{
    foreach (MailMessage msg in msgs)
    {
        if (msg.Attachments.Count > 0)
        {
            Console.WriteLine("Attachment size list for message " +
                msg.UidOnServer.ToString());
            foreach (Attachment attach in msg.Attachments)
            {
                Console.WriteLine(attach.Size.ToString());
            }
        }
        else
        {
            Console.WriteLine("Message " + msg.UidOnServer.ToString() +
                " has no attachments");
        }

        Console.WriteLine();
    }
}
else
{
    Console.WriteLine("Inbox is empty");
}

Dim msgs As MailMessageCollection = _
    Imap.QuickDownloadMessages("pop.company.com", "jdoe@company.com", "secret", "Inbox")

If msgs.Count > 0 Then
   Dim msg As MailMessage
   For Each msg In msgs
      If msg.Attachments.Count > 0 Then
         Console.WriteLine("Attachment size list for message " & msg.UidOnServer.ToString())
         Dim attach As Attachment
         For Each attach In msg.Attachments
            Console.WriteLine(attach.Size.ToString())
         Next attach
      Else
         Console.WriteLine("Message " & msg.UidOnServer.ToString() & " has no attachments")
      End If

      Console.WriteLine()
   Next msg
Else
   Console.WriteLine("Inbox is empty")
End If

These single-line methods which don't require you to create instances of Imap or Pop3 classes, however, have some drawbacks:

  • Cannot enable logging to see what's going on and trouble-shoot anything in case of errors.
  • In case if you need to download a single e-mail, you can't learn the number of e-mails in that folder. The only way is to download headers of all e-mails and use the count of items in the returned collection.
  • Cannot download multiple e-mails per connection, cannot delete messages, and so on.

The main purpose of the single-line methods is for quick testing during the development process. For instance, if you're developing some sort of e-mail viewer, you can temporarily use a quick method there to have some e-mail to test your e-mail viewer with, without the need of implementing production-level e-mail retrieval code at the moment when you're focused on other tasks.

Save all attachments of downloaded e-mail

The samples below download the last e-mail in Inbox and save all its attachments into a local folder (skipping linked resources like inline images). The first sample uses "quick" method to download the e-mail while the second sample creates an instance of Imap or Pop3 class.

Download e-mail with Imap.QuickDownloadMessage or Pop3.QuickDownloadMessage method:

  • C#
  • VB
MailMessage imapMsg =
    Imap.QuickDownloadMessage("imap.company.com", "jdoe@company.com", "secret", "Inbox", -1);
imapMsg.Attachments.SaveAll("C:\\Docs", true);

MailMessage popMsg =
    Pop3.QuickDownloadMessage("pop.company.com", "jdoe@company.com", "secret", -1);
popMsg.Attachments.SaveAll("C:\\Docs", true);

Dim imapMsg As MailMessage = _
    Imap.QuickDownloadMessage("imap.company.com", "jdoe@company.com", "secret", "Inbox", -1)
imapMsg.Attachments.SaveAll("C:\Docs", True)

Dim popMsg As MailMessage = _
    Pop3.QuickDownloadMessage("pop.company.com", "jdoe@company.com", "secret", -1)
popMsg.Attachments.SaveAll("C:\Docs", True)

Download e-mail normally, with Imap.DownloadEntireMessage or Pop3.DownloadEntireMessage method:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("imap.company.com");
imp.Login("jdoe@company.com", "secret");
imp.SelectFolder("Inbox");
MailMessage imapMsg = imp.DownloadEntireMessage(imp.MessageCount, false);
imp.Disconnect();
imapMsg.Attachments.SaveAll("C:\\Docs", true);

Pop3 pop = new Pop3();
pop.Connect("pop.company.com");
pop.Login("jdoe@company.com", "secret");
MailMessage popMsg = pop.DownloadEntireMessage(pop.InboxMessageCount);
pop.Disconnect();
popMsg.Attachments.SaveAll("C:\\Docs", true);

Dim imp As New Imap()
imp.Connect("imap.company.com")
imp.Login("jdoe@company.com", "secret")
imp.SelectFolder("Inbox")
Dim imapMsg As MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)
imp.Disconnect()
imapMsg.Attachments.SaveAll("C:\Docs", True)

Dim pop As New Pop3()
pop.Connect("pop.company.com")
pop.Login("jdoe@company.com", "secret")
Dim popMsg As MailMessage = pop.DownloadEntireMessage(pop.InboxMessageCount)
pop.Disconnect()
popMsg.Attachments.SaveAll("C:\Docs", True)

From now on, we'll always create instances of Imap and Pop3 class when accessing e-mail on the server.

Also note that we disconnect from the server BEFORE saving attachments. Although it's not required, this lets the application free the connection not waiting until all the attachments get saved (which might take some time). Shortly speaking, just a little optimization here.

Display HTML e-mail with embedded pictures

Assuming you downloaded an e-mail and got a MailMessage object, you can then get its HTML body via BodyHtmlText property. However, if the message has images attached, they may not be displayed. It's needed to either save these attachments locally and then modify IMG SRC of these images in the HTML body to reflect saved local files locations or embed these images directly in the HTML body with data:base64 URIs. The latter approach is very easy to use:

  • C#
  • VB
string html = msg.GetHtmlWithBase64EncodedRelatedFiles();

Dim html As String = msg.GetHtmlWithBase64EncodedRelatedFiles()

You can then load this HTML content in any browser control or send it as a response to the client in case of a web application.

If embedding into HTML body is not an option for you, you can also store embedded images on the filesystem of the server using MailMessage.GetHtmlAndSaveRelatedFiles method or on an external storage (e.g. Amazon S3 or whatever) using MailMessage.GetHtmlAndRelatedFilesInMemory method.

Display international e-mail addresses (IDN domains)

If you need to correcty display e-mail addresses with non-Latin domain names (they are usually encoded in Punycode), you can decode them in human-readable form with EmailAddress.FromIdnAddress, EmailAddressCollection.FromIdnAddress or EmailAddress.UnescapeIdnDomain methods.

It's safe to use these methods even if the address is not encoded (the methods will return the same value as on input).

  • C#
  • VB
string humanReadableEmail = msg.From.FromIdnAddress().Email;

Dim humanReadableEmail As String = msg.From.FromIdnAddress().Email

Make IMAP version from POP3 code

Note that POP3 and IMAP samples of downloading e-mail can be very close to each other. The main differences are:

  • The lack of folders except of Inbox in POP3.
  • The ability to specify message index as UID in IMAP (not used in this sample, though).

This makes it easy to adapt most POP3 samples to IMAP (or vice versa, IMAP to POP3):

  • Add Imap.SelectFolder("Inbox") after calling Imap.Connect(serverName).
  • Set indexIsUid to false when replacing Pop3.DownloadEntireMessage(index) with Imap.DownloadEntireMessage(index, indexIsUid).
  • Set indexIsUid to false when replacing Pop3.DownloadMessageHeader(index) with Imap.DownloadMessageHeader(index, indexIsUid).
  • Call Imap.Close() to purge the deleted messages (if you deleted some messages during the current session).

Given the above and for brevity's sake, many samples in this tutorial feature only POP3 or IMAP support, with the appropriate comments in protocol-specific portions. The samples which are completely specific to IMAP or POP3 are accompanied with a special note.

if you deal with ranges of e-mails (e.g. you need to display a page of 20 e-mails, from 11th to 30th), you should know about yet another difference between how ranges are specified in POP3 and IMAP:

  • In POP3, it's two numeric parameters: the first index and the count of e-mails to be affected. Example: 11, 20.
  • In IMAP, it's a string parameter consisting of the first and the last indices separated with a colon. Example: 11:30.

Operations other than downloading e-mail (such as search for new e-mails), can be very different between POP3 and IMAP (and even not always possible with POP3 at all).

Retrieve and parse headers for all e-mails in Inbox

This sample gets headers of all e-mails in the Inbox, and prints From, To, Subject for every e-mail whose header was downloaded:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("imap.company.com");
imp.Login("jdoe@company.com", "secret");
imp.SelectFolder("Inbox");
MailMessageCollection msgs = imp.DownloadMessageHeaders(Imap.AllMessages, false);
// POP3 version: msgs = pop.DownloadMessageHeaders();
imp.Disconnect();

foreach (MailMessage msg in msgs)
{
    Console.WriteLine("From: " + msg.From.ToString());
    Console.WriteLine("To: " + msg.To.ToString());
    Console.WriteLine("Subject: " + msg.Subject);
    Console.WriteLine();
}

Dim imp As New Imap()
imp.Connect("imap.company.com")
imp.Login("jdoe@company.com", "secret")
imp.SelectFolder("Inbox")
Dim msgs As MailMessageCollection = imp.DownloadMessageHeaders(Imap.AllMessages, False)
' POP3 version: msgs = pop.DownloadMessageHeaders()
imp.Disconnect()

Dim msg As MailMessage
For Each msg In msgs
   Console.WriteLine("From: " & msg.From.ToString())
   Console.WriteLine("To: " & msg.To.ToString())
   Console.WriteLine("Subject: " & msg.Subject))
   Console.WriteLine()
Next msg

Retrieve ranges of e-mails

Because ranges are set differently in POP3 and IMAP, two different samples in this topic.

This sample downloads the last 10 e-mails in Inbox via POP3:

  • C#
  • VB
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
if (pop.InboxMessageCount > 0)
{
    // If the inbox contains less than 10 e-mails, adjust to that.
    int msgCount = pop.InboxMessageCount > 10 ? 10 : pop.InboxMessageCount;

    // As e-mail indices on the server start with 1 (not 0), must add 1.
    MailMessageCollection msgs =
        pop.DownloadMessageHeaders(pop.InboxMessageCount - msgCount + 1, msgCount);

    foreach (MailMessage msg in msgs)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer.ToString());
        Console.WriteLine("From: " + msg.From.ToString());
        Console.WriteLine("To: " + msg.To.ToString());
        Console.WriteLine("Subject: " + msg.Subject);
        Console.WriteLine();
    }
}
else
{
    Console.WriteLine("Inbox is empty");
}
pop.Disconnect();

Dim pop As New Pop3()
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
If pop.InboxMessageCount > 0 Then
   ' If the inbox contains less than 10 e-mails, adjust to that.
   Dim msgCount As Integer = IIf(pop.InboxMessageCount > 10, 10, pop.InboxMessageCount)

   ' As e-mail indices on the server start with 1 (not 0), must add 1.
   Dim msgs As MailMessageCollection = _
       pop.DownloadMessageHeaders(pop.InboxMessageCount - msgCount + 1, msgCount)

   Dim msg As MailMessage
   For Each msg In msgs
      Console.WriteLine("Message #" & msg.IndexOnServer.ToString())
      Console.WriteLine("From: " & msg.From.ToString())
      Console.WriteLine("To: " & msg.To.ToString())
      Console.WriteLine("Subject: " & msg.Subject)
      Console.WriteLine()
   Next msg
Else
   Console.WriteLine("Inbox is empty")
End If
pop.Disconnect()

The IMAP version of the sample:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("jdoe", "secret");
imp.SelectFolder("Inbox");
if (imp.MessageCount > 0)
{
    // If the inbox contains less than 10 e-mails, adjust to that.
    int msgCount = imp.MessageCount > 10 ? 10 : imp.MessageCount;

    // As e-mail indices on the server start with 1 (not 0), must add 1.
    int firstIndex = imp.MessageCount - msgCount + 1;
    int lastIndex = imp.MessageCount;
    MailMessageCollection msgs = imp.DownloadMessageHeaders(
        firstIndex.ToString() + ":" + lastIndex.ToString(), false);

    foreach (MailMessage msg in msgs)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer.ToString());
        Console.WriteLine("From: " + msg.From.ToString());
        Console.WriteLine("To: " + msg.To.ToString());
        Console.WriteLine("Subject: " + msg.Subject);
        Console.WriteLine();
    }
}
else
{
    Console.WriteLine("Inbox is empty");
}
imp.Disconnect();

Dim imp As New Imap()
imp.Connect("mail.domain.com")
imp.Login("jdoe", "secret")
imp.SelectFolder("Inbox")
If imp.MessageCount > 0 Then
   ' If the inbox contains less than 10 e-mails, adjust to that.
   Dim msgCount As Integer = IIf(imp.MessageCount > 10, 10, imp.MessageCount)

   ' As e-mail indices on the server start with 1 (not 0), must add 1.
   Dim firstIndex As Integer = imp.MessageCount - msgCount + 1
   Dim lastIndex As Integer = imp.MessageCount
   Dim msgs As MailMessageCollection = imp.DownloadMessageHeaders( _
       firstIndex.ToString() & ":" & lastIndex.ToString(), False)

   Dim msg As MailMessage
   For Each msg In msgs
      Console.WriteLine("Message #" & msg.IndexOnServer.ToString())
      Console.WriteLine("From: " & msg.From.ToString())
      Console.WriteLine("To: " & msg.To.ToString())
      Console.WriteLine("Subject: " & msg.Subject)
      Console.WriteLine()
   Next msg
Else
   Console.WriteLine("Inbox is empty")
End If
imp.Disconnect()

Actually, IMAP ranges are much more powerful, they are rather sets than ranges. For instance, you can list multiple individual messages or ranges in a single set, separating them with commas. Example: 5,17,24:30,45:60,122.

You can also use the IMAP syntax like 10:*. It means "select all e-mails from 10th to the last e-mail in the folder".

Detect and retrieve new e-mails

Let's assume we need to completely download all new e-mails and display the attachment count for every downloaded message.

With IMAP, it's very simple as the IMAP server can track new e-mails itself:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("john.doe@company.com", "secret");
imp.SelectFolder("Inbox");
UidCollection uids = (UidCollection)imp.Search(true, "NEW", null);
if (uids.Count > 0)
{
    MailMessageCollection msgs = imp.DownloadEntireMessages(uids.ToString(), true);
    foreach (MailMessage msg in msgs)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer.ToString() +
            " has " + msg.Attachments.Count + " attachment(s)");
    }
}
else
{
    Console.WriteLine("No new messages");
}
imp.Disconnect();

Dim imp As New Imap()
imp.Connect("mail.domain.com")
imp.Login("john.doe@company.com", "secret")
imp.SelectFolder("Inbox")
Dim uids As UidCollection = CType(imp.Search(True, "NEW", Nothing), UidCollection)
If uids.Count > 0 Then
   Dim msgs As MailMessageCollection = imp.DownloadEntireMessages(uids.ToString(), True)
   Dim msg As MailMessage
   For Each msg In msgs
       Console.WriteLine("Message #" & msg.IndexOnServer.ToString() & _
           " has " & msg.Attachments.Count & " attachment(s)")
   Next msg
Else
   Console.WriteLine("No new messages")
End If
imp.Disconnect()

The sample above uses Unique-IDs (UIDs) instead of ordinal message numbers but it would work with message numbers too provided that nobody access the same mailbox simultaneously.

Also note that all the e-mails found are then downloaded with a single command. This may or may not be acceptable in your case. This is fast but may consume too much memory if there are many new e-mails are they are big. Usually, downloading multiple e-mails in a single command makes sense when you download just message headers (because they are quite small).

With POP3, the server knows nothing about new e-mails and you'll need to find out which e-mails are new by yourself.

Even with IMAP, you may also need to implement search for new e-mails manually in case if your idea of which e-mails are new is different from what your server thinks on the same matters. For the server, the e-mail is no longer new if anyone has already selected the folder which contains this e-mail (even if this person never downloaded the e-mail).

If you need to detect not the e-mails which just arrived but all the e-mails you have never seen (and never downloaded), use UNSEEN search flag instead of NEW.

Delete e-mails from server

Imap.DeleteMessages, Pop3.DeleteMessage, Pop3.DeleteMessages methods mark e-mails for deletion.

However, none of these methods actually delete e-mails from the mailbox. To purge e-mails marked as deleted, you should properly close the POP3 session with Pop3.Disconnect or close the IMAP folder with Imap.Close. However, there can be exceptions from this rule (Gmail is an example).

This sample deletes and purges all e-mails in Inbox (don't run it on your working e-mail account as you'll lose all the e-mails there):

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("john.doe@company.com", "secret");
imp.SelectFolder("Inbox");
imp.DeleteMessages(Imap.AllMessages, false);
imp.Close();
imp.Disconnect();

Dim imp As New Imap()
imp.Connect("mail.domain.com")
imp.Login("john.doe@company.com", "secret")
imp.SelectFolder("Inbox")
imp.DeleteMessages(Imap.AllMessages, False)
imp.Close()
imp.Disconnect()

The POP3 version:

  • C#
  • VB
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("john.doe@company.com", "secret");
pop.DeleteMessages();
pop.Disconnect();

Dim pop As New Pop3()
pop.Connect("mail.domain.com")
pop.Login("john.doe@company.com", "secret")
pop.DeleteMessages()
pop.Disconnect()

Note that some servers may, for instance, not let you delete e-mail via POP3 or may simply ignore the deletion request. The typical example of a non-standard POP3 and IMAP behaviour is Gmail. See Gmail IMAP and POP3 issues topic for details.

Upload e-mails to IMAP server

This sample creates an empty e-mail with "Message draft" text in the subject and attempts to upload it into Drafts folder on the IMAP server. If the server responds with a negative reply (probably because the folder does not exist), the sample tries to upload into Inbox then:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("john.doe@company.com", "secret");
MailMessage msg = new MailMessage();
msg.Subject = "Message draft";
try
{
    Console.WriteLine("Upload to Drafts");
    imp.UploadMessage(msg, "Drafts");
}
catch (MailBeeImapNegativeResponseException e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine("Upload to inbox");
    imp.UploadMessage(msg, "Inbox");
}
imp.Disconnect();

Dim imp As New Imap()
imp.Connect("mail.domain.com")
imp.Login("john.doe@company.com", "secret")
Dim msg As New MailMessage()
msg.Subject = "Message draft"
Try
   Console.WriteLine("Upload to Drafts")
   imp.UploadMessage(msg, "Drafts")
Catch e As MailBeeImapNegativeResponseException
   Console.WriteLine(e.Message)
   Console.WriteLine("Upload to inbox")
   imp.UploadMessage(msg, "Inbox")
End Try
imp.Disconnect()

You can also upload e-mails you just sent with SMTP, get the UID assigned to the uploaded e-mail, set flags and date, and so on.

Access e-mail in IMAP folders besides Inbox

Just supply the folder name in Imap.SelectFolder call (or Imap.ExamineFolder for read-only access to the folder).

This sample attempts to select "Sent Items" folder. If the server responds with a negative reply, the sample downloads the list of all available folders and displays their names:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("imap.domain.com");
imp.Login("john.doe", "secret");
try
{
    imp.SelectFolder("Sent Items");
}
catch (MailBeeImapNegativeResponseException e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine();
    Console.WriteLine("The available folders are:");
    FolderCollection folders = imp.DownloadFolders();
    foreach (Folder f in folders)
    {
        Console.WriteLine(f.Name);
    }
}
imp.Disconnect();

Dim imp As New Imap()
imp.Connect("imap.domain.com")
imp.Login("john.doe", "secret")
Try
   imp.SelectFolder("Sent Items")
Catch e As MailBeeImapNegativeResponseException
   Console.WriteLine(e.Message)
   Console.WriteLine()
   Console.WriteLine("The available folders are:")
   Dim folders As FolderCollection = imp.DownloadFolders()
   Dim f As Folder
   For Each f In  folders
      Console.WriteLine(f.Name)
   Next f
End Try
imp.Disconnect()

Retrieve e-mail from server which requires SSL

For Gmail.com, Outlook.com and some other popular services MailBee.NET detects SSL settings automatically. For instance. just specify the host name as imap.gmail.com for IMAP or pop.gmail.com for POP3.

It also works with Live.com, Outlook.com, Hotmail.com. At the moment of writing, the host names to specify are imap-mail.outlook.com and pop-mail.outlook.com for all these domains.

For other IMAP-over-SSL and POP3-over-SSL services, you'll need to set the SSL port explicitly.

The standard IMAP-over-SSL port is 993:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect("imap.domain.com", 993);

Dim imp As New Imap()
imp.Connect("imap.domain.com", 993)

The standard POP3-over-SSL port is 995:

  • C#
  • VB
Pop3 pop = new Pop3();
pop.Connect("pop.domain.com", 995);

Dim pop As New Pop3()
pop.Connect("pop.domain.com", 995)

By default, MailBee.NET uses the most secure SSL protocol supported by the server (usually, TLS). This is controlled by Imap.SslProtocol and Pop3.SslProtocol properties.

You can also enable STARTTLS mode to use SSL over regular 143 or 110 port by any of these methods: - Set Imap.SslMode or Pop3.SslMode property to SslStartupMode.UseStartTls value BEFORE connecting to the server. - Or, call Imap.StartTls/Pop3.StartTls AFTER connecting to the server.

Gmail IMAP and POP3 issues

Gmail.com, being mostly a web-based e-mail service, provides quite a special implementation of IMAP and POP3 protocols. This topic describes some issues that you should know about.

To configure IMAP and POP3 settings of your Gmail account, open Forwarding and POP/IMAP tab:

POP3 notes:

  • Only POP3-over-SSL is supported (at port 995). The standard port 110 is not available. By default, MailBee.NET automatically enables SSL and sets port 995 in case if the host name is pop.gmail.com.
  • Make sure to enable POP if you need POP3 access. In most cases, it makes sense to select all mail option.
  • Gmail does not allow the client to delete e-mail from the mailbox. Delete commands are simply ignored.
    You can, however, change When messages are accessed with POP setting to automatically delete or archive the e-mails you downloaded. This way Pop3.DownloadEntireMessage will also have effect of Pop3.DeleteMessage.

IMAP notes:

  • Only IMAP-over-SSL is supported (at port 993). The standard port 143 is not available. By default, MailBee.NET automatically enables SSL and sets port 993 in case if the host name is imap.gmail.com.
  • Make sure to enable IMAP if you need IMAP access.
  • You will need to enable Less Secure apps. Gmail settings page doesn't mention this but it's required. See Less secure apps & your Google Account. Don't worry, it's not what it seems. Google treats any app which authenticates with a login and password as less secure. The only alternative (if you don't want to use login/password authentication) is using OAuth 2.0. See OAuth 2.0 in Windows, .NET Core, and ASP.NET MVC apps for details.
  • When the client sets \Deleted flag for some e-mails (such as with Imap.DeleteMessages method), Gmail by default actually deletes these e-mails, not just marks them as deleted. To change this, set Auto-Expunge to off.
  • Gmail may return localized name for Inbox folder which you cannot use for selecting this folder. You must always pass INBOX to select an inbox. To find out if certain folder is inbox you can check its FolderFlags value.
  • You can use international text in search criteria only in the form of an IMAP literal. Quoted text can be used only with ASCII while literals can also be used with UTF-8 and so on. See the code snippet below (imp is Imap instance).
  • C#
  • VB
UidCollection uc = (UidCollection)imp.Search(true, "TEXT " + ImapUtils.ToLiteral("Some text"), "utf-8");

Dim uc As UidCollection = CType(imp.Search(True, "TEXT " & ImapUtils.ToLiteral("Some text"), "utf-8"), UidCollection)

Or you can use Google-specific method which gives you all the power of Google search syntax:

  • C#
  • VB
UidCollection uc = (UidCollection)imp.Search(true, "TEXT " + ImapUtils.GmailSearch("Some text"), "utf-8");

Dim uc As UidCollection = CType(imp.Search(True, "TEXT " & ImapUtils.GmailSearch("Some text"), "utf-8"), UidCollection)

If you experience Web login required error in Gmail IMAP or POP3, open https://www.google.com/accounts/DisplayUnlockCaptcha page in the browser and confirm your identity to Google. After that, IMAP and POP3 access should be working again.

If you need to disable the auto-detection of Gmail SSL settings, set MailBee.Global.AutodetectPortAndSslMode to false.

MS Exchange IMAP and POP3 issues

This topic is mainly for MS Exchange 2007-2016 and Office 365 (which is powered by MS Exchange 2016). For MS Exchange 2003, many of the issues described below do not apply. Sadly, IMAP and POP3 support in MS Exchange has degraded in newer versions.

The major specifics of MS Exchange POP3 and IMAP access is that MS Exchange mostly targets Outlook clients which work with MS Exchange via MAPI, not POP3 or IMAP. Therefore, neither IMAP nor POP3 is even enabled in MS Exchange by default. Make sure the service required for your application is running.

IMAP/POP access can also be blocked on a user level. Make sure the e-mail account you're using has IMAP/POP access enabled. However, Administrator user cannot have IMAP/POP access enabled under any circumstances.

You'll need to connect via SSL or use secure authentication. MS Exchange 2010 supports only GSSAPI which is, however, supported by MailBee.NET either.

Feature set of MS Exchange is also more limited than in most other IMAP servers. For instance, you cannot use search with international charsets (such as UTF-8). Only ASCII is supported.

You may consider switching to EWS (Exchange Web Services) when working with MS Exchange or Office 365 server. See Ews topic for examples.

Log file of IMAP and POP3 session

You can enable logging of IMAP or POP3 conversation between MailBee.NET client and the server in a number of ways. You can use logging into a file or memory, subscribe to Imap.LogNewEntry or Pop3.LogNewEntry event which raises each time a new log record is about to be created, and much more.

Logging is useful for trouble-shooting and tracking all the activity for later use. The code below enables logging of all the activity of Imap and Pop3 objects into a file and clears that file:

  • C#
  • VB
Imap imp = new Imap();
imp.Log.Enabled = true;
imp.Log.Filename = "C:\\Temp\\imap_log.txt";
imp.Log.Clear();

Pop3 pop = new Pop3();
pop.Log.Enabled = true;
pop.Log.Filename = "C:\\Temp\\pop3_log.txt";
pop.Log.Clear();

Dim imp As New Imap()
imp.Log.Enabled = True
imp.Log.Filename = "C:\Temp\imap_log.txt"
imp.Log.Clear()

Dim pop As New Pop3()
pop.Log.Enabled = True
pop.Log.Filename = "C:\Temp\pop3_log.txt"
pop.Log.Clear()

Troubleshoot common errors and problems

Typical issues you may face and their possible remedy:

  • The application does not run
    • The license key is not set correctly. See Import namespaces and set license key topic.
  • The web application does not run
    • ASP.NET virtual directory is not configured as an application in IIS. In IIS Manager, enable Application for the given web site or virtual directory.
    • ASP.NET v2.0 or v4.0 is disabled (although it may be installed). In IIS Manager for the given web site of virtual directory, check that ASP.NET version being used is 2.0 or higher (4.0 or higher is you're using .NET 4.5 optimized version, MailBee.NET.45.dll).
    • Make sure MailBee.NET.dll actually exists in /bin folder and the application does have permission to read this file.
  • Can't check e-mail at all
    • IMAP port 143 or POP3 port 110 blocked, open it (may not be possible if the port is blocked by your ISP).
    • Your server requires SSL connection, use dedicated SSL port 993/995 (IMAP/POP3) or use STARTTLS over regular port 143/110. See Retrieve e-mail from server which requires SSL (e.g. Gmail) topic for details.
    • You're trying to connect to SSL port as if it were a regular port, or vice versa. See above on how to correctly connect to a dedicated SSL port or to a regular port in STARTTLS mode.
    • Authentication failed due to incorrect username or password. The server may expect username as "account@domain" while you supplied just "account", or vice versa.
    • Secure authentication failed due to errors in its implementation on the server.
    • Web login required error indicates the user must log in via web interface of the mail service first (e.g. via Gmail web site). You can read more in Gmail IMAP and POP3 issues topic.
    • MS Exchange specific issue. See MS Exchange IMAP and POP3 issues topic for further suggestions.
    • Check if you can retrieve e-mail with another IMAP or POP3 client which is installed on the same computer as MailBee.NET. Another IMAP or POP3 client should use exactly the same settings like ports, SSL mode, authentication, etc. Note that MS Outlook is not an IMAP or POP3 client because it usually works via MAPI rather than IMAP or POP3. Mozilla Thunderbird is, however, an IMAP and POP3 client.
  • Can't see any e-mails in the mailbox while can see them with a web interface (usually, with Gmail).
    • Check the account settings. It may be configured to behave differently for the web interface and IMAP or POP3. Read more at Gmail IMAP and POP3 issues topic.
  • Out of memory errors
    • Do not receive all e-mails at once. Instead, receive large e-mails one-by-one or at least in portions (e.g. 10 e-mails per command), then process the current portion and discard it before retrieving another portion. MailBee.NET does not use temp files during e-mail retrieval so that any e-mail you download will consume memory until freed.
  • Can't save attachments or linked resources.
    • There can be a permission problem (typical for web applications, or if you write into the root folder like *C:* which is not usually allowed in modern Windows versions).

As a general suggestion, read carefully the exception message as it may already provide some useful information, and always enable logging when you face any connectivity errors. The log file is a very helpful source of the debug information which you can use to understand and fix the issue or send it to AfterLogic Support Team for further analysis.

To learn how to enable logging, see Log file of IMAP and POP3 session topic. To submit the log file to AfterLogic, create a ticket at http://helpdesk.afterlogic.com and upload the file there.

In case if certain e-mail cannot be parsed properly, you can save it as .EML file using MailMessage.SaveMessage method, and then open it in Mozilla Thunderbird. Does it look correctly there? If it's displayed OK, you can then submit it to AfterLogic as described above.

Send feedback to AfterLogic


Getting started with Outlook Converter

  • Introduction
  • More facts on Outlook and its file formats
  • Feature List
  • Import namespaces and set license key
  • Convert .MSG file to .EML
  • Convert .EML file to .MSG
  • Parse .MSG file and access the parsed e-mail data
  • Create .MSG file from scratch
  • Create .MSG file from IMAP e-mail
  • Export .MSG file into Outlook
  • Get MailMessage from Outlook inbox and save it as .EML file
  • Read .PST file without Outlook
  • Read contacts, appointments, and other items from .PST file
  • .MSG, .PST and .EML streams
  • Advanced topics and fine-tuning

Introduction

While the rest of the world uses the open standard called MIME for storing e-mail messages, MS Office Outlook uses its own set of proprietary formats to store e-mails. Outlook uses .MSG files to store individual e-mails and .PST files to represent the whole database of e-mail accounts, folders, and items in these folders (which may include e-mail messages, contacts, events, and so on).

MailBee.NET Outlook Converter provides MsgConvert and PstReader classes which allow your application to convert individual e-mails between .MSG and MIME formats or read any data from .PST files or streams. Items extracted from .PST container are automatically converted into MIME format.

For instance, you can create an e-mail using MailMessage class or take an existing e-mail, then convert it into .MSG format and open it with Outlook. You can also programmatically import the produced .MSG file into Outlook application using its own API.

Or, you can take an .MSG file or particular item from a .PST file, convert it into MIME, and then save it as .EML file, modify it with MailMessage methods and properties, send it as outgoing e-mail, or convert the modified e-mail back to .MSG format.

Outlook Converter does NOT require MS Outlook to be installed and does not depend on any third-party components, it's 100% managed .NET code.

More facts on Outlook and its file formats

This topic provides some facts which are not required to learn how to use Outlook Converter but may help you better understand Outlook in general.

Outlook and Outlook Express

Outlook (MS Office Outlook) and Outlook Express (OE) are DIFFERENT things. Although their names may look similar, these programs have very little in common. For instance, Outlook does not support MIME format (.EML files) but does support .MSG and .PST formats. At the same time, OE does support .EML but does not support .MSG and .PST formats. Outlook Converter is all about MS Office Outlook.

Outlook and MIME format

Although Outlook does not support files in MIME format, it can still parse and produce MIME-formatted messages when receiving or sending e-mail. This is because messages between e-mail servers are exchanged using MIME format only. Still, for unknown reason, Outlook does not provide any means to work with MIME format besides e-mail network protocols.

Well, it turns out newer versions of Outlook can open .EML files under some conditions but still can't save them. Anyway, .EML is still not the best message format for Outlook.

.MSG and .PST formats

.MSG and .PST formats are binary while MIME is text (.EML are normal text files). You cannot edit or adjust .MSG or .PST in any text editor like you can do with .EML file.

.MSG files can be in Outlook 97-2002 format (32-bit file) and in Outlook 2003+ format (64-bit file). Both are supported with Outlook Converter. Also, Outlook 2007 introduces the support of .MSGX format which is XML-based. It's not supported by Outlook Converter but you can use any XML parsing/building tool to read or write it. And Outlook 2007 and newer versions still fully support classic .MSG and .PST formats.

Note that some e-mail programs use .MSG extension for files which are actually in MIME format (i.e. .MSG extension does not yet guarantee you have a file in Outlook .MSG format). Most programs, however, use the correct, non-ambiguous extension for MIME messages which is .EML. With Outlook Converter, you can use any extensions for any file formats.

International characters, Unicode and ANSI formats

.MSG files can be 8-bit ANSI and 16-bit Unicode. if you deal with e-mails containing international characters, Unicode format is preferred. By default, MailBee.NET produces Unicode .MSG files during .EML to .MSG conversions.

HTML and RTF body

.MSG (.PST) and MIME formats are not just containers of the same data. For instance, .MSG and .PST usually use RTF to represent rich-formatted body while MIME format uses HTML for that.

Outlook Converter can extract RTF from .MSG and attach it to the resulting MIME but no e-mail program except of Outlook will be able to read it. For instance, Outlook Express cannot deal with RTF. You can, however, load this RTF into RichTextBox component or other tool capable of rendering RTF.

However, .MSG files usually have HTML version in addition to RTF. Although Outlook does not primarily use that HTML version to display e-mail and uses RTF for that, it usually puts the HTML version into produced messages. This way, a typical e-mail generated by Outlook has 3 bodies: plain-text, HTML, and RTF.

Another case is when you need to convert MIME e-mail with HTML body into .MSG file. For that, HTML must be converted into RTF. Outlook Converter provides basic means of such conversion (which can be suitable in most cases), and lets you use any external converter for high-quality HTML-to-RTF conversion. Although Outlook can display .MSG files which have HTML body and no RTF body, the problem occurs when you try to forward or reply such e-mail. For this to succeed, the original message must have RTF body as well.

Feature List

The below is what you can do with Outlook Converter component:

  • Parse Outlook .MSG file into MailMessage object.
  • Convert Outlook .MSG file into .EML MIME file.
  • Build Outlook .MSG file from MailMessage object.
  • Convert .EML MIME file into Outlook .MSG file.
  • Enumerate folders and data items in .PST files.
  • Extract any items from .PST files into MailMessage objects.
  • E-mails, contacts, events, tasks and other .PST items.
  • Use data streams instead of .MSG, .EML or .PST files.
  • Extract RTF body from .PST and .MSG data.
  • Create RTF body when converting .EML with HTML to .MSG.
  • Extract S/MIME signed e-mails from .MSG and .PST.

You can also use this component together with other components of MailBee.NET family (for instance, receive an e-mail with POP3 and convert it into .MSG format, or extract an .PST item and send it via SMTP).

Import namespaces and set license key

In NuGet Package Manager console, run:

Install-Package MailBee.NET

If NuGet is not an option, see similar topic in MailBee.NET SMTP or MailBee.NET IMAP/POP3 guides on how to add a reference to MailBee.NET assembly by other means.

Now, import the required namespaces at the top of your code file:

  • C#
  • VB
using MailBee;
using MailBee.Mime;
using MailBee.Outlook

Imports MailBee
Imports MailBee.Mime
Imports MailBee.Outlook

Note that MailBee and MailBee.Mime namespaces do not directly belong to Outlook Converter but the classes in these namespaces are commonly used with Outlook Converter classes.

After importing namespaces, unlock the component with your trial or permanent license key. The key can be specified in the code, in app.config/web.config, in the registry.

Depending on whether you're using MsgConvert or PstReader class (or both), you'll need to specify your license key for the class being used or for both. The license key is the same for both MsgConvert or PstReader classes because they both are part of the same component and share the same license.

Option A - specify license key directly in code

Before the first use and creating any instances of MsgConvert or PstReader classes, set the static MailBee.Global.LicenseKey property to assign the license key (if you haven't done this before). It's assumed you've already imported MailBee.Outlook namespace with using (C#) or Imports (VB) directives.

  • C#
  • VB
MailBee.Global.LicenseKey = "MN100-0123456789ABCDEF-0123";

MailBee.Global.LicenseKey = "MN100-0123456789ABCDEF-0123"

You can also create and unlock instances of MsgConvert or PstReader classes, passing the license key as a parameter of MsgConvert(string) or PstReader(string) constructor. Again, it's assumed you've already imported MailBee.Outlook namespace.

  • C#
  • VB
PstReader pstRead = newPstReader(@"C:\Temp\outlook.pst", "MN100-0123456789ABCDEF-0123");
MsgConvert msgConv = newMsgConvert("MN100-0123456789ABCDEF-0123");

Dim pstRead As New PstReader("C:\Temp\outlook.pst", "MN100-0123456789ABCDEF-0123")
Dim msgConv As New MsgConvert("MN100-0123456789ABCDEF-0123")

Option B - put license key in app.config or web.config

Alternatively, in app.config or web.config locate <appSettings> entry in <configuration> section (if it's not there, create it), and add MailBee.NET license key as follows:

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <appSettings>
      <add key="MailBee.Global.LicenseKey" value="MN100-0123456789ABCDEF-0123"/>
  </appSettings>
</configuration>

Note that <appSettings> may also appear as <applicationSettings> in your case.

If <appSettings> originally looked as <appSettings/> (self-closing tag syntax), you'll need to unfold it to <appSettings></appSettings> so that you could insert <add key .../> there.

If you do not yet have app.config or web.config, see Import namespaces and set license key in MailBee.NET SMTP guide on how to add it.

Convert .MSG file to .EML

It's easy to convert Outlook .MSG file into MIME format:

  • C#
  • VB
MsgConvert conv = new MsgConvert();
conv.MsgToEml(@"C:\Temp\test.msg", @"C:\Temp\test.eml");

Dim conv As MsgConvert = New MsgConvert
conv.MsgToEml("C:\Temp\test.msg", "C:\Temp\test.eml")

This code assumes MailBee.Outlook namespace is already imported and the license key is set.

You can also use streams instead of filenames if you need to.

Convert .EML file to .MSG

It's easy too:

  • C#
  • VB
MsgConvert conv = new MsgConvert();
conv.EmlToMsg(@"C:\Temp\test.eml", @"C:\Temp\test.msg");

Dim conv As MsgConvert = New MsgConvert
conv.EmlToMsg("C:\Temp\test.eml", "C:\Temp\test.msg")

This method also allows you to use streams instead of filenames.

Parse .MSG file and access the parsed e-mail data

MsgConvert.MsgToMailMessage method allows you to get .MSG file or data stream as MailMessage object. You can read or alter its properties, call methods, send this with Smtp class, convert it back to .MSG, serialize to XML, save it as .EML file, or do whatever else.

The code snippet below reads an .MSG file and displays its subject, plain-text body (and HTML body if available) and saves all attachments into a folder.

  • C#
  • VB
MsgConvert conv = new MsgConvert();
MailMessage msg = conv.MsgToMailMessage("C:\\Temp\\test.msg");
Console.WriteLine("Subject: " + msg.Subject);
Console.WriteLine("Plain-text body follows:");
Console.WriteLine();
Console.WriteLine(msg.BodyPlainText);
Console.WriteLine("----------------------------------------");
if (msg.BodyHtmlText != string.Empty)
{
    Console.WriteLine("HTML body follows:");
    Console.WriteLine();
    Console.WriteLine(msg.BodyHtmlText);
    Console.WriteLine("----------------------------------------");
}
msg.Attachments.SaveAll("C:\\Temp");
Console.WriteLine("Attachments:");
foreach (Attachment attach in msg.Attachments)
{
    Console.WriteLine(attach.Filename);
}

Dim conv As New MsgConvert()
Dim msg As MailMessage = conv.MsgToMailMessage("C:\Temp\test.msg")
Console.WriteLine("Subject: " + msg.Subject)
Console.WriteLine("Plain-text body follows:")
Console.WriteLine()
Console.WriteLine(msg.BodyPlainText)
Console.WriteLine("----------------------------------------")
If msg.BodyHtmlText <> String.Empty Then
    Console.WriteLine("HTML body follows:")
    Console.WriteLine()
    Console.WriteLine(msg.BodyHtmlText)
    Console.WriteLine("----------------------------------------")
End If
msg.Attachments.SaveAll("C:\Temp")
Console.WriteLine("Attachments:")
For Each attach As Attachment In msg.Attachments
    Console.WriteLine(attach.Filename)
Next

This sample does not deal with RTF (Rich-text) body. See MsgConvert.RtfInEmlMethod property documentation on how to get and display RTF body.

Create .MSG file from scratch

This code snippet below creates a new e-mail with plain-text and HTML parts containing some international text, adds a couple of attachments, and makes an .MSG file from it. Outlook Converter automatically creates RTF version of HMTL data.

  • C#
  • VB
// Create new MIME message.
MailMessage msg = new MailMessage();

// Set headers.
msg.From.Email = "jdoe@domain.com";
msg.From.DisplayName = "John Doe";
msg.To.Add("Sarah", "sdoe@company.com");
msg.Subject = "Hello (English),Привет (Russian),안녕하세요 (Korean)";

// Create plain-text body with international content.
msg.BodyPlainText = "Message text in English\r\n" +
    "Текст сообщения на русском\r\n" +
    "한국어의 텍스트 메시지";

// Create HTML body with international content.
msg.BodyHtmlText = "<html><b>Message text in English</b><br/>" +
    "<b>Текст сообщения на русском</b><br/>" +
    "<b>한국어의 텍스트 메시지</b></html>";

// Add two attachments in different ways.
msg.Attachments.Add("C:\\Temp\\report.doc");
msg.Attachments.Add("C:\\Temp\\12345678.tmp", "data.xls");

// Initialize Outlook Converter.
MsgConvert conv = new MsgConvert();

// We need Unicode as the message contains international chars.
conv.MsgAsUnicode = true;

// Tell MailBee.NET to create RTF from HTML.
conv.HtmlToRtfMethod = HtmlToRtfConversionMethod.Internal;

// The message is not intended to be editable.
conv.MsgAsDraft = false;

// Create .MSG file.
conv.MailMessageToMsg(msg, "C:\\Temp\\result.msg");

' Create new MIME message.
Dim msg As New MailMessage()

' Set headers.
msg.From.Email = "jdoe@domain.com"
msg.From.DisplayName = "John Doe"
msg.To.Add("Sarah", "sdoe@company.com")
msg.Subject = "Hello (English),Привет (Russian),안녕하세요 (Korean)"

' Create plain-text body with international content.
msg.BodyPlainText = "Message text in English" & vbCrLf & _
    "Текст сообщения на русском" & vbCrLf & "한국어의 텍스트 메시지"

' Create HTML body with international content.
msg.BodyHtmlText = "<html><b>Message text in English</b><br/>" & _
    "<b>Текст сообщения на русском</b><br/>" & _
    "<b>한국어의 텍스트 메시지</b></html>"

' Add two attachments in different ways.
msg.Attachments.Add("C:\Temp\report.doc")
msg.Attachments.Add("C:\Temp\12345678.tmp", "data.xls")

' Initialize Outlook Converter.
Dim conv As New MsgConvert()

' We need Unicode as the message contains international chars.
conv.MsgAsUnicode = True

' Tell MailBee.NET to create RTF from HTML.
conv.HtmlToRtfMethod = HtmlToRtfConversionMethod.Internal

' The message is not intended to be editable.
conv.MsgAsDraft = False

' Create .MSG file.
conv.MailMessageToMsg(msg, "C:\Temp\result.msg")

Create .MSG file from IMAP e-mail

You can convert any MailMessage object no matter how you got it (from an e-mail server, XML, stream, etc). The code snippet below gets the last e-mail from an IMAP inbox and converts it into an editable .MSG draft:

  • C#
  • VB
// Get e-mail via IMAP.
MailMessage msg = Imap.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", "Inbox", -1);

// You can adjust the message if you need to.

// Initialize Outlook Converter.
MsgConvert conv = new MsgConvert();

// The message is intended to be editable.
conv.MsgAsDraft = true;

// Create .MSG file.
conv.MailMessageToMsg(msg, "C:\\Temp\\result.msg");

' Get e-mail via IMAP.
Dim msg As MailMessage = Imap.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", "Inbox", -1)

' You can adjust the message if you need to.

' Initialize Outlook Converter.
Dim conv As New MsgConvert()

' The message is intended to be editable.
conv.MsgAsDraft = True

' Create .MSG file.
conv.MailMessageToMsg(msg, "C:\Temp\result.msg")

As this sample also uses Imap class, you'll need to import MailBee.ImapMail namespace and make sure your license key covers IMAP component.

Export .MSG file into Outlook

You can easily load .MSG file you got from MailBee.NET into Outlook. The console sample below is the extended version of the previous code snippet, it loads the produced .MSG file into Outlook inbox. Unlike previous samples, this sample requires Outlook to be installed on the computer.

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Outlook;
using MailBee.ImapMail;
using Microsoft.Office.Interop.Outlook;

class Sample
{
    static void Main(string[] args)
    {
        // Get e-mail via IMAP.
        MailMessage msg = Imap.QuickDownloadMessage(
            "mail.domain.com", "jdoe", "secret", "Inbox", -1);

        // You can adjust the message if you need to.

        // Initialize Outlook Converter.
        MsgConvert conv = new MsgConvert();

        // The message is intended to be editable.
        conv.MsgAsDraft = true;

        // Create .MSG file.
        conv.MailMessageToMsg(msg, "C:\\Temp\\result.msg");

        // Get Outlook's inbox.
        Microsoft.Office.Interop.Outlook.Application outlookApp = new Application();
        Microsoft.Office.Interop.Outlook.NameSpace ns = outlookApp.GetNamespace("MAPI");
        Microsoft.Office.Interop.Outlook.MAPIFolder outlookInbox = ns.GetDefaultFolder(
            Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

        // Load .MSG file into Oulook inbox.
        Microsoft.Office.Interop.Outlook.MailItem inboxItem = null;
        inboxItem = outlookApp.Application.CreateItemFromTemplate("C:\\Temp\\result.msg");
        inboxItem.Move(outlookInbox);
    }
}

Imports MailBee
Imports MailBee.Mime
Imports MailBee.Outlook
Imports MailBee.ImapMail
Imports Microsoft.Office.Interop.Outlook

Module Module1
    Sub Main()
        ' Get e-mail via IMAP.
        Dim msg As MailMessage = Imap.QuickDownloadMessage( _
        "mail.domain.com", "jdoe", "secret", "Inbox", -1)

        ' You can adjust the message if you need to.

        ' Initialize Outlook Converter.
        Dim conv As New MsgConvert()

        ' The message is intended to be editable.
        conv.MsgAsDraft = True

        ' Create .MSG file.
        conv.MailMessageToMsg(msg, "C:\Temp\result.msg")

        ' Get Outlook's inbox.
        Dim outlookApp As Microsoft.Office.Interop.Outlook.Application = New Application()
        Dim ns As Microsoft.Office.Interop.Outlook.NameSpace = outlookApp.GetNamespace("MAPI")
        Dim outlookInbox As Microsoft.Office.Interop.Outlook.MAPIFolder = _
            ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox)

        ' Load .MSG file into Oulook inbox.
        Dim inboxItem As Microsoft.Office.Interop.Outlook.MailItem = Nothing
        inboxItem = outlookApp.Application.CreateItemFromTemplate("C:\Temp\result.msg")
        inboxItem.Move(outlookInbox)
    End Sub
End Module

For this sample to work, you'll also need to add a reference to Microsoft.Office.Interop.Outlook in Add Reference dialog.

Get MailMessage from Outlook inbox and save it as .EML file

Although you can also extract data from Outlook's .PST file directly (see next topics), you may get e-mails and other items from Outlook via its API. Of course, this assumes that Outlook is installed on the computer where the application is running.

The console sample below saves the last e-mail in Outlook inbox as .MSG file. Then, the sample reads this file and converts it into MailMessage object and saves as .EML file.

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Outlook;
using Microsoft.Office.Interop.Outlook;

class Sample
{
    static void Main(string[] args)
    {
        // Get Outlook's inbox.
        Microsoft.Office.Interop.Outlook.Application outlookApp = new Application();
        Microsoft.Office.Interop.Outlook.NameSpace ns = outlookApp.GetNamespace("MAPI");
        Microsoft.Office.Interop.Outlook.MAPIFolder outlookInbox = ns.GetDefaultFolder(
            Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

        if (outlookInbox.Items.Count > 0)
        {
            // Note that Outlook's message indices are 1-based, not zero-based.
            // Also, this line may cause Outlook to display security warning.
            Microsoft.Office.Interop.Outlook.MailItem outlookMsg =
                outlookInbox.Items[outlookInbox.Items.Count];

            Console.WriteLine("Subject as in Outlook: " + outlookMsg.Subject);

            // Save e-mail as .MSG
            outlookMsg.SaveAs("C:\\Temp\\email.msg");

            // Initialize Outlook Converter.
            MsgConvert conv = new MsgConvert();

            // If the message has RTF body, let's attach it to the converted e-mail.
            conv.RtfInEmlMethod = RtfInEmlStorageMethod.AsAttachment;

            // Convert .MSG file to .EML MIME format.
            conv.MsgToEml("C:\\Temp\\email.msg", "C:\\Temp\\result.eml");

            // Or, load the .MSG, convert to .EML in memory, and display its properties
            MailMessage msg = conv.MsgToMailMessage("C:\\Temp\\email.msg");

            // If the convesion is OK, subject should be the same value as in Outlook.
            Console.WriteLine("Subject of converted e-mail: " + msg.Subject);
        }
        else
        {
            Console.WriteLine("Outlook inbox was empty");
        }
    }
}

Imports MailBee
Imports MailBee.Mime
Imports MailBee.Outlook
Imports Microsoft.Office.Interop.Outlook

Module Module1
    Sub Main()
        ' Get Outlook's inbox.
        Dim outlookApp As Microsoft.Office.Interop.Outlook.Application = New Application()
        Dim ns As Microsoft.Office.Interop.Outlook.NameSpace = outlookApp.GetNamespace("MAPI")
        Dim outlookInbox As Microsoft.Office.Interop.Outlook.MAPIFolder = _
            ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox)

        If outlookInbox.Items.Count > 0 Then
            ' Note that Outlook's message indices are 1-based, not zero-based.
            ' Also, this line may cause Outlook to display security warning.
            Dim outlookMsg As Microsoft.Office.Interop.Outlook.MailItem = _
                outlookInbox.Items(outlookInbox.Items.Count)

            Console.WriteLine("Subject as in Outlook: " + outlookMsg.Subject)

            ' Save e-mail as .MSG
            outlookMsg.SaveAs("C:\Temp\email.msg")

            ' Initialize Outlook Converter.
            Dim conv As New MsgConvert()

            ' If the message has RTF body, let's attach it to the converted e-mail.
            conv.RtfInEmlMethod = RtfInEmlStorageMethod.AsAttachment

            ' Convert .MSG file to .EML MIME format.
            conv.MsgToEml("C:\Temp\email.msg", "C:\Temp\result.eml")

            ' Or, load the .MSG, convert to .EML in memory, and display its properties
            Dim msg As MailMessage = conv.MsgToMailMessage("C:\Temp\email.msg")

            ' If the convesion is OK, subject should be the same value as in Outlook.
            Console.WriteLine("Subject of converted e-mail: " + msg.Subject)
        Else
            Console.WriteLine("Outlook inbox was empty")
        End If
    End Sub
End Module

The sample assumes MailBee.Global.LicenseKey is set in the app.config/web.config file or registry. You'll also need to add a reference to Microsoft.Office.Interop.Outlook in Add Reference dialog.

Note that Outlook may display a warning when another application tries to access its resources.

Read .PST file without Outlook

This console sample displays From field of all the e-mails in Inbox, and saves the last e-mails in Inbox and Drafts as .EML files:

  • C#
  • VB
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Outlook;

class Sample
{
    static void Main(string[] args)
    {
        // If Outlook is installed and running, the .PST file may be blocked for read access.
        PstReader pstRead = new PstReader(@"C:\Temp\Outlook.pst");
        PstFolderCollection folders = pstRead.GetPstRootFolders(true);
        foreach (PstFolder folder in folders)
        {
            if (folder.ShortName.ToLower() == "inbox")
            {
                // For all inbox e-mails, display subject.
                MailMessage inboxMsg = null;
                foreach (PstItem item in folder.Items)
                {
                    inboxMsg = item.GetAsMailMessage();
                    Console.WriteLine(inboxMsg.Subject);
                }

                // And save the last e-mail to disk as .EML file.
                if (inboxMsg != null)
                {
                    inboxMsg.SaveMessage(@"C:\Temp\inbox.eml");
                }
            }

            // Save last e-mail in Drafts folder to disk as .EML file.
            // Here, we do not use "foreach" and access the last item directly.
            if (folder.ShortName.ToLower() == "drafts")
            {
                if (folder.Items.Count > 0)
                {
                    // Note that indices are zero-based (in Outlook interop, they are 1-based).
                    MailMessage draftsMsg = folder.Items[folder.Items.Count - 1].GetAsMailMessage();
                    draftsMsg.SaveMessage(@"C:\Temp\drafts.eml");
                }
            }
        }

        pstRead.Close();
    }
}

Imports MailBee
Imports MailBee.Mime
Imports MailBee.Outlook

Module Module1
    Sub Main()
        ' If Outlook is installed and running, the .PST file may be blocked for read access.
        Dim pstRead As New PstReader("C:\Temp\Outlook.pst")
        Dim folders As PstFolderCollection = pstRead.GetPstRootFolders(True)
        For Each folder As PstFolder In folders
            If folder.ShortName.ToLower() = "inbox" Then
                ' For all inbox e-mails, display subject.
                Dim inboxMsg As MailMessage = Nothing
                For Each item As PstItem In folder.Items
                    inboxMsg = item.GetAsMailMessage()
                    Console.WriteLine(inboxMsg.Subject)
                Next

                ' And save the last e-mail to disk as .EML file.
                If inboxMsg IsNot Nothing Then
                    inboxMsg.SaveMessage("C:\Temp\inbox.eml")
                End If
            End If

            ' Save last e-mail in Drafts folder to disk as .EML file.
            ' Here, we do not use "For Each" and access the last item directly.
            If folder.ShortName.ToLower() = "drafts" Then
                If folder.Items.Count > 0 Then
                    ' Note that indices are zero-based (in Outlook interop, they are 1-based).
                    Dim draftsMsg As MailMessage = _
                        folder.Items(folder.Items.Count - 1).GetAsMailMessage()
                    draftsMsg.SaveMessage("C:\Temp\drafts.eml")
                End If
            End If
        Next

        pstRead.Close()
    End Sub
End Module

The sample assumes MailBee.Global.LicenseKey is set in the app.config/web.config file or registry.

Outlook, however, is not required, and there are no its interop dependencies.

Read contacts, appointments, and other items from .PST file

MailBee.NET can extract items of any type from a .PST file. This includes not only e-mail messages but also contacts, activities, tasks, rss items, appointments, and any other items which can be stored in a .PST file.

You can can access the specific properties of an .PST item with PstFields property (hash table of values) available for every item extracted.

Also, you can use GetAsMailMessage method to convert the extracted item into MIME format (this lets you work with non-emails like if they were e-mails, using the same methods, e.g. serialize them to .XML, save to file, etc). For such items, MailBee.NET will add all the specific property values as X-... headers to their MIME source.

For instance, PstRss.GetAsMailMessage method adds X-Rss-<property_name> headers while PstContact.GetAsMailMessage method adds X-Contact-<property_name> ones.

PstFields property documentation on every .PST item type lists all the the available specific properties and their types (e.g. PstRss.PstFields, PstContact.PstFields, etc).

The code snippet below displays some details on all the contacts found in Contacts folder of the .PST file:

  • C#
  • VB
// If Outlook is installed and running, the .PST file may be blocked for read access.
PstReader pstRead = new PstReader(@"C:\Temp\Outlook.pst");
PstFolderCollection folders = pstRead.GetPstRootFolders(true);
foreach (PstFolder folder in folders)
{
    if (folder.ShortName.ToLower() == "contacts")
    {
        foreach (PstItem item in folder.Items)
        {
            PstContact contact = item as PstContact;

            if (contact != null)
            {
                Console.WriteLine(string.Format(
                    "Given name = {0}, surname = {1}, Email1 = {2}",
                    contact.PstFields["GivenName"], contact.PstFields["Surname"],
                    contact.PstFields["Email1EmailAddress"]));
            }
        }
    }
}

pstRead.Close();

' If Outlook is installed and running, the .PST file may be blocked for read access.
Dim pstRead As New PstReader("C:\Temp\Outlook.pst")
Dim folders As PstFolderCollection = pstRead.GetPstRootFolders(True)
For Each folder As PstFolder In folders
    If folder.ShortName.ToLower() = "contacts" Then
        For Each item As PstItem In folder.Items
            Dim contact As PstContact = TryCast(item, PstContact)

            If contact IsNot Nothing Then
                Console.WriteLine(String.Format( _
                    "Given name = {0}, surname = {1}, Email1 = {2}", _
                    contact.PstFields("GivenName"), contact.PstFields("Surname"), _
                    contact.PstFields("Email1EmailAddress")))
            End If
        Next
    End If
Next

pstRead.Close()

This sample does not need Outlook to be installed on the computer. However, if Outlook is installed and running, may need to close it to let other applications access its .PST file.

This code snippet assumes MailBee.Global.LicenseKey is set in the app.config/web.config file or registry, and MailBee.Outlook namespace is imported.

.MSG, .PST and .EML streams

All the samples in this guide use .MSG, .EML and .PST as files but you may want to know that all the methods used in the sample also have overloads accepting Stream instead of filename. Thus, you can work with .PST and .MSG data in memory, not saving anything to the filesystem.

The above, however, only corresponds to Outlook Converter itself. If you're using Outlook interop, you have to use files because Outlook does not provide any Stream-based methods to exchange e-mail data between applications.

Advanced topics and fine-tuning

This article briefly highlights some specific matters of Outlook Converter.

PstReader does support S/MIME signed e-mails. Upon extraction, you can use Smime class to verify the extracted MailMessage. You'll need MailBee.NET Security license for that (included in MailBee.NET Objects unified key).

On MSG-EML conversion, you can use MsgConvert.RtfInEmlMethod property to control whether and how to include RTF body into the resulting MIME message. If extracting data from .PST file, the property name is PstMessage.RtfInEmlMethod.

MsgConvert.OnByteToStringConversion delegate is handy if you convert international e-mails from non-Unicode .MSG to .EML. You can supply your own version of converting .MSG data from bytes to string (which will, for instance, use non-default Encoding for that). This may help if you know the codepage of the source .MSG message (if it's not Unicode, MailBee.NET assumes the default codepage because .MSG file does not provide the information which codepage it uses).

MsgConvert.MsgAsUnicode propery sets if the resulting .MSG file of EML-to-MSG conversion should be Unicode. Set it to false if you need ANSI for some reason.

MsgConvert.MsgAsDraft let's you control whether the user will be able to edit the resulting .MSG file prior to sending, or it can only be sent without alteration.

PstReader class provides PstReader.GetFolderByID and PstReader.GetItemByID methods which let you access arbitrary items of a .PST file without iterating through all the items. These methods usually are not needed if you process the file only once (e.g. convert its contents to .EML files) but can be useful if you work with this .PST file in more complex ways.

Send feedback to AfterLogic


iCal and vCard calendars and contacts

  • iCal and vCard formats
  • ICalVCard.dll plugin
  • Parse vCard contact and display its contents
  • Display photo from vCard in Windows desktop app
  • Create vCard with photo and send it as e-mail
  • Create iCal appointment
  • Create event
  • Create recurring event
  • Create appointment with reminder
  • Respond to appointment request
  • Analyze responses to appointment request

iCal and vCard formats

iCal (ICS) is a file format which describes calendar events, including appointments (meeting requests), ordinary events, recurring events, reminders, etc. To exchange events over e-mail, iCal entries can be added to an e-mail. Outlook and many other e-mail systems can automatically extract iCal entries from e-mails to update their calendars, allow the user to accept or decline meeting request, and so on. iCal files usually have .ics extension.

MailBee.NET allows you to perform all kinds of operations defined for iCal, so that you can create meeting requests and send them to attendees, respond to meeting requests from other persons, analyze responses from attendees, create ordinary and recurring events, use reminders, etc.

vCard (VCF) is a file format for exchanging contact information (where contact can be any person or organization). With MailBee.NET, you can create or parse vCard data, including contacts' photos. vCard files usually have .vcf extension.

ICalVCard.dll plugin

In MailBee.NET, iCal and vCard functionality is not the part of MailBee.NET.dll. Instead, it resides in a separate .DLL. It's called ICalVCard.dll, and installed in "C:\Program Files (x86)\MailBee.NET Objects". Thus, you need to add a reference to this .DLL (in addition to MailBee.NET.dll reference) if you plan to use iCal or vCard feature. Like MailBee.NET.dll, ICalVCard.dll is also installed in GAC by MailBee.NET Objects installer, and can be found in Add Reference dialog of Visual Studio.

To install via NuGet:

Install-Package ICalVCard

ICalVCard is only available for classic .NET Framework v2.0-4.8 and not yet compatible with .NET Core and UWP.

ICalVCard.dll has separate documentation, and the source code is publicly available. You can read more at: https://afterlogic.com/mailbee-net/icalvcard. The functionality of this .DLL is free, no license key required for any classes.

As for class reference, you can use online documentation or download .CHM file.

Please note that the support of ICalVCard.dll from AfterLogic is limited. This is a community project, based on other open source projects, and provided as-is. Still, the samples below should provide a good starting point as the highlight most of typical cases of iCal and vCard usage.

For iCal, you may find the ical.NET library from https://github.com/rianjs/ical.net more stable and flexible. It's based on the same project as ICalVCard.dll so porting your code to ical.NET shouldn't be a big deal.

ICalVCard.dll uses streams for data input and output and does not use any classes of MailBee.NET. Thus, you can even use it without MailBee.NET at all (although this case has never been tested).

Parse vCard contact and display its contents

This sample loads the message from an .EML file (it's assumed the message has a vCard attachment) and displays several fields from the vCard user profile:

  • C#
  • VB
using System;
using MailBee.Mime;
using vCards;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\vcard.eml");

        foreach (Attachment attach in msg.Attachments)
        {
            if (attach.IsVCard)
            {
                vCard crd = new vCard(attach.GetData());

                Console.WriteLine("Name: " + crd.FormattedName);
                Console.WriteLine("Title: " + crd.Title);
                Console.WriteLine("BirthDate: " + crd.BirthDate);
                Console.WriteLine("Organization: " + crd.Organization);

                foreach (vCardPhone phone in crd.Phones)
                {
                    if (phone.IsCellular)
                    {
                        Console.WriteLine("Cellular phone number: " + phone.FullNumber);
                    }
                    else if (phone.IsHome)
                    {
                        Console.WriteLine("Home phone number: " + phone.FullNumber);
                    }
                    else if (phone.IsWork)
                    {
                        Console.WriteLine("Work phone number: " + phone.FullNumber);
                    }
                    else if (phone.IsFax)
                    {
                        Console.WriteLine("Fax number: " + phone.FullNumber);
                    }
                }
            }
        }
    }
}

Imports System
Imports MailBee.Mime
Imports vCards

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim msg As MailMessage = New MailMessage
        msg.LoadMessage("C:\Docs\vcard.eml")

        Dim attach As Attachment
        For Each attach In msg.Attachments
            If attach.IsVCard Then
                Dim crd As vCard = New vCard(attach.GetData())

                Console.WriteLine("Name: " & crd.FormattedName)
                Console.WriteLine("Title: " & crd.Title)
                Console.WriteLine("BirthDate: " & crd.BirthDate)
                Console.WriteLine("Organization: " & crd.Organization)

                Dim phone As vCardPhone
                For Each phone In crd.Phones
                    If phone.IsCellular Then
                        Console.WriteLine("Cellular phone number: " & phone.FullNumber)
                    ElseIf phone.IsHome Then
                        Console.WriteLine("Home phone number: " & phone.FullNumber)
                    ElseIf phone.IsWork Then
                        Console.WriteLine("Work phone number: " & phone.FullNumber)
                    ElseIf phone.IsFax Then
                        Console.WriteLine("Fax number: " & phone.FullNumber)
                    End If
                Next
            End If
        Next
    End Sub
End Class

We assume you've added references to MailBee.NET.dll and ICalVCard.dll (MailBee.NET.4.dll and ICalVCard.4.dll if you target .NET Framework 4.0 or higher). The sample loads the e-mail from a file but you can download it from a POP3 or IMAP server or get it from any other source (like in the next sample).

Display photo from vCard in Windows desktop app

This sample shows how to display Name and Surname with photo from vCard in a simple Windows Forms application. You should add two Label controls on the form for text output and a PictureBox control to display the image.

  • C#
  • VB
// Add to the beginning of your code file.
using System.IO;
using MailBee.Mime;
using MailBee.ImapMail;
using vCards;

// The actual code snippet.
MailMessage msg =
    Imap.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", "Inbox", -1);

foreach (Attachment attach in msg.Attachments)
{
    if (attach.IsVCard)
    {
        vCard crd = new vCard(attach.GetData());

        label1.Text = crd.GivenName;
        label2.Text = crd.FamilyName;

        pictureBox1.Image = Image.FromStream(
            new MemoryStream(crd.Photos[0].GetBytes()));
    }
}

' Add to the beginning of your code file.
Imports System.IO
Imports MailBee.Mime
Imports MailBee.ImapMail
Imports vCards

' The actual code snippet.
Dim msg As MailMessage = _
    Imap.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", "Inbox", -1)

Dim attach As Attachment
For Each attach In msg.Attachments
    If attach.IsVCard Then
        Dim crd As vCard = New vCard(attach.GetData())

        label1.Text = crd.GivenName
        label2.Text = crd.FamilyName

        pictureBox1.Image = Image.FromStream( _
            New MemoryStream(crd.Photos(0).GetBytes()))
    End If
Next

We assume MailBee.Global.LicenseKey is already set in app.config, registry, etc. If not, you can set it in the code.

Note that vCard photos can be of different formats (.BMP, .JPG) but PictureBox control can handle both of them.

Create vCard with photo and send it as e-mail

This sample creates a vCard user profile with a photo and sends it to a recipient. The sample does not set any body in the message but you can add it if you need to.

  • C#
  • VB
using System;
using System.IO;
using System.Text;
using MailBee.Mime;
using MailBee.SmtpMail;
using vCards;

class Sample
{
    static void Main(string[] args)
    {
        // Create a new contact.
        vCard crd = new vCard();

        crd.GivenName = "John";
        crd.FamilyName = "Smith";

        crd.Gender = vCardGender.Male;
        crd.BirthDate = new DateTime(1980, 3, 2);

        crd.Phones.Add(new vCardPhone("123-456-789", vCardPhoneTypes.Cellular));
        crd.Phones.Add(new vCardPhone("893-111-789", vCardPhoneTypes.Home));
        crd.Phones.Add(new vCardPhone("222-555-333", vCardPhoneTypes.Work));

        // We assume this file exists and contains the contact photo.
        vCardPhoto photo = new vCardPhoto(@"C:\Docs\john_smith.jpg");

        crd.Photos.Add(photo);

        MailMessage msg = new MailMessage();
        msg.From.AsString = "Me <from@domain.com>";
        msg.To.AddFromString("You <to@company.com>");
        msg.Subject = "See attached vCard";

        vCardStandardWriter wrt = new vCardStandardWriter();

        StringWriter sw = new StringWriter();

        // Specify charset to encode non-ascii strings. Use Western-European
        // encoding in this sample (you can also use UTF-8 or whatever).
        wrt.Write(crd, sw, "windows-1252");

        // Add vCard as attachment.
        msg.Attachments.Add(
            Encoding.GetEncoding("windows-1252").GetBytes(sw.ToString()),
            "John Smith.vcf", null, "application/octet-stream", null,
            NewAttachmentOptions.None, MailTransferEncoding.QuotedPrintable);

        // Send resulting e-mail in "direct send" mode. You can also send it via
        // SMTP relay (see Smtp.Send for details).
        Smtp.QuickSend(msg);
    }
}

Imports System.IO
Imports System.Text
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports vCards

Class Sample
    Shared Sub Main(ByVal args As String())
        ' Create a new contact.
        Dim crd As New vCard()

        crd.GivenName = "John"
        crd.FamilyName = "Smith"

        crd.Gender = vCardGender.Male
        crd.BirthDate = New DateTime(1980, 3, 2)

        crd.Phones.Add(New vCardPhone("123-456-789", vCardPhoneTypes.Cellular))
        crd.Phones.Add(New vCardPhone("893-111-789", vCardPhoneTypes.Home))
        crd.Phones.Add(New vCardPhone("222-555-333", vCardPhoneTypes.Work))

        ' We assume this file exists and contains the contact photo.
        Dim photo As New vCardPhoto("C:\Docs\john_smith.jpg")

        crd.Photos.Add(photo)

        Dim msg As New MailMessage()
        msg.From.AsString = "Me <from@domain.com>"
        msg.[To].AddFromString("You <to@company.com>")
        msg.Subject = "See attached vCard"

        Dim wrt As New vCardStandardWriter()

        Dim sw As New StringWriter()

        ' Specify charset to encode non-ascii strings. Use Western-European
        ' encoding in this sample (you can also use UTF-8 or whatever).
        wrt.Write(crd, sw, "windows-1252")

        ' Add vCard as attachment.
        msg.Attachments.Add(Encoding.GetEncoding("windows-1252").GetBytes(sw.ToString()), _
            "John Smith.vcf", Nothing, "application/octet-stream", Nothing, _
            NewAttachmentOptions.None, MailTransferEncoding.QuotedPrintable)

        ' Send resulting e-mail in "direct send" mode. You can also send it via
        ' SMTP relay (see Smtp.Send for details).
        Smtp.QuickSend(msg)
    End Sub
End Class

We assume MailBee.Global.LicenseKey is already set in app.config, registry, etc. If not, you can set it in the code.

Create iCal appointment

This sample sends two e-mails containing a meeting request (appointment) each. Attendees to which these meeting requests are sent to can then use their iCal-capable e-mail clients (like Outlook) to respond with Accept, Decline, or Tentative status.

The first meeting request is sent to two people (which demonstrates that you don't need to send individual e-mail to each attendee, you can list all attendees in the same e-mail).

The second meeting request is sent to demonstrate how to track multiple meeting requests. If we send multiple meeting requests for which we then get responses from their respective attendees, we need somehow match these responses and the original meeting requests to determine which response corresponds to which request.

For every meeting request, Unique-ID is generated. This Unique-ID has nothing to do with Unique-ID (UID) or Message-ID of e-mails, this is iCal Unique-ID. In this sample, we save all the generated iCal Unique-IDs in a file. We'll use the stored values in Analyze responses to appointment request sample to match meeting requests and responses.

  • C#
  • VB
using System;
using System.IO;
using System.Collections;
using MailBee.Mime;
using MailBee.SmtpMail;
using iCal;
using iCal.Serialization.iCalendar;

// This sample sends meeting requests to some persons and saves the unique-id
// assigned to that appointments into a file. These unique-ids are used to match
// appointments and replies to them. ShowAcceptanceStatus sample can then read
// this file to determine for which appointment the confirmation was received.

class SendAppointment
{
    static void Main(string[] args)
    {
        EmailAddress emailFrom = EmailAddress.Parse("Event Creator <jdoe@domain.com>");

        // Attendees of meeting #1.
        EmailAddress meeting1attendee1 = EmailAddress.Parse("Person1 <alice@company.com>");
        EmailAddress meeting1attendee2 = EmailAddress.Parse("Person2 <john@domain.com>");

        // Attendee of meeting #2.
        EmailAddress meeting2attendee1 = EmailAddress.Parse("Person3 <bob@company.com>");

        // SMTP settings.
        string smtpServer = "smtp.domain.com";
        int smtpPort = 25; // Specify 465 for SSL.
        string username = "jdoe";
        string password = "secret";

        Smtp mailer = new Smtp();

        SmtpServer srv = new SmtpServer(smtpServer, username, password);
        srv.Port = smtpPort;
        mailer.SmtpServers.Add(srv);

        // First meeting request e-mail, two recipients.
        MailMessage msg = mailer.Message;
        msg.From = emailFrom;
        msg.To.Add(meeting1attendee1);
        msg.To.Add(meeting1attendee2);
        msg.Subject = "iCal appointment with 2 recipients";

        // Create event part.
        iCalendar iCal1 = new iCalendar();
        iCal1.Method = "REQUEST";
        Event evt1 = iCal1.Create<Event>();
        evt1.Start = new iCalDateTime(DateTime.Today.AddDays(1));
        evt1.End = evt1.Start.AddHours(1);
        evt1.IsAllDay = false;
        evt1.Summary = "Project meeting";
        evt1.Location = "Conference room";

        // Add recipients for appointment.
        Attendee att1 = new Attendee("mailto:" + meeting1attendee1.Email);
        att1.RSVP = true;
        att1.CommonName = meeting1attendee1.DisplayName;
        evt1.Attendees.Add(att1);

        Attendee att2 = new Attendee("mailto:" + meeting1attendee2.Email);
        att2.RSVP = true;
        att2.CommonName = meeting1attendee2.DisplayName;
        evt1.Attendees.Add(att2);

        iCalendarSerializer serializer1 = new iCalendarSerializer();

        // Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text =
            serializer1.SerializeToString(iCal1);

        // Send first meeting request to 2 recipients.
        mailer.Send();

        ArrayList eventList = new ArrayList();

        // Save event's Unique-ID and recipients' e-mail addresses to our database.
        eventList.Add(iCal1.UniqueComponents[0].UID + ";" + meeting1attendee1.Email + ";");
        eventList.Add(iCal1.UniqueComponents[0].UID + ";" + meeting1attendee2.Email + ";");

        // Second meeting request e-mail, one recipient.
        msg.Reset();
        msg.From = emailFrom;
        msg.To.Add(meeting2attendee1);
        msg.Subject = "iCal appointment with 1 recipient";

        // Create event part.
        iCalendar iCal2 = new iCalendar();
        iCal2.Method = "REQUEST";
        Event evt2 = iCal2.Create<Event>();
        evt2.Start = new iCalDateTime(DateTime.Today.AddDays(2));
        evt2.End = evt2.Start.AddHours(1);
        evt2.IsAllDay = false;
        evt2.Summary = "Lunch";
        evt2.Location = "Dinner room";

        // Add recipients for appointment.
        Attendee att3 = new Attendee("mailto:" + meeting2attendee1.Email);
        att3.RSVP = true;
        att3.CommonName = meeting2attendee1.DisplayName;
        evt2.Attendees.Add(att3);

        iCalendarSerializer serializer2 = new iCalendarSerializer();

        // Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text =
            serializer2.SerializeToString(iCal2);

        // Send second meeting request to 1 recipient.
        mailer.Send();

        // Save event's Unique-ID and recipient's e-mail address to our database.
        eventList.Add(iCal2.UniqueComponents[0].UID + ";" + meeting2attendee1.Email + ";");

        // Write database to disk.
        File.WriteAllLines(@"C:\Temp\eventUid.txt", (string[])eventList.ToArray(typeof(string)));
    }
}

Imports System.IO
Imports System.Collections
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports iCal
Imports iCal.Serialization.iCalendar

' This sample sends meeting requests to some persons and saves the unique-id
' assigned to that appointments into a file. These unique-ids are used to match
' appointments and replies to them. ShowAcceptanceStatus sample can then read
' this file to determine for which appointment the confirmation was received.

Module SendAppointment
    Sub Main(ByVal args As String())
        Dim emailFrom As EmailAddress = EmailAddress.Parse("Event Creator <jdoe@domain.com>")

        ' Attendees of meeting #1.
        Dim meeting1attendee1 As EmailAddress = EmailAddress.Parse("Person1 <alice@company.com>")
        Dim meeting1attendee2 As EmailAddress = EmailAddress.Parse("Person2 <john@domain.com>")

        ' Attendee of meeting #2.
        Dim meeting2attendee1 As EmailAddress = EmailAddress.Parse("Person3 <bob@company.com>")

        ' SMTP settings.
        Dim smtpServer As String = "smtp.domain.com"
        Dim smtpPort As Integer = 25 ' Specify 465 for SSL.
        Dim username As String = "jdoe"
        Dim password As String = "secret"

        Dim mailer As New Smtp()

        Dim srv As New SmtpServer(smtpServer, username, password)
        srv.Port = smtpPort
        mailer.SmtpServers.Add(srv)

        ' First meeting request e-mail, two recipients.
        Dim msg As MailMessage = mailer.Message
        msg.From = emailFrom
        msg.[To].Add(meeting1attendee1)
        msg.[To].Add(meeting1attendee2)
        msg.Subject = "iCal appointment with 2 recipients"

        ' Create event part.
        Dim iCal1 As New iCalendar()
        iCal1.Method = "REQUEST"
        Dim evt1 As [Event] = iCal1.Create(Of [Event])()
        evt1.Start = New iCalDateTime(DateTime.Today.AddDays(1))
        evt1.End = evt1.Start.AddHours(1)
        evt1.IsAllDay = False
        evt1.Summary = "Project meeting"
        evt1.Location = "Conference room"

        ' Add recipients for appointment.
        Dim att1 As New Attendee("mailto:" & meeting1attendee1.Email)
        att1.RSVP = True
        att1.CommonName = meeting1attendee1.Email
        evt1.Attendees.Add(att1)

        Dim att2 As New Attendee("mailto:" & meeting1attendee2.Email)
        att2.RSVP = True
        att2.CommonName = meeting1attendee2.Email
        evt1.Attendees.Add(att2)

        Dim serializer1 As New iCalendarSerializer()

        ' Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text = serializer1.SerializeToString(iCal1)

        ' Send first meeting request to 2 recipients.
        mailer.Send()

        Dim eventList As New ArrayList()

        ' Save event's Unique-ID and recipients' e-mail addresses to our database.
        eventList.Add(iCal1.UniqueComponents(0).UID & ";" & meeting1attendee1.Email & ";")
        eventList.Add(iCal1.UniqueComponents(0).UID & ";" & meeting1attendee2.Email & ";")

        ' Second meeting request e-mail, one recipient.
        msg.Reset()
        msg.From = emailFrom
        msg.[To].Add(meeting2attendee1)
        msg.Subject = "iCal appointment with 1 recipient"

        ' Create event part.
        Dim iCal2 As New iCalendar()
        iCal2.Method = "REQUEST"
        Dim evt2 As [Event] = iCal2.Create(Of [Event])()
        evt2.Start = New iCalDateTime(DateTime.Today.AddDays(2))
        evt2.End = evt2.Start.AddHours(1)
        evt2.IsAllDay = False
        evt2.Summary = "Lunch"
        evt2.Location = "Dinner room"

        ' Add recipients for appointment.
        Dim att3 As New Attendee("mailto:" & meeting2attendee1.Email)
        att3.RSVP = True
        att3.CommonName = meeting2attendee1.Email
        evt2.Attendees.Add(att3)

        Dim serializer2 As New iCalendarSerializer()

        ' Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text = serializer2.SerializeToString(iCal2)

        ' Send second meeting request to 1 recipient.
        mailer.Send()

        ' Save event's Unique-ID and recipient's e-mail address to our database.
        eventList.Add(iCal2.UniqueComponents(0).UID + ";" & meeting2attendee1.Email & ";")

        ' Write database to disk.
        File.WriteAllLines("C:\Temp\eventUid.txt", DirectCast(eventList.ToArray(GetType(String)), String()))
    End Sub
End Module

As before, we assume MailBee.Global.LicenseKey is already set in app.config, registry, etc. If not, you can set it in the code.

In real code, you'll probably use SQL database (rather than a text file like it's done in this sample) to store and update meeting request details.

Create event

This sample creates an iCal event which does not assume a response from anybody is required. The e-mail program of the person which receives the e-mail with this event will just add this event into the local calendar, no question "Will you participate in this?" will be asked.

  • C#
  • VB
using System;
using System.IO;
using MailBee.Mime;
using MailBee.SmtpMail;
using iCal;
using iCal.Serialization.iCalendar;

class SendEvent
{
    static void Main(string[] args)
    {
        EmailAddress emailFrom = EmailAddress.Parse("John Doe <jdoe@domain.com>");

        // Attendee of meeting.
        EmailAddress meeting1attendee1 = EmailAddress.Parse("Alice <alice@company.com>");

        MailMessage msg = new MailMessage();
        msg.From = emailFrom;
        msg.To.Add(meeting1attendee1);
        msg.Subject = "Server backup";

        // Create new event.
        iCalendar iCal = new iCalendar();

        Event evt = iCal.Create<Event>();
        evt.Start = new iCalDateTime(DateTime.Today.AddDays(1));
        evt.End = evt.Start.AddHours(1);
        evt.IsAllDay = false;
        evt.Summary = "Server backup";
        evt.Location = "Server room";

        iCalendarSerializer serializer = new iCalendarSerializer();

        // Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text =
            serializer.SerializeToString(iCal);

        // And send it (we use direct send here, you can send it via SMTP relay as well).
        Smtp.QuickSend(msg);
    }
}

Imports System.IO
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports iCal
Imports iCal.Serialization.iCalendar

Module SendEvent
     Sub Main(ByVal args As String())
        Dim emailFrom As EmailAddress = EmailAddress.Parse("John Doe <jdoe@domain.com>")

        ' Attendee of meeting.
        Dim meeting1attendee1 As EmailAddress = EmailAddress.Parse("Alice <alice@company.com>")

        Dim msg As New MailMessage()
        msg.From = emailFrom
        msg.[To].Add(meeting1attendee1)
        msg.Subject = "Server backup"

        ' Create new event.
        Dim iCal As New iCalendar()

        Dim evt As [Event] = iCal.Create(Of [Event])()
        evt.Start = New iCalDateTime(DateTime.Today.AddDays(1))
        evt.End = evt.Start.AddHours(1)
        evt.IsAllDay = False
        evt.Summary = "Server backup"
        evt.Location = "Server room"

        Dim serializer As New iCalendarSerializer()

        ' Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text = serializer.SerializeToString(iCal)

        ' And send it (we use direct send here, you can send it via SMTP relay as well).
        Smtp.QuickSend(msg)
    End Sub
End Module

As you can see, the only difference from the previous sample is that it does not set attendees and iCalendar.Method = "REQUEST".

Create recurring event

This sample creates an event which will occur daily within 5 days period, once added to the calendar of the person which receives this e-mail:

  • C#
  • VB
using System;
using MailBee.Mime;
using MailBee.SmtpMail;
using iCal;
using iCal.Serialization.iCalendar;

class SendRecurring
{
    static void Main(string[] args)
    {
        string emailFrom = "John Doe <jdoe@domain.com>";
        string emailTo = "Alice <alice@company.com>";

        MailMessage msg = new MailMessage();
        msg.From.AsString = emailFrom;
        msg.To.AddFromString(emailTo);
        msg.Subject = "iCal repeated event";

        // Create new event.
        iCalendar iCal = new iCalendar();

        Event evt = iCal.Create<Event>();
        evt.Start = new iCalDateTime(DateTime.Today.AddDays(1));
        evt.IsAllDay = false;

        // Repeat every day, 5 days total.
        RecurrencePattern rp = new RecurrencePattern(FrequencyType.Daily, 1);
        rp.Count = 5;

        evt.RecurrenceRules.Add(rp);
        evt.Summary = "Server maintenance";
        evt.Location = "Room 814";

        iCalendarSerializer serializer = new iCalendarSerializer();

        // Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text =
            serializer.SerializeToString(iCal);

        // Send this iCal event. We use direct send, you can modify it to use
        // SMTP relay server (see Smtp.Send method for details).
        Smtp.QuickSend(msg);
    }
}

Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports iCal
Imports iCal.Serialization.iCalendar

Module SendRecurring
    Sub Main(ByVal args As String())
        Dim emailFrom As String = "John Doe <jdoe@domain.com>"
        Dim emailTo As String = "Alice <alice@company.com>"

        Dim msg As New MailMessage()
        msg.From.AsString = emailFrom
        msg.[To].AddFromString(emailTo)
        msg.Subject = "iCal repeated event"

        ' Create new event.
        Dim iCal As New iCalendar()

        Dim evt As [Event] = iCal.Create(Of [Event])()
        evt.Start = New iCalDateTime(DateTime.Today.AddDays(1))
        evt.IsAllDay = False

        ' Repeat every day, 5 days total.
        Dim rp As New RecurrencePattern(FrequencyType.Daily, 1)
        rp.Count = 5

        evt.RecurrenceRules.Add(rp)
        evt.Summary = "Server maintenance"
        evt.Location = "Room 814"

        Dim serializer As New iCalendarSerializer()

        ' Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text = _
            serializer.SerializeToString(iCal)

        ' Send this iCal event. We use direct send, you can modify it to use
        ' SMTP relay server (see Smtp.Send method for details).
        Smtp.QuickSend(msg)
    End Sub
End Module

You can also make events which occur with another recurring pattern (e.g. weekly or repeat without ending date).

For instance, to repeat the event every day (without ending date), just do not set RecurrencePattern.Count property:

  • C#
  • VB
RecurrencePattern rp = new RecurrencePattern(FrequencyType.Daily, 1);

Dim rp As New RecurrencePattern(FrequencyType.Daily, 1)

The below shows RecurrencePattern setting to make event trigger every working day (from Mon to Fri):

  • C#
  • VB
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Daily;
rp.ByDay.Add(new WeekDay(DayOfWeek.Monday));
rp.ByDay.Add(new WeekDay(DayOfWeek.Tuesday));
rp.ByDay.Add(new WeekDay(DayOfWeek.Wednesday));
rp.ByDay.Add(new WeekDay(DayOfWeek.Thursday));
rp.ByDay.Add(new WeekDay(DayOfWeek.Friday));

Dim rp As New RecurrencePattern()
rp.Frequency = FrequencyType.Daily
rp.ByDay.Add(New WeekDay(DayOfWeek.Monday))
rp.ByDay.Add(New WeekDay(DayOfWeek.Tuesday))
rp.ByDay.Add(New WeekDay(DayOfWeek.Wednesday))
rp.ByDay.Add(New WeekDay(DayOfWeek.Thursday))
rp.ByDay.Add(New WeekDay(DayOfWeek.Friday))

This one triggers on first Monday of every month:

  • C#
  • VB
RecurrencePattern rp = new RecurrencePattern();
rp.Frequency = FrequencyType.Monthly;
rp.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First));

Dim rp As New RecurrencePattern()
rp.Frequency = FrequencyType.Monthly
rp.ByDay.Add(New WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First))

Using this approach, you can create any complex recurrence patterns.

Create appointment with reminder

You can create appointments and normal events with reminders. The e-mail program of the person which received the e-mail with such event will remind this person about upcoming event beforehand. This code can create both meeting request (appointment) and regular event. Set isAppointment to true or false to control this.

  • C#
  • VB
using System;
using MailBee.Mime;
using MailBee.SmtpMail;
using iCal;
using iCal.Serialization.iCalendar;

class AppointmentWithReminder
{
    static void Main(string[] args)
    {
        EmailAddress emailFrom = EmailAddress.Parse("Event Creator <jdoe@domain.com>");

        // Attendees of meeting.
        EmailAddress meeting1attendee1 = EmailAddress.Parse("Person1 <alice@company.com>");
        EmailAddress meeting1attendee2 = EmailAddress.Parse("Person2 <john@domain.com>");

        // SMTP settings.
        string smtpServer = "smtp.domain.com";
        int smtpPort = 25; // Specify 465 for SSL.
        string username = "jdoe";
        string password = "secret";

        Smtp mailer = new Smtp();
        SmtpServer srv = new SmtpServer(smtpServer, username, password);
        srv.Port = smtpPort;
        mailer.SmtpServers.Add(srv);

        bool isAppointment = false; // Set to true to make it appointment.

        MailMessage msg = mailer.Message;
        msg.From = emailFrom;
        msg.To.Add(meeting1attendee1);
        msg.To.Add(meeting1attendee2);
        msg.Subject = "iCal event with reminder";

        // Create new event.
        iCalendar iCal = new iCalendar();

        if (isAppointment)
        {
            iCal.Method = "REQUEST";
        }

        Event evt1 = iCal.Create<Event>();
        evt1.Start = new iCalDateTime(DateTime.Now.AddMinutes(10));
        evt1.End = evt1.Start.AddHours(1);
        evt1.IsAllDay = false;
        evt1.Summary = "Project meeting";
        evt1.Location = "Conference room";

        // Configure reminder, triggers 15 minutes before the event.
        Alarm alrm1 = new Alarm();
        alrm1.Trigger = new Trigger(new TimeSpan(-15 * 10000000));
        alrm1.Action = AlarmAction.Display;
        alrm1.Description = "Project meeting Reminder";
        evt1.Alarms.Add(alrm1);

        if (isAppointment)
        {
            // Add recipients for appointment.

            Attendee att1 = new Attendee("mailto:" + meeting1attendee1.Email);
            att1.RSVP = true;
            att1.CommonName = meeting1attendee1.Email;
            evt1.Attendees.Add(att1);

            Attendee att2 = new Attendee("mailto:" + meeting1attendee1.Email);
            att2.RSVP = true;
            att2.CommonName = meeting1attendee2.Email;
            evt1.Attendees.Add(att2);
        }

        iCalendarSerializer serializer = new iCalendarSerializer();

        // Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text =
            serializer.SerializeToString(iCal);

        // And send it.
        mailer.Send();

        // This sample does not save Unique-ID of the appointment.
        // See "Create iCal appointment" sample for this.
    }
}

Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports iCal
Imports iCal.Serialization.iCalendar

Module AppointmentWithReminder
    Sub Main(ByVal args As String())
        Dim emailFrom As EmailAddress = _
            EmailAddress.Parse("Event Creator <jdoe@domain.com>")

        ' Attendees of meeting.
        Dim meeting1attendee1 As EmailAddress = _
            EmailAddress.Parse("Person1 <alice@company.com>")
        Dim meeting1attendee2 As EmailAddress = _
            EmailAddress.Parse("Person2 <john@domain.com>")

        ' SMTP settings.
        Dim smtpServer As String = "smtp.domain.com"
        Dim smtpPort As Integer = 25
        ' Specify 465 for SSL.
        Dim username As String = "jdoe"
        Dim password As String = "secret"

        Dim mailer As New Smtp()
        Dim srv As New SmtpServer(smtpServer, username, password)
        srv.Port = smtpPort
        mailer.SmtpServers.Add(srv)

        Dim isAppointment As Boolean = False
        ' Set to true to make it appointment.
        Dim msg As MailMessage = mailer.Message
        msg.From = emailFrom
        msg.[To].Add(meeting1attendee1)
        msg.[To].Add(meeting1attendee2)
        msg.Subject = "iCal event with reminder"

        ' Create new event.
        Dim iCal As New iCalendar()

        If isAppointment Then
            iCal.Method = "REQUEST"
        End If

        Dim evt1 As [Event] = iCal.Create(Of [Event])()
        evt1.Start = New iCalDateTime(DateTime.Now.AddMinutes(10))
        evt1.End = evt1.Start.AddHours(1)
        evt1.IsAllDay = False
        evt1.Summary = "Project meeting"
        evt1.Location = "Conference room"

        ' Configure reminder, triggers 15 minutes before the event.
        Dim alrm1 As New Alarm()
        alrm1.Trigger = New Trigger(New TimeSpan(-15 * 10000000))
        alrm1.Action = AlarmAction.Display
        alrm1.Description = "Project meeting Reminder"
        evt1.Alarms.Add(alrm1)

        If isAppointment Then
            ' Add recipients for appointment.

            Dim att1 As New Attendee("mailto:" & meeting1attendee1.Email)
            att1.RSVP = True
            att1.CommonName = meeting1attendee1.Email
            evt1.Attendees.Add(att1)

            Dim att2 As New Attendee("mailto:" & meeting1attendee1.Email)
            att2.RSVP = True
            att2.CommonName = meeting1attendee2.Email
            evt1.Attendees.Add(att2)
        End If

        Dim serializer As New iCalendarSerializer()

        ' Add iCal as BodyPart.
        msg.BodyParts.Add("text/calendar; method = REQUEST").Text = _
            serializer.SerializeToString(iCal)

        ' And send it.
        mailer.Send()

        ' This sample does not save Unique-ID of the appointment.
        ' See "Create iCal appointment" sample for this.
    End Sub
End Module

You can also set what action will take place when an alarm triggers. Usually (like in this sample), a message dialog will be displayed. However, you can use other values for Alarm.Action property to send a notification e-mail, for example.

Respond to appointment request

This console sample gets the last e-mail from a POP3 inbox and, if it's a meeting request, let's the user accept or decline this request by sending iCal response to the original sender.

In other words, this sample allows your application do what Outlook does when it receives an e-mail containing a meeting request.

  • C#
  • VB
using System;
using System.IO;
using System.Collections.Generic;
using MailBee.Mime;
using MailBee.SmtpMail;
using MailBee.Pop3Mail;
using iCal;
using iCal.Serialization.iCalendar;

class AcceptMeetingRequest
{
    static void Main(string[] args)
    {
        // E-mail address of attendee. It's assumed you as attendee receive a meeting request
        // to this e-mail address, and will send your reply (which denotes whether you accept
        // or decline the request) from this address.
        string myEmail = "jdoe@domain.com";

        // SMTP settings.
        string smtpServer = "smtp.domain.com";
        int smtpPort = 25; // Specify 465 for SSL.
        string username = "jdoe";
        string password = "secret";

        Smtp mailer = new Smtp();
        SmtpServer srv = new SmtpServer(smtpServer, username, password);
        srv.Port = smtpPort;
        mailer.SmtpServers.Add(srv);

        // Download last e-mail from POP3 account.
        MailMessage appointmentMsg = Pop3.QuickDownloadMessage("pop.domain.com", "jdoe", "secret", -1);

        Console.WriteLine("Email From: " + appointmentMsg.From.ToString());
        Console.WriteLine("Email To: " + appointmentMsg.To.ToString());
        Console.WriteLine("Subject: " + appointmentMsg.Subject);

        // For each part of the message, examine if it contains a meeting request,
        // and let the user know if it does.
        foreach (TextBodyPart part in appointmentMsg.BodyParts)
        {
            if (part.IsICalendar)
            {
                IICalendarCollection iiCal = iCalendar.LoadFromStream(new StringReader(part.Text));

                for (int i = 0; i < iiCal.Count; i++)
                {
                    if (iiCal[i].Method.ToUpper() == "REQUEST")
                    {
                        for (int j = 0; j < iiCal[i].Events.Count; j++)
                        {
                            IList<IAttendee> att = iiCal[i].Events[j].Attendees;

                            for (int k = 0; k < att.Count; k++)
                            {
                                if (att[k].AssociatedObject.Name.ToUpper() == "ATTENDEE" &&
                                    att[k].Value.AbsoluteUri.ToLower() == "mailto:" + myEmail.ToLower() &&
                                    att[k].RSVP)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("Summary: " + iiCal[i].Events[j].Summary);
                                    Console.WriteLine("Location: " + iiCal[i].Events[j].Location);

                                    MailMessage msg = mailer.Message;
                                    msg.Reset();
                                    msg.From.AsString = myEmail;
                                    if (appointmentMsg.From.Email != string.Empty)
                                    {
                                        msg.To.Add(appointmentMsg.From.Email);
                                    }
                                    else
                                    {
                                        msg.To.AddFromString(appointmentMsg.Headers["Sender"]);
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine("Press 'y' to Accept, 'n' to Decline, 't' to Tentative,");
                                    Console.WriteLine("or any other key to skip responding to this request,");
                                    Console.WriteLine("and press Enter");
                                    string respond = Console.ReadLine().ToLower();

                                    if (respond == "y" || respond == "n" || respond == "t")
                                    {
                                        // Create new event with meeting response.
                                        iCalendar iCalResp = new iCalendar();
                                        iCalResp.Method = "REPLY";

                                        Event evtResp = iCalResp.Create<Event>();

                                        evtResp.Class = "PUBLIC";
                                        evtResp.UID = iiCal[i].UniqueComponents[0].UID;
                                        evtResp.Location = iiCal[i].Events[j].Location;
                                        evtResp.Summary = iiCal[i].Events[j].Summary;

                                        // Add recipient for appointment (the sender of the meeting request).
                                        Attendee attResp = new Attendee("mailto:" + appointmentMsg.From.Email);

                                        switch (respond)
                                        {
                                            case "y":
                                                msg.Subject = "Accepted: " + iiCal[i].Events[j].Summary;
                                                attResp.ParticipationStatus = "ACCEPTED";
                                                break;
                                            case "n":
                                                msg.Subject = "Declined: " + iiCal[i].Events[j].Summary;
                                                attResp.ParticipationStatus = "DECLINED";
                                                break;
                                            case "t":
                                                msg.Subject = "Tentative: " + iiCal[i].Events[j].Summary;
                                                attResp.ParticipationStatus = "TENTATIVE";
                                                break;
                                        }

                                        evtResp.Attendees.Add(attResp);

                                        iCalendarSerializer serializer = new iCalendarSerializer();

                                        // Add iCal as BodyPart.
                                        msg.BodyParts.Add("text/calendar; method=REPLY").Text =
                                            serializer.SerializeToString(iCalResp);

                                        // Send confirmation.
                                        mailer.Send();
                                    }

                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Imports System.IO
Imports System.Collections.Generic
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports MailBee.Pop3Mail
Imports iCal
Imports iCal.Serialization.iCalendar

Module AcceptMeetingRequest
    Sub Main(ByVal args As String())
        ' E-mail address of attendee. It's assumed you as attendee receive a meeting request
        ' to this e-mail address, and will send your reply (which denotes whether you accept
        ' or decline the request) from this address.
        Dim myEmail As String = "jdoe@domain.com"

        ' SMTP settings.
        Dim smtpServer As String = "smtp.domain.com"
        Dim smtpPort As Integer = 25 ' Specify 465 for SSL.
        Dim username As String = "jdoe"
        Dim password As String = "secret"

        Dim mailer As New Smtp()
        Dim srv As New SmtpServer(smtpServer, username, password)
        srv.Port = smtpPort
        mailer.SmtpServers.Add(srv)

        ' Download last e-mail from POP3 account.
        Dim appointmentMsg As MailMessage = Pop3.QuickDownloadMessage("pop.domain.com", "jdoe", "secret", -1)

        Console.WriteLine("Email From: " & appointmentMsg.From.ToString())
        Console.WriteLine("Email To: " & appointmentMsg.[To].ToString())
        Console.WriteLine("Subject: " & appointmentMsg.Subject)

        ' For each part of the message, examine if it contains a meeting request,
        ' and let the user know if it does.
        For Each part As TextBodyPart In appointmentMsg.BodyParts
            If part.IsICalendar Then
                Dim iiCal As IICalendarCollection = iCalendar.LoadFromStream(New StringReader(part.Text))

                For i As Integer = 0 To iiCal.Count - 1
                    If iiCal(i).Method.ToUpper() = "REQUEST" Then
                        For j As Integer = 0 To iiCal(i).Events.Count - 1
                            Dim att As IList(Of IAttendee) = iiCal(i).Events(j).Attendees

                            For k As Integer = 0 To att.Count - 1
                                If att(k).AssociatedObject.Name.ToUpper() = "ATTENDEE" AndAlso _
                                    att(k).Value.AbsoluteUri.ToLower() = "mailto:" & myEmail.ToLower() AndAlso _
                                    att(k).RSVP Then
                                    Console.WriteLine()
                                    Console.WriteLine("Summary: " & iiCal(i).Events(j).Summary)
                                    Console.WriteLine("Location: " & iiCal(i).Events(j).Location)

                                    Dim msg As MailMessage = mailer.Message
                                    msg.Reset()
                                    msg.From.AsString = myEmail
                                    If appointmentMsg.From.Email <> String.Empty Then
                                        msg.[To].Add(appointmentMsg.From.Email)
                                    Else
                                        msg.[To].AddFromString(appointmentMsg.Headers("Sender"))
                                    End If

                                    Console.WriteLine()
                                    Console.WriteLine("Press 'y' to Accept, 'n' to Decline, 't' to Tentative,")
                                    Console.WriteLine("or any other key to skip responding to this request,")
                                    Console.WriteLine("and press Enter")
                                    Dim respond As String = Console.ReadLine().ToLower()

                                    If respond = "y" OrElse respond = "n" OrElse respond = "t" Then
                                        ' Create new event with meeting response.
                                        Dim iCalResp As New iCalendar()
                                        iCalResp.Method = "REPLY"

                                        Dim evtResp As [Event] = iCalResp.Create(Of [Event])()

                                        evtResp.[Class] = "PUBLIC"
                                        evtResp.UID = iiCal(i).UniqueComponents(0).UID
                                        evtResp.Location = iiCal(i).Events(j).Location
                                        evtResp.Summary = iiCal(i).Events(j).Summary

                                        ' Add recipient for appointment (the sender of the meeting request).
                                        Dim attResp As New Attendee("mailto:" & appointmentMsg.From.Email)

                                        Select Case respond
                                            Case "y"
                                                msg.Subject = "Accepted: " & iiCal(i).Events(j).Summary
                                                attResp.ParticipationStatus = "ACCEPTED"
                                                Exit Select
                                            Case "n"
                                                msg.Subject = "Declined: " & iiCal(i).Events(j).Summary
                                                attResp.ParticipationStatus = "DECLINED"
                                                Exit Select
                                            Case "t"
                                                msg.Subject = "Tentative: " & iiCal(i).Events(j).Summary
                                                attResp.ParticipationStatus = "TENTATIVE"
                                                Exit Select
                                        End Select

                                        evtResp.Attendees.Add(attResp)

                                        Dim serializer As New iCalendarSerializer()

                                        ' Add iCal as BodyPart.
                                        msg.BodyParts.Add("text/calendar; method=REPLY").Text = _
                                            serializer.SerializeToString(iCalResp)

                                        ' Send confirmation.
                                        mailer.Send()
                                    End If
                                End If
                            Next
                        Next
                    End If
                Next
            End If
        Next
    End Sub
End Module

We assume MailBee.Global.LicenseKey is already set in app.config, registry, etc. If not, you can set it in the code.

Analyze responses to appointment request

This sample shows how to find out if the incoming e-mail is a response to a meeting request and then match this response and the originating meeting request. For a change, we use IMAP as incoming e-mail protocol.

To check if we got a match, we lookup of the iCal Unique-ID of the incoming response in the list of stored meeting request attendees and assigned iCal Unique-IDs (which we created in Create iCal appointment sample).

Once we got a match, we update the list of stored meeting request information with the participation status we extracted from the response.

  • C#
  • VB
using System;
using System.IO;
using System.Collections;
using System.Text;
using MailBee.Mime;
using MailBee.ImapMail;
using iCal;

// This sample gets the last e-mail from an IMAP inbox. Then, it checks if
// this e-mail is a meeting response to a meeting request we previously sent in
// "Create iCal appointment" sample. If it is, we update our database with the
// new information (whether the attendee has accepted or declined the request).

class AnalyzeMeetingResponse
{
    static void Main(string[] args)
    {
        // Load last e-mail from IMAP inbox.
        MailMessage appointmentMsg =
            Imap.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", "Inbox", -1);

        string[] lines = null;
        bool updated = false;

        // Check all parts of the e-mail if they contain meeting response from attendees.
        foreach (TextBodyPart part in appointmentMsg.BodyParts)
        {
            if (part.IsICalendar)
            {
                IICalendarCollection iiCal = iCalendar.LoadFromStream(new StringReader(part.Text));

                for (int i = 0; i < iiCal.Count; i++)
                {
                    if (iiCal[i].Method.ToUpper() == "REPLY")
                    {
                        if (lines == null)
                        {
                            // We assume the file exists and user has read/write access.
                            // The file is in the following format:
                            // appointment's iCal Unique-ID;attendee e-mail address;status or empty
                            lines = File.ReadAllLines(@"C:\Temp\eventUid.txt");
                        }

                        for (int j = 0; j < lines.Length; j++)
                        {
                            string[] parts = lines[j].Split(new char[] { ';' });

                            // Look up for the iCal Unique-ID and e-mail address from the
                            // meeting response in our database (where we saved them earler when
                            // created the original meeting request).
                            if (iiCal[i].UniqueComponents[0].UID.ToLower() == parts[0] &&
                                appointmentMsg.From.Email.ToLower() == parts[1])
                            {
                                Console.WriteLine("From: " + appointmentMsg.From.ToString());
                                Console.WriteLine("Subject: " + appointmentMsg.Subject);
                                Console.WriteLine();

                                Console.WriteLine("Event: " + iiCal[i].Events[0].Summary);
                                Console.WriteLine("Status: " +
                                    iiCal[i].Events[0].Attendees[0].ParticipationStatus);

                                // Update our database with the participation status which we extracted
                                // from the meeting response e-mail.
                                lines[j] = parts[0] + ';' + parts[1] + ';' +
                                    iiCal[i].Events[0].Attendees[0].ParticipationStatus;

                                updated = true;
                            }
                        }
                    }
                }
            }
        }

        if (updated)
        {
            // Write acceptance status to database. We use text file here for simplicity,
            // real-world apps will probably use SQL database.
            File.WriteAllLines(@"C:\Temp\eventUid.txt", lines);
        }
    }
}

Imports System.IO
Imports System.Collections
Imports System.Text
Imports MailBee.Mime
Imports MailBee.ImapMail
Imports iCal

' This sample gets the last e-mail from an IMAP inbox. Then, it checks if
' this e-mail is a meeting response to a meeting request we previously sent in
' "Create iCal appointment" sample. If it is, we update our database with the
' new information (whether the attendee has accepted or declined the request).

Module AnalyzeMeetingResponse
    Sub Main(ByVal args As String())
        ' Load last e-mail from IMAP inbox.
        Dim appointmentMsg As MailMessage = _
            Imap.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", "Inbox", -1)

        Dim lines As String() = Nothing
        Dim updated As Boolean = False

        ' Check all parts of the e-mail if they contain meeting response from attendees.
        For Each part As TextBodyPart In appointmentMsg.BodyParts
            If part.IsICalendar Then
                Dim iiCal As IICalendarCollection = _
                    iCalendar.LoadFromStream(New StringReader(part.Text))

                For i As Integer = 0 To iiCal.Count - 1
                    If iiCal(i).Method.ToUpper() = "REPLY" Then
                        If lines Is Nothing Then
                            ' We assume the file exists and user has read/write access.
                            ' The file is in the following format:
                            ' appointment's iCal Unique-ID;attendee e-mail address;status or empty
                            lines = File.ReadAllLines("C:\Temp\eventUid.txt")
                        End If

                        For j As Integer = 0 To lines.Length - 1
                            Dim parts As String() = lines(j).Split(New Char() {";"c})

                            ' Look up for the iCal Unique-ID and e-mail address from the
                            ' meeting response in our database (where we saved them earler when
                            ' created the original meeting request).
                            If iiCal(i).UniqueComponents(0).UID.ToLower() = parts(0) AndAlso _
                                appointmentMsg.From.Email.ToLower() = parts(1) Then
                                Console.WriteLine("From: " & appointmentMsg.From.ToString())
                                Console.WriteLine("Subject: " & appointmentMsg.Subject)
                                Console.WriteLine()

                                Console.WriteLine("Event: " & iiCal(i).Events(0).Summary)
                                Console.WriteLine("Status: " & _
                                    iiCal(i).Events(0).Attendees(0).ParticipationStatus)

                                ' Update our database with the participation status
                                ' which we extracted from the meeting response e-mail.
                                lines(j) = parts(0) & ";" & parts(1) & ";" & _
                                    iiCal(i).Events(0).Attendees(0).ParticipationStatus

                                updated = True
                            End If
                        Next
                    End If
                Next
            End If
        Next

        If updated Then
            ' Write acceptance status to database. We use text file here for simplicity,
            ' real-world apps will probably use SQL database.
            File.WriteAllLines("C:\Temp\eventUid.txt", lines)
        End If
    End Sub
End Module

We assume MailBee.Global.LicenseKey is already set in app.config, registry, etc. If not, you can set it in the code.

Send feedback to AfterLogic


OAuth 2.0 in Windows, .NET Core, and ASP.NET MVC apps

You can use MailBee.NET Objects to check and send mail via OAuth 2.0 with Google and Microsoft providers including Gmail, Outlook.com, Live.com, Hotmail.com. In the future, if more providers implement XOAUTH2 extension in their IMAP and SMTP protocols, they will be supported as well.

OAuth 2.0 is a complex topic, and this tutorial aims to address as many concerns as possible, including:

  • Registering projects on Google and Microsoft web sites.
  • Support of Google Service Accounts (which makes it very easy to use OAuth 2.0 with Google Apps).
  • Google API and DotNetOpenAuth usage.
  • Getting the e-mail address and name of the user.
  • IMAP and SMTP access to the user's account via XOAUTH2 authentication.
  • Compatibility with OWIN/Katana and ASP.NET Identity 2.0 in ASP.NET MVC5 applications.
  • Configuring IIS Express to simplify local development of OAuth-enabled web applications, with HTTPS support.
  • Refreshing access tokens to enable long-lived applications.
  • Exchanging access tokens between ASP.NET and non-web applications (for background applications doing periodic activity in a user's mailboxes without that user's interaction).
  • Asynchronous and synchronous versions of the code (if possible).
  • For desktop and console applications, automating the process of passing the authorization code from the provider's web site to the application (instead of a user's manual input).

ASP.NET, desktop and console the samples are available for both C# and VB and target .NET Framework v4.5 or newer.

.NET Core samples target ASP.NET Core 2.0 (web) and .NET Core 2.0 (console), available in C# version only. Tested with .NET Core 2.2 as well.

ASP.NET samples require Visual Studio 2013 Update 3 or newer (they are using the latest version of ASP.NET MVC template, MVC5 at the moment of writing).

ASP.NET Core 2.0 sample was developed with Visual Studio 2017 15.9.

Installed applications for .NET Franework (console and WinForms samples) require Visual Studio 2012 at least.

Please select the article which corresponds your case:

  • Microsoft accounts for installed applications
  • Microsoft accounts for installed applications (installed applications running HttpListener)
  • Google regular accounts for installed applications
  • Google "Service Accounts" for installed and web applications
  • Microsoft and Google regular accounts for MVC5 web applications
  • OAuth 2.0 for Universal Windows apps

All C# and VB samples discussed in this tutorial are shipped with MailBee.NET Objects installer and get installed into My Documents\MailBee.NET Objects\Samples folder.

ASP.NET and ASP.NET Core samples:

  • Samples\ASP.NET\cs_2013_oauth_samples
  • Samples\ASP.NET\vb_2013_oauth_samples
  • Samples\ASP.NET\cs_netcore_oauth_samples

WinForms and console samples for .NET Framework 4.5 or newer, .NET Core 2.0 or newer, Universal Windows (Windows 10 Fall Creators Update or newer):

  • Samples\WinForms\.NET 4.5 OAuth
  • Samples\WinForms\.NET Core 2.0

Samples\WinForms.NET 4.5 OAuth\C#\ReadAspNetUsers and Samples\WinForms\.NET Core 2.0\C#\ReadAspNetUsers apps are special in that they are console but work with the same users database as ASP.NET/ASP.NET Core samples and demonstrate how web and non-web OAuth apps can interoperate.

Send feedback to AfterLogic


OAuth 2.0 for Microsoft Accounts (installed applications)

This is the original version of the tutorial. It does not support .NET Core (only .NET Framework is supported) and does not support authorization token exchange via a local web server (which is often the most convenient method possible). The revised application is explained in OAuth 2.0 for Microsoft Accounts (installed applications running HttpListener) topic.

The idea is to create a Windows application which can access Outlook.com, Hotmail.com or Live.com account of a user via IMAP and SMTP without knowing the password of this user.

  • .NET Core and UWP/UAP notes
  • Register Microsoft project
  • Create application in Visual Studio
  • Using MailBee.NET and DotNetOpenAuth to access a Microsoft e-mail account
  • Autodetecting the user's e-mail address
  • Using Offline mode and refresh tokens
  • Automating authorization code delivery from the browser to your app
  • Obtaining authorization code with WebBrowser control
  • Obtaining authorization code using the default browser
  • Revoking Microsoft access token
  • Sample projects overview
  • Get source code

.NET Core and UWP/UAP notes

This is a .NET Framework version of this guide (it uses DotNetOpenAuth library which exists for .NET Framework only). If you're on .NET Core, see this version. Universal Windows sample is explained in OAuth 2.0 for Universal Windows apps guide.

Register Microsoft project

Create an application in Application Registration Portal. You may need to create an account there first.

For OAuth 2.0, create a Live SDK application. Click Add an app in Live SDK applications section.

On the next screen, click Add Platform and select Native application, then save changes.

You may also add Web platform as well. This is not required by gives you the ability to use the simplified approach for getting OAuth authorization code from Microsoft server (so-called local server, see below).

Application ID (Client ID) and password (application secret) are there as well.

Make sure to add the required permissions (scopes) as well:

Microsoft is changing things there often. Sometimes, Live SDK app simply doesn't work and you may try creating a Converged application. Also, you may be asked to use Azure portal instead of apps.dev.microsoft.com site. At the moment of writing, Azure portal was not stable enough for that.

Create application in Visual Studio

Now create a console application in Visual Studio. Alternatively, you can open OAuthConsoleApps sample project and set MicrosoftEasyLogin class as startup object in the project properties.

If you need WinForms version, check MicrosoftOAuthWinForms sample.

Then proceed to adding the required dependencies. One NuGet package manager console and type:

Install-Package DotNetOpenAuth
Install-Package Newtonsoft.Json
Install-Package MailBee.NET

Alternatively, you can use Add Reference to plug MailBee.NET.dll to your project. It resides in Assemblies/Framework/Extensions in case if MailBee.NET Objects is fully installed in the system, or use Browse if you have just the .DLL file.

The sample does not use ExternalProviders library (like it's done in web apps version of OAuth 2.0 tutorial). The library uses ASP.NET Identity database as storage of access tokens and related data but we're not using that database in the sample for this article.

Using MailBee.NET and DotNetOpenAuth to access a Microsoft e-mail account

That's what we need to do in order to get access to the user's e-mails:

  • Request authorization from Microsoft to access the scopes of IMAP/SMTP and the e-mail address (areas of authorization are called scopes).
  • Do the authorization using Client ID and Client Secret issued by Microsoft to our application. This will open the browser window with Microsoft web page asking the user to authorize our application. If the user agrees, Microsoft delivers the authorization code by redirecting to the page which has this code in the URL.
  • Then we request Microsoft server again to get the access token using the authorization code provided (the user will have to manually copy/paste the authorization code from the URL to our app).
  • Use the access token and the e-mail address of the user (we assume it's know from other sources) to build XOAUTH2 key.
  • Use MailBee.NET to connect to imap-mail.outlook.com (smtp-mail.outlook.com for SMTP) and log in using XOAUTH2 authentication method. The same mail server name works for all Microsoft services including Hotmail.com and Live.com domains.
  • Do whatever needed in the user's mailbox (IMAP), or send an e-mail (SMTP).

In subsequent topics we'll also add autodetection of the user's e-mail address, programmatic delivery of the authorization code from the browser to the application, and more. For now, let's stick to the simplest implementation.

  • C#
  • VB
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using DotNetOpenAuth.OAuth2;
using MailBee;
using MailBee.ImapMail;

// This program shows how to get and use OAuth access token to check a user's inbox on Microsoft servers.
//
// To run this program, select "MicrosoftEasyLogin" in Project / project's Properties / Application tab / Startup object.
//
// What this sample does:
// - Gets OAuth access token from Microsoft OAuth server at https://login.live.com (works for outlook.com, hotmail.com,
// live.com and other services). Offline access is not requested, the access token received is not persisted.
// To get the token, it first starts the browser where the user is supposed to complete all the steps and get authorization code.
// After that, the user must copy/paste that code into the console of this app. Upon the successful authorization, the sample
// requests the access token from Microsoft server using the authorization code.
//
// - Checks the user's inbox via IMAP on outlook.com mail server using XOAUTH2 authentication in MailBee.NET Objects.
// outlook.com mail server can also be used for hotmail.com and live.com and other Microsoft domains.
//
// This sample is independent from OAuthMVC5 and ReadAspNetUsers samples, it does not store tokens anywhere
// (neither it reads them from any storage).
public class MicrosoftEasyLogin
{
    private static string GetAccessToken(string clientID, string clientSecret, string code)
    {
        UserAgentClient consumer;
        IAuthorizationState grantedAccess;

        StringDictionary parameters2 = new StringDictionary();
        parameters2.Add(OAuth2.RedirectUriKey, "https://login.live.com/oauth20_desktop.srf");

        AuthorizationServerDescription server = new AuthorizationServerDescription();
        server.AuthorizationEndpoint = new Uri("https://login.live.com/oauth20_authorize.srf");
        server.TokenEndpoint = new Uri("https://login.live.com/oauth20_token.srf");
        server.ProtocolVersion = ProtocolVersion.V20;

        consumer = new UserAgentClient(server, clientID, clientSecret);

        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);

        IAuthorizationState authorizationState = new AuthorizationState(null);

        if (parameters2.ContainsKey(OAuth2.RedirectUriKey))
        {
            authorizationState.Callback = new Uri(parameters2[OAuth2.RedirectUriKey]);
        }

        try
        {
            grantedAccess = consumer.ProcessUserAuthorization(
                new Uri("http://example.com/?code=" + code), authorizationState);
        }
        catch (DotNetOpenAuth.Messaging.ProtocolException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }

        return grantedAccess.AccessToken;
    }

    public static void Main(string[] args)
    {
        // You get these at https://account.live.com/developers/applications/create
        string clientID = "Your Client ID, like 000000001A2B3456";
        string clientSecret = "Your Client Secret, like 0a1b2c-3d4e5f";

        // E-mail address can be of any MS domain: hotmail.com, outlook.com, live.com, etc. All MS services will work.
        // See MicrosoftLogin advanced sample on how to autodetect the e-mail address (in particular, GetUserData call)
        // and don't forget to change the scope from "wl.imap" to "wl.imap,wl.emails" at least.
        string userEmail = "user@outlook.com";

        OAuth2 myOAuth2 = new OAuth2(clientID, clientSecret);

        StringDictionary parameters1 = new StringDictionary();
        parameters1.Add(OAuth2.Scope, "wl.imap"); // Works for both IMAP and SMTP.
        parameters1.Add(OAuth2.RedirectUriKey, "https://login.live.com/oauth20_desktop.srf");
        parameters1.Add(OAuth2.ResponseTypeKey, "code");

        string url = myOAuth2.AuthorizeToken("https://login.live.com/oauth20_authorize.srf", parameters1);
        Process.Start(url);

        Console.Write("Please enter the authorization code: ");
        string authorizationCode = Console.ReadLine().Trim();

        if (string.IsNullOrEmpty(authorizationCode))
        {
            Console.WriteLine("No authorization code provided");
            return;
        }

        string accessToken = GetAccessToken(clientID, clientSecret, authorizationCode);
        if (accessToken == null)
        {
            Console.WriteLine("Can't get the access token");
            return;
        }

        string imapXOAuthKey = OAuth2.GetXOAuthKeyStatic(userEmail, accessToken);

        // Uncomment and set your key if you haven't specified it in app.config or Windows registry.
        // MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here";

        Imap imp = new Imap();

        // Logging is not necessary but useful for debugging.
        imp.Log.Filename = "C:\\Temp\\log.txt";
        imp.Log.HidePasswords = false;
        imp.Log.Enabled = true;
        imp.Log.Clear();

        imp.Connect("imap-mail.outlook.com", 993);
        imp.Login(null, imapXOAuthKey, AuthenticationMethods.SaslOAuth2, AuthenticationOptions.None, null);
        imp.SelectFolder("INBOX");

        Console.WriteLine(imp.MessageCount.ToString() + " message(s) in INBOX");

        imp.Disconnect();
    }
}

Imports System.Collections.Specialized
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports MailBee
Imports MailBee.ImapMail

' This program shows how to get and use OAuth access token to check a user's inbox on Microsoft servers.
'
' To run this program, select "MicrosoftEasyLogin" in Project / project's Properties / Application tab / Startup object.
'
' What this sample does:
' - Gets OAuth access token from Microsoft OAuth server at https://login.live.com (works for outlook.com, hotmail.com,
' live.com and other services). Offline access is not requested, the access token received is not persisted.
' To get the token, it first starts the browser where the user is supposed to complete all the steps and get authorization code.
' After that, the user must copy/paste that code into the console of this app. Upon the successful authorization, the sample
' requests the access token from Microsoft server using the authorization code.
'
' - Checks the user's inbox via IMAP on outlook.com mail server using XOAUTH2 authentication in MailBee.NET Objects.
' outlook.com mail server can also be used for hotmail.com and live.com and other Microsoft domains.
'
' This sample is independent from OAuthMVC5 and ReadAspNetUsers samples, it does not store tokens anywhere
' (neither it reads them from any storage).
Public Class MicrosoftEasyLogin
    Private Shared Function GetAccessToken(clientID As String, clientSecret As String, code As String) As String
        Dim consumer As UserAgentClient
        Dim grantedAccess As IAuthorizationState

        Dim parameters2 As New StringDictionary()
        parameters2.Add(OAuth2.RedirectUriKey, "https://login.live.com/oauth20_desktop.srf")

        Dim server As New AuthorizationServerDescription()
        server.AuthorizationEndpoint = New Uri("https://login.live.com/oauth20_authorize.srf")
        server.TokenEndpoint = New Uri("https://login.live.com/oauth20_token.srf")
        server.ProtocolVersion = ProtocolVersion.V20

        consumer = New UserAgentClient(server, clientID, clientSecret)

        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret)

        Dim authorizationState As IAuthorizationState = New AuthorizationState(Nothing)

        If parameters2.ContainsKey(OAuth2.RedirectUriKey) Then
            authorizationState.Callback = New Uri(parameters2(OAuth2.RedirectUriKey))
        End If

        Try
            grantedAccess = consumer.ProcessUserAuthorization(New Uri("http://example.com/?code=" & code), authorizationState)
        Catch e As DotNetOpenAuth.Messaging.ProtocolException
            Console.WriteLine(e.Message)
            Return Nothing
        End Try

        Return grantedAccess.AccessToken
    End Function

    Public Shared Sub Main(args As String())
        ' You get these at https://account.live.com/developers/applications/create
        Dim clientID As String = "Your Client ID, like 000000001A2B3456"
        Dim clientSecret As String = "Your Client Secret, like 0a1b2c-3d4e5f"

        ' E-mail address can be of any MS domain: hotmail.com, outlook.com, live.com, etc. All MS services will work.
        ' See MicrosoftLogin advanced sample on how to autodetect the e-mail address (in particular, GetUserData call)
        ' and don't forget to change the scope from "wl.imap" to "wl.imap,wl.emails" at least.
        Dim userEmail As String = "user@outlook.com"

        Dim myOAuth2 As New OAuth2(clientID, clientSecret)

        Dim parameters1 As New StringDictionary()
        parameters1.Add(OAuth2.Scope, "wl.imap") ' Works for both IMAP and SMTP.
        parameters1.Add(OAuth2.RedirectUriKey, "https://login.live.com/oauth20_desktop.srf")
        parameters1.Add(OAuth2.ResponseTypeKey, "code")

        Dim url As String = myOAuth2.AuthorizeToken("https://login.live.com/oauth20_authorize.srf", parameters1)
        Process.Start(url)

        Console.Write("Please enter the authorization code: ")
        Dim authorizationCode As String = Console.ReadLine().Trim()

        If String.IsNullOrEmpty(authorizationCode) Then
            Console.WriteLine("No authorization code provided")
            Return
        End If

        Dim accessToken As String = GetAccessToken(clientID, clientSecret, authorizationCode)
        If accessToken Is Nothing Then
            Console.WriteLine("Can't get the access token")
            Return
        End If

        Dim imapXOAuthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, accessToken)

        ' Uncomment and set your key if you haven't specified it in app.config or Windows registry.
        ' MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here"

        Dim imp As New Imap()

        ' Logging is not necessary but useful for debugging.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.HidePasswords = False
        imp.Log.Enabled = True
        imp.Log.Clear()

        imp.Connect("imap-mail.outlook.com", 993)
        imp.Login(Nothing, imapXOAuthKey, AuthenticationMethods.SaslOAuth2, AuthenticationOptions.None, Nothing)
        imp.SelectFolder("INBOX")

        Console.WriteLine(imp.MessageCount.ToString() & " message(s) in INBOX")

        imp.Disconnect()
    End Sub
End Class

This sample does not use async methods of MailBee.NET library. For async version, refer to MicrosoftOAuthWinForms sample. See Sample projects overview section for details.

Autodetecting the user's e-mail address

If you don't want to have the user to type their e-mail address manually, you can autodetect it, provided that you change the scope from wl.imap to wl.imap,wl.emails. You can also get other details of the user such as their name.

The below is the code snippet demonstrating how GetUserData method can be called, and the code snippet which implements the method itself and its supporting methods and types.

You may also need to add some using directives (Imports in VB) to make this code compile. Refer to OAuthConsoleApps\MicrosoftLogin.cs(vb) for the full list.

Usage

  • C#
  • VB
IDictionary<string, string> userData = GetUserData(authState.AccessToken);
userEmail = userData["email"];

Dim userData As IDictionary(Of String, String) = GetUserData(authState.AccessToken)
userEmail = userData("email")

Implementation

  • C#
  • VB
const string LiveGetProfileUri = "https://apis.live.net/v5.0/me?access_token=";

protected class ExtendedMicrosoftClientUserData
{
    public string FirstName { get; set; }
    public string Gender { get; set; }
    public string Id { get; set; }
    public string LastName { get; set; }
    public Uri Link { get; set; }
    public string Name { get; set; }
    public Emails Emails { get; set; }
}

protected class Emails
{
    public string Preferred { get; set; }
    public string Account { get; set; }
    public string Personal { get; set; }
    public string Business { get; set; }
}

private static readonly string[] UriRfc3986CharsToEscape = new string[] { "!", "*", "'", "(", ")" };
private static string EscapeUriDataStringRfc3986(string value)
{
    StringBuilder escaped = new StringBuilder(Uri.EscapeDataString(value));

    // Upgrade the escaping to RFC 3986, if necessary.
    for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++)
    {
        escaped.Replace(UriRfc3986CharsToEscape[i], Uri.HexEscape(UriRfc3986CharsToEscape[i][0]));
    }

    // Return the fully-RFC3986-escaped string.
    return escaped.ToString();
}

// Inspired by http://answer.techwikihow.com/154458/getting-email-oauth-authentication-microsoft.html
// Be sure to have "wl.emails" in the requested scopes if you're using this method.
private static IDictionary<string, string> GetUserData(string accessToken)
{
    ExtendedMicrosoftClientUserData graph;
    WebRequest request =
        WebRequest.Create(LiveGetProfileUri + EscapeUriDataStringRfc3986(accessToken));
    using (WebResponse response = request.GetResponse())
    {
        using (Stream responseStream = response.GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(responseStream))
            {
                string data = sr.ReadToEnd();
                graph = JsonConvert.DeserializeObject<ExtendedMicrosoftClientUserData>(data);
            }
        }
    }

    Dictionary<string, string> userData = new Dictionary<string, string>();
    userData.Add("id", graph.Id);
    userData.Add("username", graph.Name);
    userData.Add("name", graph.Name);
    userData.Add("link", graph.Link == null ? null : graph.Link.AbsoluteUri);
    userData.Add("gender", graph.Gender);
    userData.Add("firstname", graph.FirstName);
    userData.Add("lastname", graph.LastName);
    userData.Add("email", graph.Emails.Preferred);
    return userData;
}

Const LiveGetProfileUri As String = "https://apis.live.net/v5.0/me?access_token="

Protected Class ExtendedMicrosoftClientUserData
    Public Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set(value As String)
            m_FirstName = Value
        End Set
    End Property
    Private m_FirstName As String
    Public Property Gender() As String
        Get
            Return m_Gender
        End Get
        Set(value As String)
            m_Gender = Value
        End Set
    End Property
    Private m_Gender As String
    Public Property Id() As String
        Get
            Return m_Id
        End Get
        Set(value As String)
            m_Id = Value
        End Set
    End Property
    Private m_Id As String
    Public Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set(value As String)
            m_LastName = Value
        End Set
    End Property
    Private m_LastName As String
    Public Property Link() As Uri
        Get
            Return m_Link
        End Get
        Set(value As Uri)
            m_Link = Value
        End Set
    End Property
    Private m_Link As Uri
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set(value As String)
            m_Name = Value
        End Set
    End Property
    Private m_Name As String
    Public Property Emails() As Emails
        Get
            Return m_Emails
        End Get
        Set(value As Emails)
            m_Emails = Value
        End Set
    End Property
    Private m_Emails As Emails
End Class

Protected Class Emails
    Public Property Preferred() As String
        Get
            Return m_Preferred
        End Get
        Set(value As String)
            m_Preferred = Value
        End Set
    End Property
    Private m_Preferred As String
    Public Property Account() As String
        Get
            Return m_Account
        End Get
        Set(value As String)
            m_Account = Value
        End Set
    End Property
    Private m_Account As String
    Public Property Personal() As String
        Get
            Return m_Personal
        End Get
        Set(value As String)
            m_Personal = Value
        End Set
    End Property
    Private m_Personal As String
    Public Property Business() As String
        Get
            Return m_Business
        End Get
        Set(value As String)
            m_Business = Value
        End Set
    End Property
    Private m_Business As String
End Class

Private Shared ReadOnly UriRfc3986CharsToEscape As String() = New String() {"!", "*", "'", "(", ")"}
Private Shared Function EscapeUriDataStringRfc3986(value As String) As String
    Dim escaped As New StringBuilder(Uri.EscapeDataString(value))

    ' Upgrade the escaping to RFC 3986, if necessary.
    For i As Integer = 0 To UriRfc3986CharsToEscape.Length - 1
        escaped.Replace(UriRfc3986CharsToEscape(i), Uri.HexEscape(UriRfc3986CharsToEscape(i)(0)))
    Next

    ' Return the fully-RFC3986-escaped string.
    Return escaped.ToString()
End Function

' Inspired by http://answer.techwikihow.com/154458/getting-email-oauth-authentication-microsoft.html
' Be sure to have "wl.emails" in the requested scopes if you're using this method.
Private Shared Function GetUserData(accessToken As String) As IDictionary(Of String, String)
    Dim graph As ExtendedMicrosoftClientUserData
    Dim request As WebRequest = WebRequest.Create(LiveGetProfileUri & EscapeUriDataStringRfc3986(accessToken))
    Using response As WebResponse = request.GetResponse()
        Using responseStream As Stream = response.GetResponseStream()
            Using sr As New StreamReader(responseStream)
                Dim data As String = sr.ReadToEnd()
                graph = JsonConvert.DeserializeObject(Of ExtendedMicrosoftClientUserData)(data)
            End Using
        End Using
    End Using

    Dim userData As New Dictionary(Of String, String)()
    userData.Add("id", graph.Id)
    userData.Add("username", graph.Name)
    userData.Add("name", graph.Name)
    userData.Add("link", If(graph.Link Is Nothing, Nothing, graph.Link.AbsoluteUri))
    userData.Add("gender", graph.Gender)
    userData.Add("firstname", graph.FirstName)
    userData.Add("lastname", graph.LastName)
    userData.Add("email", graph.Emails.Preferred)
    Return userData
End Function

Note that it's not required to get the e-mail address of the user on every run of the application for the same user. The e-mail address of the user will never change so you can save the result once and then re-use on future runs.

Using Offline mode and refresh tokens

Microsoft access tokens are short-lived, their lifetime is just 1 hour. We can enable "Offline mode" scope when requesting authorization and get the refresh token in addition to the access token. After that, the access token can then be renewed without user interaction.

To persist access/refresh token data between sessions, any kind of data storage can be used. For instance, JSON-serialized text file. We need to implement this persistence manually as DotNetOpenAuth library does not provide any means for that (unlike Google APIs).

Instead of GetAccessToken method from the original sample, let's introduce GetOrRefreshAccessToken.

In case if you're getting error 400 from Microsoft server during consumer.RefreshAuthorization call, you'll have to disable chunked transfer encoding when making HTTP requests to the Microsoft server. This is clearly a bug in their service and the only known workaround is to modify DotNetOpenAuth library for that (more exactly, DotNetOpenAuth.OAuth.Common.dll). You can find it on Github. The file to be updated is DotNetOpenAuth.OAuth.Common\OAuth\DefaultOAuthHostFactories.cs. In CreateHttpClient(HttpMessageHandler handler) method, add client.DefaultRequestHeaders.TransferEncodingChunked = false;.

  • C#
  • VB
// Gets access and refresh token if grantedAccess is null, and returns the token data on success or null on failure.
// Refreshes the access token using the refresh token if grantedAccess is not null, and returns the token data (also
// modifying the input parameter grantedAccess) on successful renewal or null if the renewal is not required yet.
private static AuthorizationState GetOrRefreshAccessToken(
    string clientID, string clientSecret, string code, AuthorizationState grantedAccess)
{
    UserAgentClient consumer;

    // Get a new token or refresh an existing token?
    bool getMode = (grantedAccess == null);

    StringDictionary parameters2 = new StringDictionary();
    parameters2.Add(OAuth2.RedirectUriKey, LiveDesktopRedirectUri);

    AuthorizationServerDescription server = new AuthorizationServerDescription();
    if (getMode)
    {
        server.AuthorizationEndpoint = new Uri(LiveAuthorizationUri);
    }
    server.TokenEndpoint = new Uri(LiveTokenEndpoint);
    server.ProtocolVersion = ProtocolVersion.V20;

    consumer = new UserAgentClient(server, clientID, clientSecret);

    // Not needed in our tests, uncomment the next line if for some reason it's required in your case.
    // consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);

    if (getMode)
    {
        grantedAccess = new AuthorizationState(null);
        if (parameters2.ContainsKey(OAuth2.RedirectUriKey))
        {
            grantedAccess.Callback = new Uri(parameters2[OAuth2.RedirectUriKey]);
        }
        return (AuthorizationState)consumer.ProcessUserAuthorization(
            new Uri("http://example.com/?code=" + code), grantedAccess);
    }
    else
    {
        return consumer.RefreshAuthorization(grantedAccess, TimeSpan.FromMinutes(1)) ? grantedAccess : null;
    }
}

' Gets access and refresh token if grantedAccess is null, and returns the token data on success or null on failure.
' Refreshes the access token using the refresh token if grantedAccess is not null, and returns the token data (also
' modifying the input parameter grantedAccess) on successful renewal or null if the renewal is not required yet.
Private Shared Function GetOrRefreshAccessToken(clientID As String, clientSecret As String, code As String, _
    grantedAccess As AuthorizationState) As AuthorizationState

    Dim consumer As UserAgentClient

    ' Get a new token or refresh an existing token?
    Dim getMode As Boolean = (grantedAccess Is Nothing)

    Dim parameters2 As New StringDictionary()
    parameters2.Add(OAuth2.RedirectUriKey, LiveDesktopRedirectUri)

    Dim server As New AuthorizationServerDescription()
    If getMode Then
        server.AuthorizationEndpoint = New Uri(LiveAuthorizationUri)
    End If
    server.TokenEndpoint = New Uri(LiveTokenEndpoint)
    server.ProtocolVersion = ProtocolVersion.V20

    consumer = New UserAgentClient(server, clientID, clientSecret)

    ' Not needed in our tests, uncomment the next line if for some reason it's required in your case.
    ' consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);

    If getMode Then
        grantedAccess = New AuthorizationState(Nothing)
        If parameters2.ContainsKey(OAuth2.RedirectUriKey) Then
            grantedAccess.Callback = New Uri(parameters2(OAuth2.RedirectUriKey))
        End If
        Return DirectCast(consumer.ProcessUserAuthorization(New Uri("http://example.com/?code=" & code), grantedAccess),  _
            AuthorizationState)
    Else
        Return If(consumer.RefreshAuthorization(grantedAccess, TimeSpan.FromMinutes(1)), grantedAccess, Nothing)
    End If
End Function

You can use this method like below:

  • C#
  • VB
AuthorizationState authState;
string tokenData;
bool mustSaveToken = true;
tokenData = File.ReadAllText(tokenFile);
authState = JsonConvert.DeserializeObject<AuthorizationState>(tokenData);
if (GetOrRefreshAccessToken(clientID, clientSecret, null, authState) != null)
{
    Console.WriteLine("Refreshing the token completed");
}
else
{
    Console.WriteLine("Refreshing the token is not required yet");
    mustSaveToken = false;
}
if (mustSaveToken)
{
    tokenData = JsonConvert.SerializeObject(authState);
    File.WriteAllText(tokenFile, tokenData);
}

Dim authState As AuthorizationState
Dim tokenData As String
Dim mustSaveToken As Boolean = True
tokenData = File.ReadAllText(tokenFile)
authState = JsonConvert.DeserializeObject(Of AuthorizationState)(tokenData)
If GetOrRefreshAccessToken(clientID, clientSecret, Nothing, authState) IsNot Nothing Then
    Console.WriteLine("Refreshing the token completed")
Else
    Console.WriteLine("Refreshing the token is not required yet")
    mustSaveToken = False
End If
If mustSaveToken Then
    tokenData = JsonConvert.SerializeObject(authState)
    File.WriteAllText(tokenFile, tokenData)
End If

We read the stored access token data from a file (tokenFile must contain its filename) and pass it as authState object to GetOrRefreshAccessToken method which updates it if necessary. If the method returned null (Nothing in VB), the refresh is not needed and the method did nothing. Otherwise, the token data in authState object has been changed and the app must update the access token file to save the changes.

After that, authState.AccessToken string can be used to pass OAuth 2.0 authentication against Microsoft server (just like in the previous samples).

Automating authorization code delivery from the browser to your app

The original sample simply started the browser prompting the user to copy/paste the authorization code from the web page to the app manually. There are methods to automate this.

Unlike Google APIs library which provides the built-in mechanism of authorization code delivery to the app, DotNetOpenAuth has no means for that. What options do we have?

  • We can create a Form, put WebBrowser control there (actually, Internet Explorer), navigate it to Microsoft OAuth authorization page, let the user complete the authorization so that "code" parameter finally appears in the URL, and grab that code.
  • Or, we can start a process to open the default web browser at Microsoft OAuth authorization page and start monitoring of system processes to wait till the moment when "code" parameter appears in the process name.

Pros and cons:

  • With WebBrowser control, the user will have to fully log in their Microsoft account, including typing the e-mail address (not very convenient). This is because WebBrowser control environment is not the same as the default browser's environment where the user may have already been logged in. However, this method always works.
  • With launching the default browser, the user won't have to type the e-mail address as they most likely are already logged in Microsoft account there (requiring less actions from the user). The password is still needed to be entered as Microsoft always requires that when the user grants access to an application (this is Microsoft-specific behavior, Google currently does not require that). However, this only works with Chrome and IE. Firefox does not show the current URL in the process name.

WebBrowser approach seems to be a better alternative:

  • It does not depend on whether the default browser puts URLs in its process name.
  • The fact that the user has to type the e-mail address is not a big deal as the password is needed to be entered anyway (Microsoft requirement).

If you're creating an app which will support both Microsoft and Google, you need to take care of Microsoft only regarding this issue. Google API hides authorization codes in its internals and the app receives the access token right away.

Actually, it's also possible to simulate Google method of delivering authorization token to the application when dealing with Microsoft OAuth provider. Google API internally starts a local web server on localhost domain and Google web site redirects the browser there once the user completes the authorization process. The same approach can be used with Microsoft as well. See LocalServer version for details.

Obtaining authorization code with WebBrowser control

You can display a form even in a console app, although it requires a bit more coding than in WinForms app (MicrosoftOAuthWinForms is an example).

The main method is RunWebBrowserFormAndGetCode. In a console app, you need to run in on STA thread (WebBrowser control limitation), so there is StartTaskAsSTAThread helper method.

And be sure to add reference to System.Windows.Forms.

Usage

  • C#
  • VB
string authorizationCode = StartTaskAsSTAThread(() => RunWebBrowserFormAndGetCode(url)).Result;

Dim authorizationCode As String = StartTaskAsSTAThread(Function() RunWebBrowserFormAndGetCode(url)).Result

Implementation

  • C#
  • VB
// Provides means to display OAuth authorization page on Microsoft web server using WebBrowser control. The control loads
// that page, the user authenticates on Microsoft web server if necessary, and grants authorization to our app. Each step
// involves a browser redirect. We monitor DocumentCompleted events to determine out the moment when "code" parameter appears
// in the current URL and return it to the caller.
//
// Pros: WebBrowser control is always available.
// Cons: the user will have to log in their Microsoft account in IE as it's the only browser supported by WebBrowser control.
private static string RunWebBrowserFormAndGetCode(string url)
{
    string code = null;

    Form webBrowserForm = new Form();
    webBrowserForm.WindowState = FormWindowState.Maximized;
    WebBrowser webBrowser = new WebBrowser();
    webBrowser.Dock = DockStyle.Fill;
    webBrowser.Url = new Uri(url);

    webBrowserForm.Controls.Add(webBrowser);

    WebBrowserDocumentCompletedEventHandler documentCompletedHandler = (s, e) =>
    {
        string[] parts = webBrowser.Url.Query.Split(new char[] { '?', '&' });
        foreach (string part in parts)
        {
            if (part.StartsWith("code="))
            {
                code = part.Split('=')[1];
                webBrowserForm.Close();
            }
            else if (part.StartsWith("error="))
            {
                webBrowserForm.Close();
            }
        }
    };

    webBrowser.DocumentCompleted += documentCompletedHandler;
    Application.Run(webBrowserForm);
    webBrowser.DocumentCompleted -= documentCompletedHandler;

    return code;
}

// We must run WebBrowser control in a separate STA thread (otherwise, it just wouldn't work in a console app),
// but it's not required for Forms-based apps (there you'd simply place it on the form and that't all).
private static Task<T> StartTaskAsSTAThread<T>(Func<T> taskFunc)
{
    TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
    Thread thread = new Thread(() =>
    {
        try
        {
            tcs.SetResult(taskFunc());
        }
        catch (Exception e)
        {
            tcs.SetException(e);
        }
    });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    return tcs.Task;
}

' Provides means to display OAuth authorization page on Microsoft web server using WebBrowser control. The control loads
' that page, the user authenticates on Microsoft web server if necessary, and grants authorization to our app. Each step
' involves a browser redirect. We monitor DocumentCompleted events to determine out the moment when "code" parameter appears
' in the current URL and return it to the caller.
'
' Pros: WebBrowser control is always available.
' Cons: the user will have to log in their Microsoft account in IE as it's the only browser supported by WebBrowser control.
Private Shared Function RunWebBrowserFormAndGetCode(url As String) As String
    Dim code As String = Nothing

    Dim webBrowserForm As New Form()
    webBrowserForm.WindowState = FormWindowState.Maximized
    Dim webBrowser As New WebBrowser()
    webBrowser.Dock = DockStyle.Fill
    webBrowser.Url = New Uri(url)

    webBrowserForm.Controls.Add(webBrowser)

    Dim documentCompletedHandler As WebBrowserDocumentCompletedEventHandler = _
        Sub(s, e)
            Dim parts As String() = webBrowser.Url.Query.Split(New Char() {"?", "&"})
            For Each part As String In parts
                If part.StartsWith("code=") Then
                    code = part.Split("=")(1)
                    webBrowserForm.Close()
                ElseIf part.StartsWith("error=") Then
                    webBrowserForm.Close()
                End If
            Next
        End Sub

    AddHandler webBrowser.DocumentCompleted, documentCompletedHandler
    Application.Run(webBrowserForm)
    RemoveHandler webBrowser.DocumentCompleted, documentCompletedHandler

    Return code
End Function

' We must run WebBrowser control in a separate STA thread (otherwise, it just wouldn't work in a console app),
' but it's not required for Forms-based apps (there you'd simply place it on the form and that't all).
Private Shared Function StartTaskAsSTAThread(Of T)(taskFunc As Func(Of T)) As Task(Of T)
    Dim tcs As New TaskCompletionSource(Of T)()
    Dim thread As New Thread( _
        Sub()
            Try
                tcs.SetResult(taskFunc())
            Catch e As Exception
                tcs.SetException(e)
            End Try
        End Sub)
    thread.SetApartmentState(ApartmentState.STA)
    thread.Start()
    Return tcs.Task
End Function

Note that in native WinForms apps, StartTaskAsSTAThread method is not needed. MicrosoftOAuthWinForms sample project demonstrates using RunWebBrowserFormAndGetCode method directly.

Obtaining authorization code using the default browser

In case if you still think WebBrowser control approach does not suit your needs, you can use the alternate approach of running the system's default browser.

You can explore the full code #region "DefaultBrowser" section in OAuthConsoleApps\MicrosoftLogin.cs(vb) file to see how process monitoring can be implemented. Here, we just list the main method to let you get the idea.

  • C#
  • VB
private static async Task<string> RunDefaultBrowserProcessAndGetCodeAsync(string url, string timestamp, CancellationToken cancelToken)
{
    // Opens the default browser to start OAuth authorization procedure. It will eventually redirect to the URL like
    // https://login.live.com/oauth20_desktop.srf?code=c9afcb5f-fd66-4fec-49b4-9194f5a074d5&lc=1033
    // The user will need to copy/paste c9afcb5f-fd66-4fec-49b4-9194f5a074d5 code in case if we couldn't get it from the
    // browser's process name (Firefox is problematic as it does not send the process name from the current URL
    // while IE and Chrome are fine with that).
    // The side effect could occur if the user changed the current browser tab to another tab which already had
    // https://login.live.com/oauth20_desktop.srf URL for some reason (like previous OAuth authorization attempts). This sample
    // could take it as the authorization code source. To locate the browser tab which was opened by the current OAuth attempt
    // (among multiple opened tabs with https://login.live.com/oauth20_desktop.srf URL) we use timestamp parameter. In your apps
    // you can use any other unique string which is unlikely to occur in other https://login.live.com/oauth20_desktop.srf windows.
    Process.Start(url);

    while (!cancelToken.IsCancellationRequested)
    {
        await Task.Delay(1000);
        Process[] processes = Process.GetProcesses();
        foreach (Process proc in processes)
        {
            string title = proc.MainWindowTitle;
            if (!String.IsNullOrEmpty(title))
            {
                if (title.IndexOf(LiveDesktopRedirectUri) > -1 && title.IndexOf(timestamp) > -1)
                {
                    string[] parts = title.Split(new char[] { '?', '&' });
                    foreach (string part in parts)
                    {
                        if (part.StartsWith("code="))
                        {
                            return part.Split('=')[1];
                        }
                        else if (part.StartsWith("error="))
                        {
                            return null;
                        }
                    }
                }
            }
        }
    }

    return null;
}

Private Shared Async Function RunDefaultBrowserProcessAndGetCodeAsync( _
    url As String, timestamp As String, cancelToken As CancellationToken) As Task(Of String)

    ' Opens the default browser to start OAuth authorization procedure. It will eventually redirect to the URL like
    ' https://login.live.com/oauth20_desktop.srf?code=c9afcb5f-fd66-4fec-49b4-9194f5a074d5&lc=1033
    ' The user will need to copy/paste c9afcb5f-fd66-4fec-49b4-9194f5a074d5 code in case if we couldn't get it from the
    ' browser's process name (Firefox is problematic as it does not send the process name from the current URL
    ' while IE and Chrome are fine with that).
    ' The side effect could occur if the user changed the current browser tab to another tab which already had
    ' https://login.live.com/oauth20_desktop.srf URL for some reason (like previous OAuth authorization attempts). This sample
    ' could take it as the authorization code source. To locate the browser tab which was opened by the current OAuth attempt
    ' (among multiple opened tabs with https://login.live.com/oauth20_desktop.srf URL) we use timestamp parameter. In your apps
    ' you can use any other unique string which is unlikely to occur in other https://login.live.com/oauth20_desktop.srf windows.
    Process.Start(url)

    While Not cancelToken.IsCancellationRequested
        Await Task.Delay(1000)
        Dim processes As Process() = Process.GetProcesses()
        For Each proc As Process In processes
            Dim title As String = proc.MainWindowTitle
            If Not String.IsNullOrEmpty(title) Then
                If title.IndexOf(LiveDesktopRedirectUri) > -1 AndAlso title.IndexOf(timestamp) > -1 Then
                    Dim parts As String() = title.Split(New Char() {"?", "&"})
                    For Each part As String In parts
                        If part.StartsWith("code=") Then
                            Return part.Split("=")(1)
                        ElseIf part.StartsWith("error=") Then
                            Return Nothing
                        End If
                    Next
                End If
            End If
        Next
    End While

    Return Nothing
End Function

As you can see, this method also utilizes "state" parameter in OAuth URLs. Unlike WebBrowser control which is fully controlled by our app, running the default browser does not guarantee the user won't change the current tab (making it active) and this tab won't have the same URL like the one we need (for instance, if the user recently authorized our app and didn't close that browser tab). We need to somehow make sure that the currently opened browser tab was indeed initiated by our app. Moreover, by the current run of our app. For that, we set "state" parameter to some timestamp and then compare the browser process name (i.e. URL) if it contains that timestamp.

OAuthConsoleApps\MicrosoftLogin.cs(vb) also shows some techniques to let the user bypass the standard method of waiting for the authorization code in the process name and type it directly in the console. For instance, if the current browser does not set the process name from the URL, the user will still have an option to copy/paste the code manually. This means the app must support two input sources simultaneously - from the browser process and from console input.

For instance, the sample shows how to stop waiting for console input in case if the result became available by other means (from the process name in our case). The sample does this by sending [Enter] keypress event to the console.

Revoking Microsoft access token

Unlike Google APIs library, there is no built-in method of revoking refresh tokens yet in DotNetOpenAuth library. However, you can make a direct REST query for that. See Revoke refresh tokens section in Manage access tokens for API requests for details.

Sample projects overview

All the code in this tutorial is available in MicrosoftEasyLogin and MicrosoftLogin classes of OAuthConsoleApps project. WinForms version is available in FormMain class of MicrosoftOAuthWinForms project.

All samples are available in both C# and VB versions.

MicrosoftEasyLogin provides the very basic means of using Microsoft OAuth provider to check the user's mailbox via IMAP.

MicrosoftLogin adds autodetection of the e-mail address, persistent storage of access token data, Offline mode and refresh tokens, automated detection of the authorization code via detecting it in the browser URL(manual user input is still available), sending e-mail via SMTP.

FormMain class MicrosoftOAuthWinForms sample has most features of MicrosoftLogin class of OAuthConsoleApps, with the following differences:

  • MicrosoftLogin provides 2 methods of getting the authorization code: with WebBrowser control and launching the system's default browser in a separate process. FormMain class only offers WebBrowser control as the natural method for WinForms apps.

  • FormMain class uses async methods which don't block UI during send e-mail or check e-mail operations with MailBee.NET Objects. Most of the operations can be canceled by hitting ESC or closing the app.

    OAuth calls involving DotNetOpenAuth library are still sync-only due to the lack of async versions in the current version of DotNetOpenAuth (can be worked around by putting the entire thing in a worker thread, however).

Get source code

All C# and VB samples discussed in this article (MicrosoftOAuthWinForms and OAuthConsoleApps) are shipped with MailBee.NET Objects installer and get installed into My Documents\MailBee.NET Objects\Samples\WinForms\NET 4.5 OAuth folder.

Send feedback to AfterLogic


OAuth 2.0 for Microsoft Accounts (installed applications running HttpListener)

This is the the modern version of the tutorial. It supports both .NET Framework and .NET Core, does not use DotNetOpenAuth (which is not available for .NET Core), and demonstrates how your app can start a local web server (HttpListener) for a short interval of time to process authorization code from Microsoft server. This spares the end users from manual copy-pasting authorization codes from the browser to your app.

In this guide, we'll configure a .NET Core application which can access Outlook.com, Hotmail.com or Live.com account of a user via IMAP and SMTP without knowing the password of this user. The app has no .NET Core specific code so you can convert it into a .NET Framework 4.5+ app if needed.

  • UWP/UAP notes
  • Register Microsoft project
  • Configure application in Visual Studio
  • Run application in Visual Studio

UWP/UAP notes

Running HttpListener is not supported in Universal Windows apps (UWP allows listening on localhost for debugging purposes only, productions apps are not allowed to do this). For UWP, you need to register a URL schema handler and make the browser to call your application when being redirected from the OAuth provider web site. Refer to OAuth 2.0 for Universal Windows apps guide for details.

Register Microsoft project

Create an application in Application Registration Portal. You may need to create an account there first.

For OAuth 2.0, create a Live SDK application. Click Add an app in Live SDK applications section.

On the next screen, click Add Platform and select Web. Then add a Redirect URL, such as http://localhost:49217/signin-microsoft, then save changes. The port number can be different, it's not actually required to run the local web server on this exact port. Also, it's not a problem that it's http and not https. The network traffic won't leave the local system, it will be the browser accessing the local resource.

Application ID (Client ID) and password (application secret) are there as well. You'll need them both for your application.

Make sure to add the required permissions (scopes) as well:

Microsoft is changing things there often. Sometimes, Live SDK app simply doesn't work and you may try creating a Converged application. Also, you may be asked to use Azure portal instead of apps.dev.microsoft.com site. At the moment of writing, Azure portal was not stable enough for that.

Configure application in Visual Studio

Open My Documents\MailBee.NET Objects\Samples\WinForms.NET Core 2.0\C#\MicrosoftRegularAccounts sample project. It runs on .NET Core platform but can be easily ported to .NET Framework with no code changes.

In Program.cs, set ClientId and ClientSecret to the values obtained from apps.dev.microsoft.com portal, and set MailBee.Global.LicenseKey to your MailBee.NET Objects license key.

Run application in Visual Studio

Now build and run the application. How it works:

  • Checks if token.json file exists in the current folder. If yes, it reads the stored OAuth token from there.
  • If token.json is not there, the app starts HttpListener (a local web server) on any unoccupied local port, then opens the browser which connects to Microsoft OAuth server and displays the consent screen of your application registered on apps.dev.microsoft.com portal. If the user gives consent, the Microsoft server causes the browser to redirect to the localhost. The redirect URL contains the authorization code.
  • The HttpListener gets the incoming request (which is coming from the browser) and gets the authorization code from the URL. Then we shut the local server down.
  • Authorization code is used to get the access and refresh tokens. We store them in token.json.
  • The app then uses the access token for multiple purposes:
    • To get e-mail address and display name of the user.
    • To build XOAUTH2 key which we then use to get the inbox of Microsoft account the user authenticated with or to send an email to that account. useImap bool variable in the code controls whether the action to perform will be "checking mail" or "sending mail".
  • On further runs, when token.json is there, we also check if the access token is still valid (it expires in an hour). If it's about to expire soon, we refresh it using the refresh token. There is expiresAtUtc = expiresAtUtc.AddMinutes(-59); line which you can uncomment to test access token expiration without the need to wait for an hour (for debugging purposes).

Send feedback to AfterLogic


OAuth 2.0 for Google Regular Accounts (installed applications)

You can create a Windows application which can access Gmail account of a user via IMAP and SMTP without knowing the password of this user. Note that in case of Google Apps you can also use Service Accounts for that (Service Accounts approach is much easier to use).

  • .NET Core and UWP/UAP notes
  • Register Google project
  • Create application in Visual Studio
  • Add Google APIs references to your Visual Studio project (NuGet console)
  • Add Google APIs references to your Visual Studio project (NuGet UI)
  • Add MailBee.NET Objects reference
  • Using MailBee.NET and Google API to access a user's e-mail account
  • Clearing or revoking tokens
  • Advanced sample
  • Revoking the previously saved token
  • Using custom storage for Google tokens
  • Sample projects overview
  • Get source code

.NET Core and UWP/UAP notes

As of May 2019, the current version of Google API requires .NET Standard 2.0 at least (available for UWP starting from Windows 10 Fall Creators Update). UWP for older versions of Windows (e.g. .NET Standard 1.3) won't work.

In UWP, you must use async methods and use JSON file for storing client secrets (cannot specify them directly in code). See example in UWP Edition (Universal Windows, UAP 10.0) topic.

Or, you can use no Google libraries at all. Refer to OAuth 2.0 for Universal Windows apps guide and My Documents\MailBee.NET Objects\Samples\WinForms\.NET Core 2.0\C#\OAuthUniversalApp project on how to use OAuth to authenticate against Google and Microsoft and then check/send mail on their servers.

Register Google project

First, you need to register a project in your Google Developer Console:

Now, at "API Manager/Credentials/OAuth consent screen" section specify your support e-mail address and your product name. People will see this info when authorizing your application on access to your mailbox:

Click Save.

Then, at "API Manager/Credentials/Credentials" section click Create Credentials and select OAuth Client ID. Create a new Client ID selecting "Other" type, you can leave any name for client ID:

Now you have OAuth credentials:

Enable access to Google e-mail address, IMAP and SMTP services

You will also need to go to "API Manager/Library" and locate "Gmail API" and "Google+ API":

Click and enable "Gmail API" to let your application authenticate in Gmail services with XOAUTH2 (OAuth 2.0 extension for IMAP and SMTP):

Finally, repeat the same for "Google+ API" to let your application see the e-mail address of the user:

There can be a few minutes delay on Google end for these changes to take effect.

Create application in Visual Studio

Now create a console application in Visual Studio. The same approach will work for Windows Forms applications as well, see GoogleOAuthWinForms sample.

Then proceed to adding the required Google APIs dependencies. You can use NuGet console or NuGet user interface for that (whatever you prefer).

The sample does not use the helper ExternalProviders library (like it's done in web apps version of OAuth 2.0 tutorial). The library uses ASP.NET Identity database as storage of access tokens and related data but we're not using that database in the sample for this article.

Add Google APIs references to your Visual Studio project (NuGet console)

First, install Google APIs .NET library packages. The sample in this topic was tested in Visual Studio 2013 (.NET 4.5.1), 2015 (.NET 4.6), and 2017 (up to .NET Core 2.2).

Install-Package Google.Apis.Auth
Install-Package Google.Apis.Oauth2.v2

Google.Apis.Oauth2.v2 package is required only if you need to get the e-mail address of the user (i.e. if you can't get it by other means). The sample below asks Google for the user's e-mail address and thus uses this library.

NuGet may install not the latest versions when auto-resolving dependencies, that's why post-update may be required. After adding the packages, it's recommended to run:

Update-Package

packages.config should finally contain these Google entries:

  • Google.Apis
  • Google.Apis.Auth
  • Google.Apis.Core
  • Google.Apis.Oauth2.v2

Add Google APIs references to your Visual Studio project (NuGet UI)

If you prefer UI version of NuGet rather than its console, then open "Manage NuGet Packages" of your project, search and select:

  • Google APIs Core Client Library
  • Google APIs Client Library
  • Google APIs Auth Client Library
  • Google.Apis.Oauth2.v2 Client Library

"Google.Apis.Oauth2.v2 Client Library" is required only if you need to get the e-mail address of the user (i.e. if you can't get it by other means). The sample below asks Google for the user's e-mail address and thus uses this library.

In case if you're targeting .NET Core or UWP, you'll also need to install

Also, there are some NuGet dependencies for these libraries and you may need to update NuGet and Visual Studio themselves. So, make sure you have resolved all the references, installed all the updates for both Visual Studio components and for the packages referenced by this project. Otherwise, you may encounter misc. compilation or runtime errors. The picture below lists all the packages used in the sample code for this article:

Open "Manage NuGet Packages for Solution" once again to check if Update All command appeared, and run it if available.

Add MailBee.NET Objects reference

In NuGet console, run:

Install-Package MailBee.NET

Alternatively, you can use Add Reference to plug MailBee.NET.dll to your project. It resides in Assemblies/Framework/Extensions in case if MailBee.NET Objects is fully installed in the system, or use Browse if you have just the .DLL file.

Using MailBee.NET and Google API to access a user's e-mail account

That's what we need to do in order to get access to the user's e-mails:

  • Request authorization from Google to access the scopes of Gmail and the e-mail address (areas of authorization are called scopes).
  • Do the authorization using Client ID and Client Secret issued by Google to our application. At the first time, this will open the browser window with Google web page asking the user to authorize our application. If the user agrees, Google delivers the access token which we can then use to do IMAP authentication. The access token is also saved locally in a persistent location like C:\Users\UserName\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user for later use.
  • In case if the stored access token is already available (i.e. the application has already been run before), we extract the stored token instead and don't bother the user with the authorization dialog.
  • However, access tokens are short-lived (they expire in an hour). Google provides the mechanism of refresh tokens which can be used to get new access tokens. On the first run, Google delivers us both an access token and a refresh token which are both stored locally in the location mentioned above. So we need to check if the access token is expired and renew it if necessary.
  • Determine the e-mail address of the user (needed for IMAP OAuth 2.0 authentication, XOAUTH2). The sample does this on every run but for performance sake you can save the results after the first run (the e-mail address of the user will never change).
  • Use the e-mail address and access token to build XOAUTH2 key.
  • Use MailBee.NET to connect to Gmail and log in using XOAUTH2 authentication method. Both IMAP and SMTP are supported.
  • Do whatever needed in the user's mailbox (IMAP), or send an e-mail (SMTP).

Now, here is the code which lists the message count in the user's Gmail Inbox.

  • C#
  • VB
using System;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
using Google.Apis.Services;
using MailBee;
using MailBee.ImapMail;

// This program shows how to issue, refresh and use Google access tokens for IMAP access to a Gmail mailbox.
//
// To run this program, select "GmailEasyLogin" in Project / project's Properties / Application tab / Startup object.
public class GmailEasyLogin
{
    public static void Main(string[] args)
    {
        // Request Gmail IMAP/SMTP scope and the e-mail address scope.
        string[] scopes = new string[] { "https://mail.google.com/", Oauth2Service.Scope.UserinfoEmail };

        Console.WriteLine("Requesting authorization");
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets
            {
                ClientId = "Your Client ID, like 0123-abcd.apps.googleusercontent.com",
                ClientSecret = "Your Client Secret, like 0a1b2c3d",
            },
             scopes,
             "user",
             CancellationToken.None).Result;
        Console.WriteLine("Authorization granted or not required (if the saved access token already available)");

        if (credential.Token.IsExpired(credential.Flow.Clock))
        {
            Console.WriteLine("The access token has expired, refreshing it");
            if (credential.RefreshTokenAsync(CancellationToken.None).Result)
            {
                Console.WriteLine("The access token is now refreshed");
            }
            else
            {
                Console.WriteLine("The access token has expired but we can't refresh it :(");
                return;
            }
        }
        else
        {
            Console.WriteLine("The access token is OK, continue");
        }

        Console.WriteLine("Requesting the e-mail address of the user from Google");

        // Sometimes, you may also need to set Initializer.ApplicationName property.
        // In our tests, setting just Initializer.HttpClientInitializer was enough for Google.
        Oauth2Service oauthService = new Oauth2Service(
            new BaseClientService.Initializer() { HttpClientInitializer = credential });

        // Userinfo.Get may crash if you run the app under debugger (a bug in Google API).
        // If this happens, use "Start without debugging" instead.
        Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result;
        string userEmail = userInfo.Email;
        Console.WriteLine("E-mail address is " + userEmail);

        // Build XOAUTH2 token. Can be used with Gmail IMAP or SMTP.
        string xoauthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

        // Uncomment and set your key if you haven't specified it in app.config or Windows registry.
        // MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here";

        // Finally, use MailBee.NET to list the number of e-mails in Inbox.

        Imap imp = new Imap();

        // Logging is not necessary but useful for debugging.
        imp.Log.Enabled = true;
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.HidePasswords = false;
        imp.Log.Clear();

        imp.Connect("imap.gmail.com");

        // This is the where IMAP XOAUTH2 actually occurs.
        imp.Login(null, xoauthKey, AuthenticationMethods.SaslOAuth2,
            MailBee.AuthenticationOptions.None, null);

        // If we're here, we're lucky.
        imp.SelectFolder("INBOX");
        Console.WriteLine(imp.MessageCount.ToString() + " e-mails in Inbox");
        imp.Disconnect();
    }
}

Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Oauth2.v2
Imports Google.Apis.Oauth2.v2.Data
Imports Google.Apis.Services
Imports MailBee
Imports MailBee.ImapMail

' This program shows how to issue, refresh and use Google access tokens for IMAP access to a Gmail mailbox.
'
' To run this program, select "GmailEasyLogin" in Project / project's Properties / Application tab / Startup object.
Public Class GmailEasyLogin
    Public Shared Sub Main(args As String())
        ' Request Gmail IMAP/SMTP scope and the e-mail address scope.
        Dim scopes As String() = New String() {"https://mail.google.com/", Oauth2Service.Scope.UserinfoEmail}

        Console.WriteLine("Requesting authorization")
        Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With { _
            .ClientId = "Your Client ID, like 0123-abcd.apps.googleusercontent.com", _
            .ClientSecret = "Your Client Secret, like 0a1b2c3d" _
        }, scopes, "user", CancellationToken.None).Result
        Console.WriteLine("Authorization granted or not required (if the saved access token already available)")

        If credential.Token.IsExpired(credential.Flow.Clock) Then
            Console.WriteLine("The access token has expired, refreshing it")
            If credential.RefreshTokenAsync(CancellationToken.None).Result Then
                Console.WriteLine("The access token is now refreshed")
            Else
                Console.WriteLine("The access token has expired but we can't refresh it :(")
                Return
            End If
        Else
            Console.WriteLine("The access token is OK, continue")
        End If

        Console.WriteLine("Requesting the e-mail address of the user from Google")

        ' Sometimes, you may also need to set Initializer.ApplicationName property.
        ' In our tests, setting just Initializer.HttpClientInitializer was enough for Google.
        Dim oauthService As New Oauth2Service(New BaseClientService.Initializer() With { _
            .HttpClientInitializer = credential _
        })

        ' Userinfo.Get may crash if you run the app under debugger (a bug in Google API).
        ' If this happens, use "Start without debugging" instead.
        Dim userInfo As Userinfoplus = oauthService.Userinfo.Get().ExecuteAsync().Result
        Dim userEmail As String = userInfo.Email
        Console.WriteLine("E-mail address is " & userEmail)

        ' Build XOAUTH2 token. Can be used with Gmail IMAP or SMTP.
        Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

        ' Uncomment and set your key if you haven't specified it in app.config or Windows registry.
        ' MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here"

        ' Finally, use MailBee.NET to list the number of e-mails in Inbox.

        Dim imp As New Imap()

        ' Logging is not necessary but useful for debugging.
        imp.Log.Enabled = True
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.HidePasswords = False
        imp.Log.Clear()

        imp.Connect("imap.gmail.com")

        ' This is the where IMAP XOAUTH2 actually occurs.
        imp.Login(Nothing, xoauthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, Nothing)

        ' If we're here, we're lucky.
        imp.SelectFolder("INBOX")
        Console.WriteLine(imp.MessageCount & " e-mails in Inbox")
        imp.Disconnect()
    End Sub
End Class

The code does not use async methods of MailBee.NET library. You can see async version in GoogleOAuthWinForms project. See Sample projects overview for details.

Clearing or revoking tokens

You may sometimes need to remove tokens you received from Google, for different reasons:

  • If you want Google to forget the current token (sign out the user from your application), you need to revoke the token - this will remove both local copy and Google copy of the token.
  • If you simply want to remove the locally stored token just to force Google to display authorization window again on next login, you may clear the local copy. This mainly makes sense for debugging purposes or in advanced cases if you want to move the existing local token to another storage.

The sample code below will demonstrate both methods.

Advanced sample

The sample below adds:

  • The option to clear the token before login. This will let you debug the logic of your application if you want to re-run authorization on Google server for some reason.
  • The option to select whether to access the e-mail address from Google. If you already know that address, you can optimize your login procedure by removing one unnecessary request. Mainly you'll request the e-mail address only on the first login.
  • The option to use SMTP (send mail) in addition to IMAP (check mail).
  • The option to revoke the token after use. For instance, if you want to access the user's account only once and forget about it immediately afterwards.
  • C#
  • VB
using System;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Util.Store;
using Google.Apis.Services;

// These two are required only if you want to get the e-mail address of the user (with Oauth2Service class).
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;

using MailBee;
using MailBee.ImapMail;
using MailBee.SmtpMail;

// This program shows how to issue, refresh, delete, revoke and use Google access tokens for IMAP and SMTP access to a Gmail mailbox.
//
// To run this program, select "GmailLogin" in Project / project's Properties / Application tab / Startup object.
public class GmailLogin
{
    public static void Main(string[] args)
    {
        // You get these in Google Developer Console.
        string yourAppClientID = "Your Client ID, like 0123-abcd.apps.googleusercontent.com";
        string yourAppClientSecret = "Your Client Secret, like 0a1b2c3d";

        // If you want to clear the saved token (if any) to force Google to show authorization screen again,
        // set clearSavedToken to true. Note that the code below only removes the token from the local storage,
        // Google server still remembers it. Deleting a token just locally without revoking it on Google server
        // makes a little practical sense but can be useful for debugging, such as when your local token became
        // invalid: typically happens during development when you issue such many tokens that Google starts to forget
        // them and your local token no longer corresponds to its counterpart on Google server (even revoking such
        // token will fail).
        // If your purpose is to invalidate a working token everywhere (delete from both local storage and Google server),
        // use UserCredential.RevokeTokenAsync (for that, in the end of this sample, set revokeToken to true).
        bool clearSavedToken = false;
        if (clearSavedToken)
        {
            // If there is no saved token (e.g. Google authorization screen has never been shown for this user),
            // the code below will do nothing. No exception will occur. If the token is there, Google API will delete
            // C:\Users\<YourWindowsUser>\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user
            // file (the exact path may vary depending on your OS and Google API version). Without the stored token
            // subsequent GoogleWebAuthorizationBroker.AuthorizeAsync call will open the browser window asking for
            // authorization.
            // Note that there still be a difference in authorization window between two situations: when
            // you actually request authorization for the first time and when you deleted the previous token locally
            // and now force Google to request authorization again. In second case Google still remembers that it already
            // authorized this application to access your user and it will just ask the user that the application wants
            // Offline access. In the first case Google will ask for the specified scopes (full access to your mailbox
            // and e-mail address).
            FileDataStore ds = new FileDataStore(GoogleWebAuthorizationBroker.Folder);
            ds.DeleteAsync<TokenResponse>("user").Wait();
        }

        // Here you should specify the user's e-mail address if you already know it (for instance, from
        // your user's input). If you don't set the e-mail address here, MailBee.NET will ask Google for it
        // but this will require the user to grant extra permissions to the application during the authorization.
        string userEmail = null;

        // Gmail supports a number of scopes. This one is required for IMAP/SMTP access.
        string gmailScope = "https://mail.google.com/";

        string[] scopes;

        // We set only a Gmail scope if we don't need the user's email address (when it's already set).
        // Otherwise, we need to add another scope to determine the user's email address.
        if (userEmail != null)
        {
            scopes = new string[1];
        }
        else
        {
            scopes = new string[2];
        }
        scopes[0] = gmailScope;

        // Adding Oauth2Service.Scope.UserinfoEmail causes the app to request more permissions from the user
        // but lets us get the e-mail address automatically. Otherwise, you'll need to get the e-mail address
        // by other means, such as to ask it from the user.
        if (userEmail == null)
        {
            scopes[1] = Oauth2Service.Scope.UserinfoEmail;
        }

        Console.WriteLine("Requesting authorization");
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets
            {
                ClientId = yourAppClientID,
                ClientSecret = yourAppClientSecret,
            },
             scopes,
             "user",
             CancellationToken.None).Result;
        Console.WriteLine("Authorization granted or not required (if the saved access token already available)");

        if (credential.Token.IsExpired(credential.Flow.Clock))
        {
            Console.WriteLine("The access token has expired, refreshing it");
            if (credential.RefreshTokenAsync(CancellationToken.None).Result)
            {
                Console.WriteLine("The access token is now refreshed");
            }
            else
            {
                Console.WriteLine("The access token has expired but we can't refresh it :(");
                return;
            }
        }
        else
        {
            Console.WriteLine("The access token is OK, continue");
        }

        // Here we autodetect the user's email address with Google+ API. This autodetection is not required
        // if you already know the user's email address from other sources (like the user's input).
        // Also, even if you do ask for the email address, it's not required to do this every time you access
        // the Google mailbox of that user. For instance, you can do this just once and then store the e-mail
        // address locally. This will spare you one HTTP request per each mailbox access and increase performance.
        if (userEmail == null)
        {
            Console.WriteLine("Requesting the e-mail address of the user from Google");

            // Sometimes, you may also need to set Initializer.ApplicationName property.
            // In our tests, setting just Initializer.HttpClientInitializer was enough for Google.
            Oauth2Service oauthService = new Oauth2Service(
                new BaseClientService.Initializer() { HttpClientInitializer = credential });

            Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result;
            userEmail = userInfo.Email;
            Console.WriteLine("E-mail address is " + userEmail);
        }

        string xoauthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

        bool useImap = true; // Set to false to use SMTP (send e-mail) instead of IMAP (check Inbox).

        // Uncomment and set your key if you haven't specified it in app.config or Windows registry.
        // MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here";

        if (useImap)
        {
            Imap imp = new Imap();

            // Logging is not necessary but useful for debugging.
            imp.Log.Enabled = true;
            imp.Log.Filename = @"C:\Temp\log.txt";
            imp.Log.HidePasswords = false;
            imp.Log.Clear();

            imp.Connect("imap.gmail.com");
            imp.Login(null, xoauthKey, AuthenticationMethods.SaslOAuth2,
                MailBee.AuthenticationOptions.None, null);
            imp.SelectFolder("INBOX");
            Console.WriteLine(imp.MessageCount.ToString() + " e-mails in Inbox");
            imp.Disconnect();
        }
        else
        {
            Smtp mailer = new Smtp();
            mailer.SmtpServers.Add("smtp.gmail.com", null, xoauthKey, AuthenticationMethods.SaslOAuth2);

            // Logging is not necessary but useful for debugging.
            mailer.Log.Enabled = true;
            mailer.Log.Filename = @"C:\Temp\log.txt";
            mailer.Log.HidePasswords = false;
            mailer.Log.Clear();

            mailer.From.Email = userEmail;
            mailer.To.Add(userEmail);
            mailer.Subject = "empty email to myself";
            mailer.Send();
            Console.WriteLine("E-mail sent");
        }

        // Set revokeToken to true to invalidate the token if you want to disconnect the user from your application.
        // Revoking a token deletes it from Google server and from local storage. Strictly speaking, Google may remember
        // even revoked tokens so there can be a way to reactivate a revoked token but this sample doesn't go that deep.
        //
        // This code revokes the token which was already retrieved with GoogleWebAuthorizationBroker.AuthorizeAsync method.
        // This can be useful if you want to use it instantly - you retrieved the token, used it, and then want to forget it.
        // In case if you need to revoke an existing token which was retrieved earlier (not in the current session) you can
        // use GmailRevokeToken sample code. It also shows the alternate way of how to refresh a previously stored token.
        //
        // Note: revoking tokens only works for valid tokens. If your token is not known to Google (for instance, you issued
        // more than 25 new tokens since then), it will fail. Use local-only deletion (in the beginning of this sample) for that.
        // Also, revoking won't work for expired tokens. If it's expired and you want to test revoking, refresh it first.
        // You may ask what's the purpose of revoking an access token if it's already expired and cannot be used anyway. However,
        // an expired access token can be refreshed in case if you have its refresh token counterpart. But if the access token is
        // revoked, its refresh token will also be revoked and thus can no longer be used for access token renewal.
        bool revokeToken = false;
        if (revokeToken)
        {
            credential.RevokeTokenAsync(CancellationToken.None).Wait();
        }
    }
}

Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Auth.OAuth2.Responses
Imports Google.Apis.Util.Store
Imports Google.Apis.Services

' These two are required only if you want to get the e-mail address of the user (with Oauth2Service class).
Imports Google.Apis.Oauth2.v2
Imports Google.Apis.Oauth2.v2.Data

Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail

' This program shows how to issue, refresh, delete, revoke and use Google access tokens for IMAP and SMTP access to a Gmail mailbox.
'
' To run this program, select "GmailLogin" in Project / project's Properties / Application tab / Startup object.
Public Class GmailLogin
    Public Shared Sub Main(args As String())
        ' You get these in Google Developer Console.
        Dim yourAppClientID As String = "Your Client ID, like 0123-abcd.apps.googleusercontent.com"
        Dim yourAppClientSecret As String = "Your Client Secret, like 0a1b2c3d"

        ' If you want to clear the saved token (if any) to force Google to show authorization screen again,
        ' set clearSavedToken to true. Note that the code below only removes the token from the local storage,
        ' Google server still remembers it. Deleting a token just locally without revoking it on Google server
        ' makes a little practical sense but can be useful for debugging, such as when your local token became
        ' invalid: typically happens during development when you issue such many tokens that Google starts to forget
        ' them and your local token no longer corresponds to its counterpart on Google server (even revoking such
        ' token will fail).
        ' If your purpose is to invalidate a working token everywhere (delete from both local storage and Google server),
        ' use UserCredential.RevokeTokenAsync (for that, in the end of this sample, set revokeToken to true).
        Dim clearSavedToken As Boolean = False
        If clearSavedToken Then
            ' If there is no saved token (e.g. Google authorization screen has never been shown for this user),
            ' the code below will do nothing. No exception will occur. If the token is there, Google API will delete
            ' C:\Users\<YourWindowsUser>\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user
            ' file (the exact path may vary depending on your OS and Google API version). Without the stored token
            ' subsequent GoogleWebAuthorizationBroker.AuthorizeAsync call will open the browser window asking for
            ' authorization.
            ' Note that there still be a difference in authorization window between two situations: when
            ' you actually request authorization for the first time and when you deleted the previous token locally
            ' and now force Google to request authorization again. In second case Google still remembers that it already
            ' authorized this application to access your user and it will just ask the user that the application wants
            ' Offline access. In the first case Google will ask for the specified scopes (full access to your mailbox
            ' and e-mail address).
            Dim ds As New FileDataStore(GoogleWebAuthorizationBroker.Folder)
            ds.DeleteAsync(Of TokenResponse)("user").Wait()
        End If

        ' Here you should specify the user's e-mail address if you already know it (for instance, from
        ' your user's input). If you don't set the e-mail address here, MailBee.NET will ask Google for it
        ' but this will require the user to grant extra permissions to the application during the authorization.
        Dim userEmail As String = Nothing

        ' Gmail supports a number of scopes. This one is required for IMAP/SMTP access.
        Dim gmailScope As String = "https://mail.google.com/"

        Dim scopes As String()

        ' We set only a Gmail scope if we don't need the user's email address (when it's already set).
        ' Otherwise, we need to add another scope to determine the user's email address.
        If userEmail IsNot Nothing Then
            scopes = New String(0) {}
        Else
            scopes = New String(1) {}
        End If
        scopes(0) = gmailScope

        ' Adding Oauth2Service.Scope.UserinfoEmail causes the app to request more permissions from the user
        ' but lets us get the e-mail address automatically. Otherwise, you'll need to get the e-mail address
        ' by other means, such as to ask it from the user.
        If userEmail Is Nothing Then
            scopes(1) = Oauth2Service.Scope.UserinfoEmail
        End If

        Console.WriteLine("Requesting authorization")
        Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With { _
            .ClientId = yourAppClientID, _
            .ClientSecret = yourAppClientSecret _
        }, scopes, "user", CancellationToken.None).Result
        Console.WriteLine("Authorization granted or not required (if the saved access token already available)")

        If credential.Token.IsExpired(credential.Flow.Clock) Then
            Console.WriteLine("The access token has expired, refreshing it")
            If credential.RefreshTokenAsync(CancellationToken.None).Result Then
                Console.WriteLine("The access token is now refreshed")
            Else
                Console.WriteLine("The access token has expired but we can't refresh it :(")
                Return
            End If
        Else
            Console.WriteLine("The access token is OK, continue")
        End If

        ' Here we autodetect the user's email address with Google+ API. This autodetection is not required
        ' if you already know the user's email address from other sources (like the user's input).
        ' Also, even if you do ask for the email address, it's not required to do this every time you access
        ' the Google mailbox of that user. For instance, you can do this just once and then store the e-mail
        ' address locally. This will spare you one HTTP request per each mailbox access and increase performance.
        If userEmail Is Nothing Then
            Console.WriteLine("Requesting the e-mail address of the user from Google")

            ' Sometimes, you may also need to set Initializer.ApplicationName property.
            ' In our tests, setting just Initializer.HttpClientInitializer was enough for Google.
            Dim oauthService As New Oauth2Service(New BaseClientService.Initializer() With { _
                .HttpClientInitializer = credential _
            })

            Dim userInfo As Userinfoplus = oauthService.Userinfo.Get().ExecuteAsync().Result
            userEmail = userInfo.Email
            Console.WriteLine("E-mail address is " & userEmail)
        End If

        Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

        Dim useImap As Boolean = True ' Set to false to use SMTP (send e-mail) instead of IMAP (check Inbox).

        ' Uncomment and set your key if you haven't specified it in app.config or Windows registry.
        ' MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here"

        If useImap Then
            Dim imp As New Imap()

            ' Logging is not necessary but useful for debugging.
            imp.Log.Enabled = True
            imp.Log.Filename = "C:\Temp\log.txt"
            imp.Log.HidePasswords = False
            imp.Log.Clear()

            imp.Connect("imap.gmail.com")
            imp.Login(Nothing, xoauthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, Nothing)
            imp.SelectFolder("INBOX")
            Console.WriteLine(imp.MessageCount.ToString() & " e-mails in Inbox")
            imp.Disconnect()
        Else
            Dim mailer As New Smtp()
            mailer.SmtpServers.Add("smtp.gmail.com", Nothing, xoauthKey, AuthenticationMethods.SaslOAuth2)

            ' Logging is not necessary but useful for debugging.
            mailer.Log.Enabled = True
            mailer.Log.Filename = "C:\Temp\log.txt"
            mailer.Log.HidePasswords = False
            mailer.Log.Clear()

            mailer.From.Email = userEmail
            mailer.To.Add(userEmail)
            mailer.Subject = "empty email to myself"
            mailer.Send()
            Console.WriteLine("E-mail sent")
        End If

        ' Set revokeToken to true to invalidate the token if you want to disconnect the user from your application.
        ' Revoking a token deletes it from Google server and from local storage. Strictly speaking, Google may remember
        ' even revoked tokens so there can be a way to reactivate a revoked token but this sample doesn't go that deep.
        '
        ' This code revokes the token which was already retrieved with GoogleWebAuthorizationBroker.AuthorizeAsync method.
        ' This can be useful if you want to use it instantly - you retrieved the token, used it, and then want to forget it.
        ' In case if you need to revoke an existing token which was retrieved earlier (not in the current session) you can
        ' use GmailRevokeToken sample code. It also shows the alternate way of how to refresh a previously stored token.
        '
        ' Note: revoking tokens only works for valid tokens. If your token is not known to Google (for instance, you issued
        ' more than 25 new tokens since then), it will fail. Use local-only deletion (in the beginning of this sample) for that.
        ' Also, revoking won't work for expired tokens. If it's expired and you want to test revoking, refresh it first.
        ' You may ask what's the purpose of revoking an access token if it's already expired and cannot be used anyway. However,
        ' an expired access token can be refreshed in case if you have its refresh token counterpart. But if the access token is
        ' revoked, its refresh token will also be revoked and thus can no longer be used for access token renewal.
        Dim revokeToken As Boolean = False
        If revokeToken Then
            credential.RevokeTokenAsync(CancellationToken.None).Wait()
        End If
    End Sub
End Class

Revoking the previously saved token

The option to revoke a token in the previous sample assumed the token is received during the same session. However, in many cases you may want to cancel the token which had been received much earlier, such as in a previous session, and you don't want the user to complete OAuth 2.0 authorization again just to have the token canceled.

To revoke the previously stored token, you should load it directly from local storage rather than with GoogleWebAuthorizationBroker.AuthorizeAsync. Still, you may need to make sure the token is not expired (you cannot revoke an expired token).

You may ask what's the point of revoking an access token if it's already expired? But revoking also invalidates its associated refresh token which (mostly) never expires. Until the token is revoked, the app can renew the expired access token with the refresh token. Revoking truly disconnects the user from the app.

  • C#
  • VB
using System;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Util.Store;

// This program shows how to load a previously stored Google access token and revoke it.
//
// To run this program, select "GmailRevokeToken" in Project / project's Properties / Application tab / Startup object.
public class GmailRevokeToken
{
    const string gmailFullAccessScope = "https://mail.google.com/";

    public static void Main(string[] args)
    {
        GoogleAuthorizationCodeFlow.Initializer initializer = new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = "Your Client ID, like 0123-abcd.apps.googleusercontent.com",
                ClientSecret = "Your Client Secret, like 0a1b2c3d"
            }
        };
        initializer.DataStore = new FileDataStore(GoogleWebAuthorizationBroker.Folder);
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(initializer);

        Console.WriteLine("Will load the saved access token");
        TokenResponse token = flow.LoadTokenAsync("user", CancellationToken.None).Result;

        if (token == null)
        {
            Console.WriteLine("No saved token found");
        }
        else
        {
            // Revoking an expired token is not possible, we need to refresh it first.
            if (token.IsExpired(flow.Clock))
            {
                Console.WriteLine("Will renew the access token");
                token = flow.RefreshTokenAsync("user", token.RefreshToken, CancellationToken.None).Result;
            }
            else
            {
                Console.WriteLine("Token renewal not needed");
            }

            Console.WriteLine("Will revoke the saved access token now");
            flow.RevokeTokenAsync("user", token.AccessToken, CancellationToken.None).Wait();
            Console.WriteLine("The token revoked");
        }
    }
}

Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Auth.OAuth2.Flows
Imports Google.Apis.Auth.OAuth2.Responses
Imports Google.Apis.Util.Store

' This program shows how to load a previously stored Google access token and revoke it.
'
' To run this program, select "GmailRevokeToken" in Project / project's Properties / Application tab / Startup object.
Public Class GmailRevokeToken
    Const gmailFullAccessScope As String = "https://mail.google.com/"

    Public Shared Sub Main(args As String())
        Dim initializer As New GoogleAuthorizationCodeFlow.Initializer() With { _
            .ClientSecrets = New ClientSecrets() With { _
                .ClientId = "Your Client ID, like 0123-abcd.apps.googleusercontent.com", _
                .ClientSecret = "Your Client Secret, like 0a1b2c3d" _
            } _
        }
        initializer.DataStore = New FileDataStore(GoogleWebAuthorizationBroker.Folder)
        Dim flow As New GoogleAuthorizationCodeFlow(initializer)

        Console.WriteLine("Will load the saved access token")
        Dim token As TokenResponse = flow.LoadTokenAsync("user", CancellationToken.None).Result

        If token Is Nothing Then
            Console.WriteLine("No saved token found")
        Else
            ' Revoking an expired token is not possible, we need to refresh it first.
            If token.IsExpired(flow.Clock) Then
                Console.WriteLine("Will renew the access token")
                token = flow.RefreshTokenAsync("user", token.RefreshToken, CancellationToken.None).Result
            Else
                Console.WriteLine("Token renewal not needed")
            End If

            Console.WriteLine("Will revoke the saved access token now")
            flow.RevokeTokenAsync("user", token.AccessToken, CancellationToken.None).Wait()
            Console.WriteLine("The token revoked")
        End If
    End Sub
End Class

Using custom storage for Google tokens

All samples in this article use the default file storage where each token is stored as C:\Users\UserName\AppData\Roaming\Google.Apis.Auth\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user file where user is what you pass in Google API methods ("user" string in this article). This is how Google API internally works.

However, you may implement your own custom IDataStore and use it instead of the default FileDataStore (recommended approach). Or, you can do all the work of storing or reading token data separately and manually construct Google token objects - this approach is easier for demonstration purposes. MailBee.NET ASP.NET OAuthMVC5 samples use it to show utilizing AspNetUserClaims database table as tokens storage.

In production apps, you can implement custom IDataStore based on AspNetUserClaims table (useful for ASP.NET apps) or any other storage of your choice. For instance, Microsoft version of this sample (MicrosoftLogin class) stores token data in a JSON-serialized text file.

Sample projects overview

All the code in this tutorial is available in GmailEasyLogin, GmailLogin and GmailRevokeToken classes of OAuthConsoleApps project. WinForms version is available in FormMain class of GoogleOAuthWinForms project.

All samples are available in both C# and VB versions.

GmailEasyLogin provides the common means of using Google OAuth provider: it lets you get, refresh and persist OAuth access tokens, determine the e-mail address of the user, check the user's inbox via IMAP. Google API is quite functional so there is a good chance GmailEasyLogin sample will be enough for your needs.

GoogleLogin adds revoking and deleting persisted access tokens, the ability not to request the e-mail address of the user (useful if you already know it but don't want the user to let your application see their profile), sending e-mail via SMTP.

GoogleOAuthWinForms sample has most features of GoogleLogin class of OAuthConsoleApps but uses async methods instead. Thus, it doesn't block UI during send e-mail or check e-mail operations. All operations can be canceled by hitting ESC or closing the app.

Get source code

All C# and VB samples discussed in this article (GoogleOAuthWinForms and OAuthConsoleApps) are shipped with MailBee.NET Objects installer and get installed into My Documents\MailBee.NET Objects\Samples\WinForms\NET 4.5 OAuth folder.

.NET Core 2.0 C# console sample can be found at My Documents\MailBee.NET Objects\Samples\WinForms\.NET Core 2.0\C#\GoogleRegularAccounts folder.

Send feedback to AfterLogic


OAuth 2.0 for Google Apps Service Accounts (installed and web applications)

Google Service Accounts which are available for Google Apps (G Suite) paid subscriptions enable access from a single service account to all regular e-mail accounts of the domain (to which that service account is linked), without knowing their passwords.

  • Prepare a service account
  • Using MailBee.NET and Google API to access an e-mail account via your service account
  • Installed app version
  • Web app version
  • Get source code

Prepare a service account

If you don't yet have a service account for your domain, you can create it in Google Developer Console:

When creating a new service account, be sure to sure to enable Domain-wide Delegation.

Note that you can enable Domain-wide Delegation for G Suite accounts only. You can learn more at Creating a service account.

The last step during creating a service account is creating keys. Download and save the private key for later use (select P12 format when downloading). The default password assigned by Google to the private key file is notasecret.

Also, remember the generated value of Client ID (in Domain-wide Delegation section) which is SomeID.apps.googleusercontent.com. The e-mail address of the service account will be SomeID@developer.gserviceaccount.com. SomeID itself looks like 01234567890-j348a3hnsd8923hs78mkdu3no5i2dk72.

Then, log in Google Admin Console and then grant your newly created service account the permission to access e-mail via IMAP/SMTP:

  • Specify your SomeID.apps.googleusercontent.com as Client Name.
  • Specify https://mail.google.com/ as the scope value. Do NOT remove trailing slash character in that URL!

Again, Creating a service account documentation can provides more details on this.

Using MailBee.NET and Google API to access an e-mail account via your service account

First, make sure you have Google APIs .NET library. In NuGet Package Manager Console, run:

Install-Package Google.Apis.Auth

To add MailBee.NET Objects reference:

Install-Package MailBee.NET

Alternatively, you can use Add Reference dialog to plug the local copy of MailBee.NET.dll (if you have one) to your project.

Now, let's write some code. It's assumed user@some-googleapps-domain.com account (the user account to which we'll connect via IMAP or SMTP) belongs to the domain controlled by your service account.

Installed app version

The example is a console app.

  • C#
  • VB
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using MailBee;
using MailBee.ImapMail;
using MailBee.SmtpMail;

// This program gets OAuth access token for Google user account via a service account of the domain
// that user account belongs to.
// Then, the program checks that user's inbox via IMAP or sends an e-mail from that account via SMTP.
public class Program
{
    public static void Main(string[] args)
    {
        string serviceAccountEmail = "SomeID@developer.gserviceaccount.com";
        string userEmail = "user@some-googleapps-domain.com";

        X509Certificate2 certificate = new X509Certificate2(@"C:\Temp\a...0-privatekey.p12",
            "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
               User = userEmail,
               Scopes = new string[] { "https://mail.google.com/" }
           }.FromCertificate(certificate));

        if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
        {
            string xoauthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

            // Uncomment and set your key if you haven't specified it in app.config or Windows registry.
            // MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here";

            bool useImap = true; // Set to false to use SMTP (send e-mail) instead of IMAP (check Inbox).

            if (useImap)
            {
                Imap imp = new Imap();

                // Logging is not necessary but useful for debugging.
                imp.Log.Enabled = true;
                imp.Log.Filename = @"C:\Temp\log.txt";
                imp.Log.HidePasswords = false;
                imp.Log.Clear();

                imp.Connect("imap.gmail.com");
                imp.Login(userEmail, xoauthKey, AuthenticationMethods.SaslOAuth2,
                    AuthenticationOptions.None, null);
                imp.SelectFolder("INBOX");
                Console.WriteLine(imp.MessageCount.ToString() + " e-mails in Inbox");
                imp.Disconnect();
            }
            else
            {
                Smtp mailer = new Smtp();
                mailer.SmtpServers.Add("smtp.gmail.com", null, xoauthKey, AuthenticationMethods.SaslOAuth2);

                // Logging is not necessary but useful for debugging.
                mailer.Log.Enabled = true;
                mailer.Log.Filename = @"C:\Temp\log.txt";
                mailer.Log.HidePasswords = false;
                mailer.Log.Clear();

                mailer.From.Email = userEmail;
                mailer.To.Add(userEmail);
                mailer.Subject = "empty email to myself";
                mailer.Send();
                Console.WriteLine("E-mail sent");
            }
        }
        else
        {
            Console.WriteLine("Can't get the access token");
        }
    }
}

Imports System.Security.Cryptography.X509Certificates
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail

' This program gets OAuth access token for Google user account via a service account of the domain
' that user account belongs to.
' Then, the program checks that user's inbox via IMAP or sends an e-mail from that account via SMTP.
Public Class Program
    Public Shared Sub Main(args As String())
        Dim serviceAccountEmail As String = "SomeID@developer.gserviceaccount.com"
        Dim userEmail As String = "user@some-googleapps-domain.com"

        Dim certificate As New X509Certificate2("C:\Temp\a...0-privatekey.p12", _
            "notasecret", X509KeyStorageFlags.Exportable)

        Dim credential As New ServiceAccountCredential( _
            New ServiceAccountCredential.Initializer(serviceAccountEmail) With { _
            .User = userEmail, _
            .Scopes = New String() {"https://mail.google.com/"} _
        }.FromCertificate(certificate))

        If credential.RequestAccessTokenAsync(CancellationToken.None).Result Then
            Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

            ' Uncomment and set your key if you haven't specified it in app.config or Windows registry.
            ' MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here"

            Dim useImap As Boolean = True ' Set to False to use SMTP (send e-mail) instead of IMAP (check Inbox).

            If useImap Then
                Dim imp As New Imap()

                ' Logging is not necessary but useful for debugging.
                imp.Log.Enabled = True
                imp.Log.Filename = "C:\Temp\log.txt"
                imp.Log.HidePasswords = False
                imp.Log.Clear()

                imp.Connect("imap.gmail.com")
                imp.Login(userEmail, xoauthKey, AuthenticationMethods.SaslOAuth2, AuthenticationOptions.None, Nothing)
                imp.SelectFolder("INBOX")
                Console.WriteLine(imp.MessageCount.ToString() & " e-mails in Inbox")
                imp.Disconnect()
            Else
                Dim mailer As New Smtp()
                mailer.SmtpServers.Add("smtp.gmail.com", Nothing, xoauthKey, AuthenticationMethods.SaslOAuth2)

                ' Logging is not necessary but useful for debugging.
                mailer.Log.Enabled = True
                mailer.Log.Filename = "C:\Temp\log.txt"
                mailer.Log.HidePasswords = False
                mailer.Log.Clear()

                mailer.From.Email = userEmail
                mailer.To.Add(userEmail)
                mailer.Subject = "empty email to myself"
                mailer.Send()
                Console.WriteLine("E-mail sent")
            End If
        Else
            Console.WriteLine("Can't get the access token")
        End If
    End Sub
End Class

For simplicity, this app does not use async methods of MailBee.NET library. However, you can easily adapt it to async, e.g. replace Connect with ConnectAsync and so on.

Web app version

The case of web apps is surprisingly similar to installed apps. We'll assume our web app is based on the MVC5 template created in Visual Studio (although this approach can be used for other types of web apps as well).

Simplicity and uniformity are key benefits of OAuth for service accounts, in contrast to OAuth for regular accounts which is more complex and very different for installed and web apps.

The below is the full contents of Controllers\HomeController.cs(vb) which is the only file we modified in the standard MVC5 template.

  • C#
  • VB
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Web.Mvc;
using Google.Apis.Auth.OAuth2;
using MailBee;
using MailBee.ImapMail;
using MailBee.SmtpMail;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            string serviceAccountEmail = "SomeID@developer.gserviceaccount.com";
            string userEmail = "user@some-googleapps-domain.com";

            X509Certificate2 certificate = new X509Certificate2(@"C:\Temp\a...0-privatekey.p12",
                "notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   User = userEmail,
                   Scopes = new string[] { "https://mail.google.com/" }
               }.FromCertificate(certificate));

            if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
            {
                string xoAuthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

                // Uncomment and set your key if you haven't specified it in app.config or Windows registry.
                // MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here";

                bool useImap = true; // Set to false to use SMTP (send e-mail) instead of IMAP (check Inbox).

                if (useImap)
                {
                    Imap imp = new Imap();

                    // Logging is not necessary but useful for debugging.
                    imp.Log.Enabled = true;
                    imp.Log.Filename = @"C:\Temp\log.txt";
                    imp.Log.HidePasswords = false;
                    imp.Log.Clear();

                    imp.Connect("imap.gmail.com");
                    imp.Login(userEmail, xoAuthKey, AuthenticationMethods.SaslOAuth2,
                        MailBee.AuthenticationOptions.None, null);
                    imp.SelectFolder("Inbox");
                    ViewBag.Message = imp.MessageCount.ToString() + " message(s) in INBOX";
                    imp.Disconnect();
                }
                else
                {
                    Smtp mailer = new Smtp();
                    mailer.SmtpServers.Add("smtp.gmail.com", null, xoAuthKey, AuthenticationMethods.SaslOAuth2);

                    // Logging is not necessary but useful for debugging.
                    mailer.Log.Enabled = true;
                    mailer.Log.Filename = @"C:\Temp\log.txt";
                    mailer.Log.HidePasswords = false;
                    mailer.Log.Clear();

                    mailer.From.Email = userEmail;
                    mailer.To.Add(userEmail);
                    mailer.Subject = "empty email to myself";
                    mailer.Send();
                    ViewBag.Message = "E-mail sent";
                }
            }
            else
            {
                ViewBag.Message = "Can't get the access token";
            }

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Imports System.Security.Cryptography.X509Certificates
Imports System.Threading
Imports System.Web.Mvc
Imports Google.Apis.Auth.OAuth2
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail

Public Class HomeController
    Inherits Controller
    Public Function Index() As ActionResult
        Return View()
    End Function

    Public Function About() As ActionResult
        Dim serviceAccountEmail As String = "SomeID@developer.gserviceaccount.com"
        Dim userEmail As String = "user@some-googleapps-domain.com"

        Dim certificate As New X509Certificate2("C:\Temp\a...0-privatekey.p12", _
            "notasecret", X509KeyStorageFlags.Exportable)

        Dim credential As New ServiceAccountCredential( _
            New ServiceAccountCredential.Initializer(serviceAccountEmail) With { _
            .User = userEmail, _
            .Scopes = New String() {"https://mail.google.com/"} _
        }.FromCertificate(certificate))

        If credential.RequestAccessTokenAsync(CancellationToken.None).Result Then
            Dim xoAuthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

            ' Uncomment and set your key if you haven't specified it in app.config or Windows registry.
            ' MailBee.Global.LicenseKey = "Your MNXXX-XXXX-XXXX key here"

            Dim useImap As Boolean = True ' Set to False to use SMTP (send e-mail) instead of IMAP (check Inbox).

            If useImap Then
                Dim imp As New Imap()

                ' Logging is not necessary but useful for debugging.
                imp.Log.Enabled = True
                imp.Log.Filename = "C:\Temp\log.txt"
                imp.Log.HidePasswords = False
                imp.Log.Clear()

                imp.Connect("imap.gmail.com")
                imp.Login(userEmail, xoAuthKey, AuthenticationMethods.SaslOAuth2, _
                    MailBee.AuthenticationOptions.None, Nothing)
                imp.SelectFolder("Inbox")
                ViewBag.Message = imp.MessageCount.ToString() & " message(s) in INBOX"
                imp.Disconnect()
            Else
                Dim mailer As New Smtp()
                mailer.SmtpServers.Add("smtp.gmail.com", Nothing, xoAuthKey, AuthenticationMethods.SaslOAuth2)

                ' Logging is not necessary but useful for debugging.
                mailer.Log.Enabled = True
                mailer.Log.Filename = "C:\Temp\log.txt"
                mailer.Log.HidePasswords = False
                mailer.Log.Clear()

                mailer.From.Email = userEmail
                mailer.To.Add(userEmail)
                mailer.Subject = "empty email to myself"
                mailer.Send()
                ViewBag.Message = "E-mail sent"
            End If
        Else
            ViewBag.Message = "Can't get the access token"
        End If

        Return View()
    End Function

    Public Function Contact() As ActionResult
        ViewBag.Message = "Your contact page."
        Return View()
    End Function
End Class

Get source code

Console C# and VB samples discussed in this article are shipped with MailBee.NET Objects installer and get installed into My Documents\MailBee.NET Objects\Samples\WinForms\NET 4.5 OAuth\CS\GoogleServiceAccounts folder (\VB\GoogleServiceAccounts for VB version).

For ASP.NET version, you simply need to create ASP.NET MVC app and replace Controllers\HomeController.cs(vb) as stated in the previous topic.

Send feedback to AfterLogic


OAuth 2.0 with IMAP/SMTP for Microsoft Outlook.com and Google Gmail in ASP.NET MVC5 applications

  • Introduction
  • Note on Google Service Accounts
  • MVC5 OAuth 2.0 technology features and limitations
  • OAuthMVC5 project summary
  • The steps to get things done
  • Considerations for "web server is your local machine" case
  • Register Google project
  • Google Client ID and Client Secret
  • Enable access to Google e-mail address, IMAP and SMTP services
  • Register Microsoft project
  • Microsoft Client ID and Client Secret
  • Create Visual Studio MVC5 project for Google OAuth provider
  • Create Visual Studio MVC5 project for Microsoft OAuth provider
  • Setting custom domain
  • Setting SSL certificate on custom domain (makes sense for Microsoft over https, not needed for Google-only)
  • Associating port with custom domain (not required for localhost)
  • Add references
  • OAuthMVC5 sample goals
  • OAuthMVC5 overview
    • OAuth provider configuration
    • Preparing OAuth tokens for use
    • Check or send e-mail with XOAUTH2 key
    • Other changes to the standard MVC5 template
  • ExternalProviders library overview
  • Refreshing access tokens
  • Syncing access tokens between AspNetUserClaims table and ASP.NET cookies
  • Using and refreshing access tokens in non-web applications
  • Get source code

This is the older version of OAuth 2.0 tutorial for web apps. It was intended for classic ASP.NET (not ASP.NET Core). Also, it assumes that Microsoft OAuth provider does not support localhost redirect_uri (which is no longer true) and explains how you can create a custom local domain. You can follow simpler route explained in the modern version of this tutorial which focuses on creating OAuth-enabled ASP.NET Core 2.0 app.

Introduction

You can create a C# or VB web application which is able access Microsoft or Google account of a user via IMAP and SMTP without knowing the password of this user. This works with all the domains these providers support, such as:

  • Microsoft - Outlook.com, Live.com, Hotmail.com
  • Google - Gmail.com
  • No Yahoo there - they still don't support OAuth for IMAP or SMTP :-(

We developed OAuthMVC5 sample which encapsulates the matters mentioned in this tutorial. You can open/edit this sample (see Get source code for details) or create your own ASP.NET project.

To write or build OAuthMVC5 sample, you need at least Visual Studio 2013 with .NET 4.5.1, MVC5, OWIN/Katana, ASP.NET Identity 2.0, and provider-specific OAuth 2.0 libraries - Microsoft's DotNetOpenAuth and Google APIs.

Update: Visual Studio 2015 and 2017 with .NET 4.6 is supported as well. However, .NET Core is not supported because Microsoft and Google OAuth 2.0 client libraries have't been ported to .NET Core yet.

The sample can work via both plain http and secure https. This tutorial includes the instructions for configuring local IIS Express server in both http and https modes on localhost and custom domains.

MailBee.NET Objects library provides means of OAuth 2.0 capable IMAP/SMTP client.

OAuthMVC5 sample was developed in both C# and VB versions.

Note on Google Service Accounts

Google Apps platform provides the special way of accessing user accounts in your domain with Service Accounts. IT'S VERY SIMPLE and can be used for both installed and web apps just the same way. See Google OAUTH2 for Service Accounts tutorial to learn more.

Microsoft does not yet support the concept of service accounts.

MVC5 OAuth 2.0 technology features and limitations

The current version of MVC (MVC5 at the moment of writing) provides native means of external authentication (including OAuth 2.0) using OWIN interface and its implementation for Windows, Katana.

However, this API and Visual Studio MVC5 template provide only basic means of OAuth 2.0 functionality, while some important matters like refreshing short-lived access tokens are not fully covered. It also lacks the ability to share access tokens obtained during OAuth process with other applications (such as Windows services which need to perform background activities in the user's account). This tutorial aims to address these issues as well.

OAuthMVC5 project summary

OAuthMVC5 sample highlights these aspects related to OAuth 2.0 development with ASP.NET MVC5:

  • Creating Google and Microsoft projects in their developer consoles.
  • Configuring Visual Studio IIS Express to support connections from both Google and Microsoft providers to a web application on your local machine (for development and testing). No 3rd-party services like ngrok are utilized.
  • Support of multiple providers. You can have multiple external logins associated with a user at the same time and thus multiple e-mail addresses per user (e.g. Microsoft and Google accounts attached to a single user account in your system). And we don't rely on the fact that a user's e-mail address is always the same as the external login's e-mail (although they can be the same, no problem with that).
  • Storing access tokens and related data in ASP.NET Identity database in addition to ASP.NET cookies (the standard MVC5 OAuth 2.0 implementation uses cookies only). This enables other parts of the code (and even other applications) to access this data.
  • Requesting Offline mode and refreshing access tokens (by default, they last just for an hour which may not be acceptable).
  • Checking a user's inbox via IMAP or sending an e-mail via SMTP using OAuth 2.0 for login.
  • A number of debugging tools such as the ability to use non-encrypted ASP.NET OWIN cookies (Startup.EncryptCookies, lets you see when and how these cookies change), logging of IMAP and SMTP sessions, ExternalProviderHelper.AccessTokenFastExpiration mode for testing of how exactly access tokens expire and how they get refreshed.

Most of the provider-specific code resides in a separate ExternalProviders library which is, just like OAuthMVC5 core project, available in both C# and VB versions.

The steps to get things done

The below is the common description of the procedure. Every step will be explained in detail in subsequent sections.

  • Register a project in Microsoft or Google developer console (or in both consoles if you want to support both providers). This way you notify Microsoft or Google servers on how they can let their users authorize your application to access their data.
  • Create ASP.NET application and select MVC template. Alternatively, open OAuthMVC5 C# or VB project.
  • Configure IIS Express if you want to develop the app on your local machine which does not have the assigned external host name. This is required even if you opened the existing OAuthMVC5 sample (many IIS Express settings are machine-specific and cannot be deployed with an ASP.NET project).

Other steps are only needed if you're creating a new ASP.NET project (rather than using OAuthMVC5 sample):

  • Add reference to ExternalProviders library. If you wish, you can move ExternalProviders source code inside your project instead of linking it as a separate library.
  • With NuGet, add references to MailBee.NET and other required libraries. The exact list depends on which providers you support (ExternalProviders already links both Google-specific and Microsoft-specific libraries).
  • Modify App_Start\Startup.Auth.cs(vb) to initialize OAuth logic.
  • Modify Controllers\AccountController.cs(vb) and ManageController.cs(vb) to inject some additional calls.
  • Add the logic to actually deal with IMAP or SMTP. In this sample, we do all the mail connections and related tasks like refreshing access tokens in Controllers\HomeController.cs(vb) code.

Considerations for "web server is your local machine" case

If you develop on your local machine (IIS Express), it can be tricky to support both Microsoft and Google providers for the same application, especially if you want to use HTTPS. This is because Microsoft and Google may provide the means for accessing local servers differently. This tutorial provides the unified way which works for both providers simultaneously.

However, if you need to support only a single provider, you can configure things in a simpler way (this tutorial covers the simple way as well).

In short, Google allows your project to reside at localhost domain (the default domain in IIS Express) while Microsoft does not allow for localhost name, they require you to have some unique string in the domain name instead.

Thus, if you want to support Microsoft (or both Microsoft and Google) in your web app, your local URL must be http://unique-string.com[:port]. Port can be omitted in theory but local IIS Express usually runs on non-standard ports so you'll need it.

The above covers the situation at the moment of writing. For instance, Microsoft or Google may decide to require https someday. This tutorial also provides HTTPS way as well, and https://unique-string.com[:port] approach is unlikely to get outdated by Microsoft or Google in the foreseeable future.

EDIT As of 2019, Microsoft now permits using localhost (just like Google). No need to create a custom local domain any longer. You can now use http://localhost:port for both Microsoft and Google.

Register Google project

Skip this if you target Microsoft provider only.

First, you need to register a project in your Google Developer Console:

If you already have a Google project where you have credentials for an installed application, you can just create web application credentials for that project instead of creating a new project (useful in case if you want to have both web and Windows installed applications use the same credentials).

Now, at "API Manager/Credentials/OAuth consent screen" section specify your support e-mail address and your product name. People will see this info when authorizing your application on access to your mailbox:

Click Save.

Then, at "API Manager/Credentials/Credentials" section click Create Credentials and select OAuth Client ID. Create a new Client ID selecting "Web application" type, you can leave any name for client ID.

In this chapter, https protocol is being used for screenshots and examples. Use http in all URLs if you don't need https for your development server.

If you plan to support Google only (and drop Microsoft), use localhost domain:

Or, if you want to support both Microsoft and Google, use https://unique-string.com:44301/ instead of https://localhost:44301/.

I originally developed localhost version and then edited it to idh.mailbee.test.com for compatibility with Microsoft provider (but I could have used idh.mailbee.test.com from the very beginning with the same effect):

With localhost or unique-string.com choice, you can follow any of these three routes:

  1. Use localhost domain only (if Google is all you need).

  2. Start with localhost domain, quickly make Google work with your app, then change it to unique-string.com and make Microsoft work as well.

  3. Use unique-string.com domain from the very beginning and do both Microsoft and Google at once.

For #2 and #3 it's up to you to decide if you want to split a bigger task into two smaller ones or solve it as a whole. Just note that configuring IIS Express and Windows for https://localhost is much easier than for https://unique-string.com. For plain http, http://unique-string.com is not so hard to configure but http://localhost is still easier.

Now, let's have a closer look at the settings.

Authorized JavaScript Origins must point to the URL of your application.

In Google-only case, we set it as https://localhost:44301/ for the following purposes:

  • We'll use local ASP.NET development server (Visual Studio built-in IIS Express), that's why it's localhost.
  • If you're using https, the default SSL ports in Visual Studio web apps will start from 44300. It's incremented by 1 with every new SSL web app you create in Visual Studio. OAuthMVC5 C# and VB samples in this tutorial use ports 44300 or 44301, respectively. If you're unsure which port to specify to Google at this point, you can update it anytime later (when you already have a port assigned by Visual Studio to your application).
  • If you're using http, the port will likely be an arbitrary number such as 7690, 12969, etc. IIS Express can allocate any free port for that. At this point, you don't know which port to specify as your web app is not created yet but you can easily adjust the port number in Edit Client Settings dialog at any time later.

In case of Microsoft+Google, there is https://idh.mailbee.test.com:44301/. You can use something like https://whatever-but-unique.com:44301/ (Microsoft won't allow you to use the domain name someone else has already used for their project).

Authorized Redirect URI denotes the particular URL where Google will redirect the application upon successful authorization. Set it to:

  • https://localhost:44301/signin-google for Google-only case
  • https://whatever-but-unique.com:44301/signin-google for Microsoft+Google case.

Or, if you're on http:

  • http://localhost:12969/signin-google for Google-only case
  • http://whatever-but-unique.com:12969/signin-google for Microsoft+Google case. Again, the exact port number value is not important at this time and can be adjusted later.

EDIT As of 2019, you can use localhost for both Microsoft and Google. Custom domain is no longer necessary.

MVC5 template in Visual Studio by default reserves /signin-google as the redirect landing page so we tell Google to redirect there. Actually, it can be changed but we're fine with the default value.

Now, in "API Manager/Credentials/OAuth consent screen" section specify your support e-mail address and your product name. People will see this info when authorizing your application to access their mailboxes:

Also, make sure you have email, profile and openid scopes added in Scopes for Google APIs section:

Google Client ID and Client Secret

In "API Manager/Credentials/Credentials" section, click your web client's name to grab your Client ID and Client Secret which you'll specify in your ASP.NET app later:

Enable access to Google e-mail address, IMAP and SMTP services

You will also need to go to "API Manager/Library" and locate "Gmail API" and "Google+ API":

Click and enable "Gmail API" to let your application authenticate in Gmail services with XOAUTH2 (OAuth 2.0 extension for IMAP and SMTP):

Finally, repeat the same for "Google+ API" to let your application see the e-mail address of the user:

There can be a few minutes delay on Google end for these changes to take effect.

Register Microsoft project

Skip this if you target Google provider only.

Create an application in Application Registration Portal. You may need to create an account there first.

For OAuth 2.0, you create a Live SDK application. Click Add an app in Live SDK applications section.

EDIT As of 2019, creating Converged application seems to work better because it allows you to use localhost endpoints on your local server rather than custom domain (which can be tricky).

On the next screen, click Add Platform and and select Web application, then save changes. You'll be redirected to the App Registration page:

Application ID (Client ID) and password (application secret) are there as well.

You'll need to use your own unique domain name in Redirect URLs. This tutorial assumes you'll enter the same domain name and port you set for Google project (this will let you use the same ASP.NET app for both Microsoft and Google).

As you can see on the screenshot, we're using https there. You can use http if this is your development server. However, in production it's strongly recommended to use https anyway.

Finally, /signin-microsoft part of the URL is the default redirect target page for Microsoft provider in the MVC5 template.

Microsoft Client ID and Client Secret

On the same App Registration page, you can grab your Client ID and Client Secret which you'll specify in your ASP.NET app later:

In case if you created a Converged application (not Live SDK application), make sure to add the required permissions (scopes) as well:

Create Visual Studio MVC5 project for Google OAuth provider

Run Visual Studio as Administrator (might be needed for IIS Express configuration in case if you're using custom domain name, not localhost).

Instead of creating a new ASP.NET app, you can open OAuthMCV5 sample.

First we'll create a project which is configured to support Google (runs on localhost), and then modify it to support Microsoft as well (custom-domain-name).

Create a new ASP.NET Web Application (C# or VB) and click OK:

If you have multiple choices there, select ASP.NET Web Application (.NET Framework):

Select MVC template and leave other values in their default state (Individual User Accounts, no Azure, etc):

In Visual Studio 2013/2015/2017, this creates a so-called ASP.NET MVC5 project.

Now, if you want https for your app, enable SSL in the project:

Visual Studio assigns the SSL port automatically. In case if it's not 44301 (or whatever you specified when creating Client ID in Google Developer Console), you have two options:

  • Update port number in Authorized JavaScript Origins and Authorized Redirect URI fields in Google Developer Console.
  • Or, close Visual Studio project and edit IISExpressSSLPort in .csproj or .vbproj file manually.

Note that you cannot have two projects with the same port number open at the same time (that's why Visual Studio increments port number for every new project).

Now copy SSL URL value into buffer. In my case, it's https://localhost:44303/.

If you're on http, copy URL value instead. For instance, http://localhost:12969/.

Then open WebApplication Properties in Projects menu, select Web tab and paste it into "Project Url" and "Override application root URL" fields (setting the checkbox if necessary):

And click Create Virtual Directory button. Run the project to make sure it successfully opens at that URL.

If you're on https, Visual Studio may ask you to generate a self-signed certificate for localhost. Confirm that to let the browser trust your https://localhost connection. For this to succeed, Visual Studio must run as Administrator.

You don't need to always run Visual Studio as Administrator, this is needed only at the stage of configuring the application and IIS Express.

You can now update the port number in Google Developer Console to match the exact value assigned by Visual Studio.

Create Visual Studio MVC5 project for Microsoft OAuth provider

Run Visual Studio as Administrator.

Instead of creating a new ASP.NET app, you can open OAuthMCV5 sample.

You can create a new ASP.NET Web Application (C# or VB) just the same way it was described for Google:

...and then configure it for some custom domain name. Recommended if you never did Google app (i.e. you need Microsoft alone).

Or, you can upgrade the app you already created for Google to make it use non-localhost domain name (if you need both Microsoft and Google).

By default, Visual Studio wizard assigns ASP.NET apps to use localhost domain which is not allowed by Live SDK applications. To make an ASP.NET app running under IIS Express use another domain, follow this guide.

EDIT As of 2019, Microsoft now permits using localhost (for Converged applications but not for Live SDK applications). No need to create a custom local domain any longer. You can now use http://localhost:port for both Microsoft and Google.

Setting custom domain

EDIT As of 2019, setting custom domain for local server is now optional in case if you created a Converged application on apps.dev.microsoft.com portal. You can use localhost which is much easier to set up.

This part is inspired by this great article: Custom domain url in IIS Express with Visual Studio 2013. Here's my version:

  • Go to your hosts file under C:\Windows\System32\drivers\etc and add:

    127.0.0.1 unique-string.com

    UAC may prevent the file from writing so you must run the text editor as Administrator. Alternatively, copy the file somewhere, edit it normally and then copy back. You may also need to temporarily disable your antivirus program as they often block access to that file.

  • In Project menu, select your project's Properties, then Web tab.

  • If you're using https, check "Override application root URL", type https://unique-string.com:port (the same host and port you specified at apps.dev.microsoft.com, https://idh.mailbee.test.com:44301 in my case).

  • If you're using http, check "Override application root URL", type http://unique-string.com:port (the same host and port you specified at apps.dev.microsoft.com, such as http://idh.mailbee.test.com:12969).
  • Click "Create Virtual Directory". This may not succeed if Visual Studio is not being run under Administrator.
  • Update Project Url to https://unique-string.com:port.
  • Go to your IIS Express settings under C:\Users<YourUser>\Documents\IISExpress\config and open the applicationhost.config file.

  • Find your site and adjust the binding (I used idh.mailbee.test.com as my unique-string.com value):

    <site name="WebApplication1" id="15">
  <application path="/" applicationPool="Clr4IntegratedAppPool">
    <virtualDirectory path="/" physicalPath="C:\Projects\WebApplication1" />
  </application>
  <bindings>
    <binding protocol=”https” bindingInformation=”*:44301:idh.mailbee.test.com” />
    <binding protocol=”http” bindingInformation=”*:12969:idh.mailbee.test.com” />
  </bindings>

44301 entry will be there only if you enabled SSL for your project (https case). Adjust the binding for http or https depending on which protocol you're using. - Run your ASP.NET app to see if it now opens on the custom domain. If you're using the custom domain with https, the browser will complain that the certificate is not trusted. Follow the next step if this bothers you.

Setting SSL certificate on custom domain (makes sense for Microsoft over https, not needed for Google-only)

Skip this chapter if you're on plain http or using localhost.

Setting SSL certificate on custom domain is only required if you cannot live with browser warnings (or you cannot add an exception in the browser to avoid them in the future). Complete this step only if want to configure a trusted self-signed certificate for your custom domain (like Visual Studio does for localhost).

If you want a custom domain on your local server and at the same time want to use https in IIS Express and avoid browser warnings, follow the instructions below.

This will work with Chrome and IE only. Firefox does not use Windows storage of certificates. In Firefox, you can add a security exception.

Basically, the idea is to generate a self-signed certificate for your custom local domain, then register this certificate in IIS Express and Windows.

  • Run Visual Studio command line tools as Administrator. I used "VS2013 x64 Native Tools Command Prompt" as I have 64-bit Windows.
  • Run makecert -r -pe -n "CN=idh.mailbee.test.com" -a sha512 -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss Root -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 (you need to correct CN parameter to your custom domain name). This creates a certificate for the specified domain name and adds it to the Trusted Root of this machine.

    sha512 value for -a (algorithm) parameter is very important. Otherwise, Chrome will complain your certificate is too weak.

  • Locate this certificate in Certificate Manager (for instance, in Chrome settings), and select its Thumbprint (copy carefully, the first char there is whitespace and must not be selected):

  • Run netsh http delete sslcert ipport=0.0.0.0:44301 (correct the port number if it's not 44301 in your case). This command may fail in case if no assignment for this port exists in Windows. That's OK, we just make sure nobody else has attached their certificate to this port.

  • To associate this port with the certificate we created, type netsh http add sslcert ipport=0.0.0.0:44301 appid={314124ce-d05c-4309-9af9-9caa44b2b74c} certstorename=Root certhash=881fb7579f4e07087249354c823a3b7b24ab7402 You need to specify your own hash in certhash parameter so paste the copied Thumbprint and remove all spaces between chars. appid does not need correction, any value works. Run the command.
  • Restart your Chrome or IE (whatever you're using).
  • Run your app (assuming you run Visual Studio as Administrator). It should now open at https://your-custom-domain.com:port without browser warnings.

The guide above was inspired by Working with SSL at Development Time is easier with IISExpress article by Scott Hanselman. However, the original article uses more complex approach when the certificate is first created in another place and thus needs to be moved manually with MMC console. This is troublesome and, moreover, works only until reboot.

If you ever decide to delete changes you made to certificate and SSL port associations:

  • Open Certificate Manager via MMC console (like explained in the Scott's original article), select Trusted Root Certification Authorities folder, locate your-domain-name certificate there and remove. Ignore Windows warnings that it's not safe (Windows does not know the certificate you're about to delete was not part of the system but was added by you).
  • Run Visual Studio command line tools as Administrator.
  • Run netsh http delete sslcert ipport=0.0.0.0:44301 (assuming that your SSL port number is 44301).

Associating port with custom domain (not required for localhost)

Skip this chapter if you always run Visual Studio as Administrator or if you're on localhost (Google-only case).

Make sure you run Command line as Administrator.

Now, run netsh http add urlacl url=https://idh.mailbee.test.com:44301/ user=everyone (correct the domain and port to match your case, e.g. url=http://idh.mailbee.test.com:12969/ if you're on http).

The above lets you avoid running Visual Studio as Administrator in order to start your app. Without this command, IIS Express will be unable to start listening on the given port if not being run as Administrator.

Now restart Visual Studio in normal mode (not as Administrator), and make sure the app starts without IIS Express errors in system tray.

To ever delete urlacl association, open Command line as Administrator and run netsh http delete urlacl url=https://idh.mailbee.test.com:44301/ (correct url to your domain name and port).

Add references

OAuthMVC5 sample references ExternalProviders library (included in the solution as a project) and MailBee.NET Objects.

In your own projects, you'll need to add references to MailBee.NET and ExternalProviders. To add MailBee.NET reference, open NuGet console and type:

Install-Package MailBee.NET

For ExternalProviders library, you have 3 ways:

  • Include ExternalProviders as a project to your solution and reference it from your main project in Add Reference / Solution / Projects (recommended).
  • Or, build ExternalProviders into .DLL and just reference that .DLL file.
  • Or, move the code files from ExternalProviders into your main project. In this case, you'll also need to add references to Google and Microsoft OAuth libraries used by ExternalProviders (see below).

In your own projects you'll also need to make sure "Microsoft.Owin.Security" and "Microsoft ASP.NET Identity Framework" packages are referenced. ASP.NET MVC5 template should add them by default, however.

If you get compilation errors like 'System.Web.HttpContextBase' does not contain a definition for 'GetOwinContext', make sure Microsoft.Owin.Host.SystemWeb is referenced.

In case if you added ExternalProviders code files right inside your project, add references to their dependencies in NuGet console:

Install-Package DotNetOpenAuth
Install-Package Google.Apis.Auth
Install-Package Google.Apis
Install-Package Google.Apis.Oauth2.v2
Update-Package

The above assumes you need support for both Microsoft and Google OAuth providers.

If you need just Microsoft, Google packages are not needed. You must remove GoogleProviderHelper.cs(vb) from ExternalProviders if you don't install these packages.

For Google-only case, DotNetOpenAuth package is not required, so remove MicrosoftProviderHelper.cs(vb) from ExternalProviders.

OAuthMVC5 sample goals

Our goal is to use OAuth tokens (received from Microsoft or Google during external authentication mechanism of an MVC5 app) for IMAP or SMTP authentication against the mail provider (Outlook.com, Live.com, Hotmail.com, Gmail). Once the authentication process is done, we can check the user's mailbox or send e-mails from that user.

By default, MVC5 template lets the developer enable OAuth 2.0 for Microsoft and Google but doesn't provide any means to read the received access token in other places of the application (the access token is by default available in an object which gets freed in the end of authentication procedure). We need to extract the access token received during the authentication and store it elsewhere in the application.

We also need to implement token refresh mechanism in case if the app must be able to access the user's mailbox without asking the user for permission every hour or so (because access tokens expire shortly). In other words, we want the app to support Offline access.

It would also be great if the received access token could be consumed by another application of us. For instance, the user logs in our web app with OAuth, then ANOTHER app running in background (such as a Windows service) will poll the user's mailbox for new e-mails and send SMS notifications on that. You can use ReadAspNetUsers sample to get the idea.

We achieve these goals with the following methods:

  • We modify the standard OAuth procedure of an MVC5 template by requesting Offline access. Usually Offline access is needed to be requested only once (to receive a refresh token). Once we have a refresh token, the access token can be renewed without user interaction.
  • We insert a callback in OAuth procedure to save the access tokens and refresh tokens in database. We use AspNetUserClaims table of ASP.NET Identity database for this (other apps can also use this table so we reach the goal of interoperability as well).

OAuthMVC5 overview

All the code is available in OAuthMVC5 samples (C# and VB). We'll now explore this sample in its C# version and explain the most interesting pieces. VB version is identical.

OAuthMVC5 project heavily uses ExternalProviders library which will be discussed later.

OAuth provider configuration

App_Start\Startup.Auth.cs contains templates of external authentication against Microsoft, Google, Facebook and other providers in ConfigureAuth method. We configured it for Microsoft and Google. Interesting part is that we also implemented OnAuthenticated callback. This lets us get the details of OAuth process (access tokens, refresh tokens, time-to-live) for later use.

Microsoft version

  • C#
  • VB
MicrosoftProviderHelper.Register(MicrosoftClientId, MicrosoftClientSecret);

MicrosoftAccountAuthenticationOptions microsoftOptions = new MicrosoftAccountAuthenticationOptions()
{
    ClientId = MicrosoftClientId,
    ClientSecret = MicrosoftClientSecret,
    Provider = new MicrosoftAccountAuthenticationProvider()
    {
        OnAuthenticated = (context) =>
        {
            MicrosoftProviderHelper tokenHelper = new MicrosoftProviderHelper();

            // Any exception here will result in 'loginInfo == null' in AccountController.ExternalLoginCallback.
            // Be sure to add exception handling here in case of production code.
            context.Identity.AddClaim(new Claim(tokenHelper.AccessTokenFieldName, context.AccessToken));

            // For clarity, we don't check most values for null but RefreshToken is another kind of thing. It's usually
            // not set unless we specially request it. Typically, you receive the refresh token only on the initial request,
            // store it permanently and reuse it when you need to refresh the access token.
            if (context.RefreshToken != null)
            {
                context.Identity.AddClaim(new Claim(tokenHelper.RefreshTokenFieldName, context.RefreshToken));
            }

            // We want to use the e-mail account of the external identity (for which we doing OAuth). For that we save
            // the external identity's e-mail address separately as it can be different from the main e-mail address
            // of the current user.
            context.Identity.AddClaim(new Claim(tokenHelper.EmailAddressFieldName, context.Email));
            context.Identity.AddClaim(new Claim(tokenHelper.NameFieldName, context.Name));

            context.Identity.AddClaim(new Claim(tokenHelper.TokenIssuedFieldName, DateTime.Now.ToString()));
            context.Identity.AddClaim(new Claim(tokenHelper.TokenExpiresInFieldName,
                ((long)context.ExpiresIn.Value.TotalSeconds).ToString()));

            return Task.FromResult(0);
        }
    }
};

microsoftOptions.Scope.Add(MicrosoftProviderHelper.MicrosoftScopeImap);
microsoftOptions.Scope.Add(MicrosoftProviderHelper.MicrosoftScopeEmailAddress);

if (RequireOfflineAccess)
{
    microsoftOptions.Scope.Add(MicrosoftProviderHelper.MicrosoftScopeOfflineAccess);
}

app.UseMicrosoftAccountAuthentication(microsoftOptions);

MicrosoftProviderHelper.Register(MicrosoftClientId, MicrosoftClientSecret)

Dim microsoftOptions As New MicrosoftAccountAuthenticationOptions() With { _
    .ClientId = MicrosoftClientId, _
    .ClientSecret = MicrosoftClientSecret, _
    .Provider = New MicrosoftAccountAuthenticationProvider() With { _
        .OnAuthenticated = _
        Function(context)
            Dim tokenHelper As New MicrosoftProviderHelper()

            ' Any exception here will result in 'loginInfo Is Nothing' in AccountController.ExternalLoginCallback.
            ' Be sure to add exception handling here in case of production code.
            context.Identity.AddClaim(New Claim(tokenHelper.AccessTokenFieldName, context.AccessToken))

            ' For clarity, we don't check most values for Nothing but RefreshToken is another kind of thing. It's usually
            ' not set unless we specially request it. Typically, you receive the refresh token only on the initial request,
            ' store it permanently and reuse it when you need to refresh the access token.
            If context.RefreshToken IsNot Nothing Then
                context.Identity.AddClaim(New Claim(tokenHelper.RefreshTokenFieldName, context.RefreshToken))
            End If

            ' We want to use the e-mail account of the external identity (for which we doing OAuth). For that we save
            ' the external identity's e-mail address separately as it can be different from the main e-mail address
            ' of the current user.
            context.Identity.AddClaim(New Claim(tokenHelper.EmailAddressFieldName, context.Email))
            context.Identity.AddClaim(New Claim(tokenHelper.NameFieldName, context.Name))

            context.Identity.AddClaim(New Claim(tokenHelper.TokenIssuedFieldName, DateTime.Now.ToString()))
            context.Identity.AddClaim(New Claim(tokenHelper.TokenExpiresInFieldName, CLng(context.ExpiresIn.Value.TotalSeconds).ToString()))

            Return Task.FromResult(0)
        End Function
    } _
}

microsoftOptions.Scope.Add(MicrosoftProviderHelper.MicrosoftScopeImap)
microsoftOptions.Scope.Add(MicrosoftProviderHelper.MicrosoftScopeEmailAddress)

If RequireOfflineAccess Then
    microsoftOptions.Scope.Add(MicrosoftProviderHelper.MicrosoftScopeOfflineAccess)
End If

app.UseMicrosoftAccountAuthentication(microsoftOptions)

Google version

  • C#
  • VB
GoogleProviderHelper.Register(GoogleClientId, GoogleClientSecret);

GoogleOAuth2AuthenticationOptions googleOptions = new GoogleOAuth2AuthenticationOptions()
{
    ClientId = GoogleClientId,
    ClientSecret = GoogleClientSecret,
    Provider = new GoogleOAuth2AuthenticationProvider()
    {
        OnAuthenticated = (context) =>
        {
            GoogleProviderHelper tokenHelper = new GoogleProviderHelper();

            // Any exception here will result in 'loginInfo == null' in AccountController.ExternalLoginCallback.
            // Be sure to add exception handling here in case of production code.
            context.Identity.AddClaim(new Claim(tokenHelper.AccessTokenFieldName, context.AccessToken));

            // For clarity, we don't check most values for null but RefreshToken is another kind of thing. It's usually
            // not set unless we specially request it. Typically, you receive the refresh token only on the initial request,
            // store it permanently and reuse it when you need to refresh the access token.
            if (context.RefreshToken != null)
            {
                context.Identity.AddClaim(new Claim(tokenHelper.RefreshTokenFieldName, context.RefreshToken));
            }

            // We want to use the e-mail account of the external identity (for which we doing OAuth). For that we save
            // the external identity's e-mail address separately as it can be different from the main e-mail address
            // of the current user.
            context.Identity.AddClaim(new Claim(tokenHelper.EmailAddressFieldName, context.Email));
            context.Identity.AddClaim(new Claim(tokenHelper.NameFieldName, context.Name));

            context.Identity.AddClaim(new Claim(tokenHelper.TokenIssuedFieldName, DateTime.Now.ToString()));
            context.Identity.AddClaim(new Claim(tokenHelper.TokenExpiresInFieldName,
                ((long)context.ExpiresIn.Value.TotalSeconds).ToString()));

            return Task.FromResult(0);
        }
    }
};

googleOptions.Scope.Add(GoogleProviderHelper.GoogleScopeProfile);
googleOptions.Scope.Add(GoogleProviderHelper.GoogleScopeEmailAddress);
googleOptions.Scope.Add(GoogleProviderHelper.GoogleScopeGmail);

// See AccountController.ChallengeResult.ExecuteResult on how to request Offline access with Google.

app.UseGoogleAuthentication(googleOptions);

GoogleProviderHelper.Register(GoogleClientId, GoogleClientSecret)

Dim googleOptions As New GoogleOAuth2AuthenticationOptions() With { _
    .ClientId = GoogleClientId, _
    .ClientSecret = GoogleClientSecret, _
    .Provider = New GoogleOAuth2AuthenticationProvider() With { _
        .OnAuthenticated = _
        Function(context)
            Dim tokenHelper As New GoogleProviderHelper()

            ' Any exception here will result in 'loginInfo Is Nothing' in AccountController.ExternalLoginCallback.
            ' Be sure to add exception handling here in case of production code.
            context.Identity.AddClaim(New Claim(tokenHelper.AccessTokenFieldName, context.AccessToken))

            ' For clarity, we don't check most values for Nothing but RefreshToken is another kind of thing. It's usually
            ' not set unless we specially request it. Typically, you receive the refresh token only on the initial request,
            ' store it permanently and reuse it when you need to refresh the access token.
            If context.RefreshToken IsNot Nothing Then
                context.Identity.AddClaim(New Claim(tokenHelper.RefreshTokenFieldName, context.RefreshToken))
            End If

            ' We want to use the e-mail account of the external identity (for which we doing OAuth). For that we save
            ' the external identity's e-mail address separately as it can be different from the main e-mail address
            ' of the current user.
            context.Identity.AddClaim(New Claim(tokenHelper.EmailAddressFieldName, context.Email))
            context.Identity.AddClaim(New Claim(tokenHelper.NameFieldName, context.Name))

            context.Identity.AddClaim(New Claim(tokenHelper.TokenIssuedFieldName, DateTime.Now.ToString()))
            context.Identity.AddClaim(New Claim(tokenHelper.TokenExpiresInFieldName, CLng(context.ExpiresIn.Value.TotalSeconds).ToString()))

            Return Task.FromResult(0)
        End Function
    } _
}

googleOptions.Scope.Add(GoogleProviderHelper.GoogleScopeProfile)
googleOptions.Scope.Add(GoogleProviderHelper.GoogleScopeEmailAddress)
googleOptions.Scope.Add(GoogleProviderHelper.GoogleScopeGmail)

' See AccountController.ChallengeResult.ExecuteResult on how to request Offline access with Google.

app.UseGoogleAuthentication(googleOptions)

To enable Offline mode for Google, something extra needs to be configured. OAuthMVC5\Controllers\AccountController.cs contains ChallengeResult class provided by the MVC5 template. We extended its ExecuteResult method to enable Offline access during OAuth process. It actually contains more code which you can find well-documented there but the most important line is:

  • C#
  • VB
properties.Dictionary[GoogleProviderHelper.GoogleAccessType] = GoogleProviderHelper.GoogleOfflineAccessType;

properties.Dictionary(GoogleProviderHelper.GoogleAccessType) = GoogleProviderHelper.GoogleOfflineAccessType

The above is Google-specific fix, Microsoft provider is configured for Offline mode just in ConfigureAuth method.

Due to some specifics of MVC5 external auth pipeline, token data gets lost after OAuth process completes, that's why we need to intercept this data before it's lost. In fact, we have to do this even twice:

  • First, we need to save data from context object in OnAuthenticated callback because it's local to this callback. We copy it to the user's claims dictionary.
  • However, the user's claims dictionary is cleared upon OAuth completion as it belongs to the external user's context. OWIN in MVC5 works the way that upon successful authentication the external user's context is removed and replaced with authenticated user's context. Therefore we need to save this data to database before the external user's context is gone.

We don't want to save to database immediately in OnAuthenticated callback because at that point it's not guaranteed that the entire authentication process succeeded yet (saving data at this point would probably cause out-of-sync situation when different parts of the app would have different opinion on whether or not the user has successfully logged in).

In OAuthMVC5\Controllers\AccountController.cs we also modified ExternalLoginCallback and ExternalLoginConfirmation methods to read token data from the external user's claims and save to AspNetUserClaims table (these methods are executed in different scenarios of logging in the user which has already been registered before). The same is done in LinkLoginCallback method in Controllers\ManageController.cs (it's executed when the user registers for the first time). The method call which saves token data to database looks like:

  • C#
  • VB
ExternalProviderHelper helper = ExternalProviderHelper.Create(loginInfo.Login.LoginProvider);
if (helper != null)
{
    await helper.MoveClaimsFromExternalIdenityToAuthenticatedUserAsync<ApplicationUser>(
        AuthenticationManager, UserManager, user.Id);
}

Dim helper As ExternalProviderHelper = ExternalProviderHelper.Create(info.Login.LoginProvider)
If helper IsNot Nothing Then
    Await helper.MoveClaimsFromExternalIdenityToAuthenticatedUserAsync(Of ApplicationUser)( _
        AuthenticationManager, UserManager, userInfo.Id)
End If

The database itself is in App_Data folder of the project, MVC5 template is already pre-configured to use it. See connectionStrings section in web.config if interested.

Preparing OAuth tokens for use

The actual IMAP/SMTP thing occurs in HomeController.MailAction (it replaces HomeController.About of the standard MVC5 template).

First, we extract the access token from AspNetUserClaims table, then check if it's already expired and refresh it if needed (updating AspNetUserClaims table and ASP.NET cookies accordingly).

  • C#
  • VB
ApplicationUser currentUser = UserManager.FindById(uid);

bool refreshed;
actualAccessToken = helper.GetActualAccessToken<ApplicationUser>(
    UserManager, uid, Startup.RequireOfflineAccess, out refreshed);

if (refreshed)
{
    // The previous method has refreshed the access token (and updated AspNetUserClaims accordingly). Now we need
    // to update the application cookie to save the updated identity claims there (as the claims need to be stored
    // in both places: AspNetUserClaims table and cookies).
    ClaimsIdentity identity = await currentUser.GenerateUserIdentityAsync(UserManager);
    HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
    HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
}

Dim currentUser As ApplicationUser = UserManager.FindById(uid)

Dim refreshed As Boolean
actualAccessToken = helper.GetActualAccessToken(Of ApplicationUser)(UserManager, uid, Startup.RequireOfflineAccess, refreshed)

If refreshed Then
    ' The previous method has refreshed the access token (and updated AspNetUserClaims accordingly). Now we need
    ' to update the application cookie to save the updated identity claims there (as the claims need to be stored
    ' in both places: AspNetUserClaims table and cookies).
    Dim identity As ClaimsIdentity = Await currentUser.GenerateUserIdentityAsync(UserManager)
    HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie)
    HttpContext.GetOwinContext().Authentication.SignIn(New AuthenticationProperties() With { _
        .IsPersistent = False _
    }, identity)
End If

helper is an instance of MicrosoftProviderHelper or GoogleProviderHelper classes from ExternalProviders library.

We also read the user's e-mail address from the database as it participates in building XOAUTH2 key required for IMAP or SMTP OAuth login. Then, we build that key.

  • C#
  • VB
ExternalUserProfile userProfile = helper.GetUserProfile(UserManager, uid);
string xoAuthKey = OAuth2.GetXOAuthKeyStatic(userProfile.EmailAddress, actualAccessToken);

Dim userProfile As ExternalUserProfile = helper.GetUserProfile(UserManager, uid)
Dim xoAuthKey As String = OAuth2.GetXOAuthKeyStatic(userProfile.EmailAddress, actualAccessToken)

Note that cannot use User.Identity.Name as the user's e-mail address. This address can be different from the external login's e-mail address. Also, this address is only one per user while there can be many external logins, each one with its own e-mail address.

Check or send e-mail with XOAUTH2 key

Finally we can use the XOAUTH2 key for authentication on Microsoft or Gmail server.

IMAP login:

  • C#
  • VB
Imap imp = new Imap();
imp.Connect(helper.ImapHost);
imp.Login(null, xoAuthKey, AuthenticationMethods.SaslOAuth2,
    MailBee.AuthenticationOptions.None, null);

Dim imp As Imap = New Imap()
imp.Connect(helper.ImapHost)
imp.Login(Nothing, xoAuthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, Nothing)

We're using the full name of MailBee.AuthenticationOptions type to avoid confusion with Microsoft.Owin.Security.AuthenticationOptions class.

Send e-mail with SMTP:

  • C#
  • VB
Smtp mailer = new Smtp();
mailer.SmtpServers.Add(helper.SmtpHost, null, xoAuthKey, AuthenticationMethods.SaslOAuth2);
mailer.From.Email = userProfile.EmailAddress;
mailer.From.DisplayName = userProfile.DisplayName;
mailer.To.Add(userProfile.EmailAddress, userProfile.DisplayName);
mailer.Subject = "empty email to myself";
mailer.Send();

Dim mailer As Smtp = New Smtp()
mailer.SmtpServers.Add(helper.SmtpHost, Nothing, xoAuthKey, AuthenticationMethods.SaslOAuth2)
mailer.From.Email = userProfile.EmailAddress
mailer.From.DisplayName = userProfile.DisplayName
mailer.To.Add(userProfile.EmailAddress, userProfile.DisplayName)
mailer.Subject = "empty email to myself"
mailer.Send()

You can use async methods instead, such as Imap.ConnectAsync, Smtp.SendAsync, etc. OAuthMVC5 sample uses exactly async methods.

If XOAUTH2 fails, the access token is invalid. For instance, this may happen if Offline access wasn't initially requested and the current access token expired as it can't be refreshed. Or, the application issued too many refresh tokens so that Microsoft or Google started to "forget" older tokens (for instance, Google remembers only 25 last tokens). Relogging in OAuthMVC5 app or clearing AspNetUsers and AspNetUserClaims tables may help.

Other changes to the standard MVC5 template

Startup.UnsecureTokenFormatter class in App_Start\Startup.Auth.cs enables you to turn off ASP.NET cookie encryption for debug purposes (see the class definition for details). This can be activated by setting Startup.EncryptCookies to false.

ManageLogins in Controllers\ManageController.cs was extended with better error handling. For instance, by default MVC5 template may just say you "error occurred" without any explanation (even when the external account you're trying to register just already exists in the database).

Views\Shared_Layout.cshtml now adds buttons to check mail with external providers, instead of About button.

Views\Home\MailAction.cshtml supersedes About.cshtml and provides "check mail" and "send mail" controls.

ExternalProviders library overview

Disclaimer: ExternalProviders is not a production-level software. To make it easier to explain how things work, they are often implemented not the best way possible. In your production apps, you may consider refactoring for sake of performance optimization or better conforming to ASP.NET development guidelines.

The library serves these purposes:

  • Getting provider-specific data (such as Microsoft or Google IMAP server name).
  • Storing access tokens, user profile and related data in AspNetUserClaims table.
  • Getting the user profile (ExternalProviderHelper.GetUserProfile method).
  • Refreshing access tokens.

ImapHost, SmtpHost and some other properties of MicrosoftProviderHelper and GoogleProviderHelper classes get provider-specific constants.

ExternalProviderHelper.MoveClaimsFromExternalIdenityToAuthenticatedUserAsync actually stores authentication data received from the external provider into AspNetUserClaims table.

Refreshing access tokens is the most interesting and bigger part.

Refreshing access tokens

Refreshing an access token enables the application to work with the user's Microsoft or Google account for more than an hour. We assume Offline access is enabled and we have the refresh token. The procedure:

  • Check if the access token stored in AspNetUserClaims is not expired.
  • If it's expired, use DotNetOpenAuth for Microsoft provider or Google API for Gmail to refresh the access token using the stored refresh token.
  • Update the access token in AspNetUserClaims table.

To find how exactly the methods of refreshing tokens for Microsoft and Google providers are implemented, refer to RefreshAccessTokenIfNeeded methods in the corresponding Helper classes.

Syncing access tokens between AspNetUserClaims table and ASP.NET cookies

Now you have the access token which is ready for use. However, there is a small side effect that the user's browser still keeps the previous version of the access token (we updated the database but not cookies). This out-of-sync is not a disaster as this cookie may never be used later but there is still a way to update it to keep ASP.NET cookie in sync with the copy in AspNetUserClaims table. Remember this code in HomeController.MailAction?

  • C#
  • VB
ClaimsIdentity identity = await currentUser.GenerateUserIdentityAsync(UserManager);
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);

Dim identity As ClaimsIdentity = Await currentUser.GenerateUserIdentityAsync(UserManager)
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie)
HttpContext.GetOwinContext().Authentication.SignIn(New AuthenticationProperties() With { _
    .IsPersistent = False _
}, identity)

This code does the trick (you may disable cookie encryption in Startup class and set breakpoints in Startup.UnsecureTokenFormatter class to actually see that the cookie gets updated). Again, even if you never update this cookie, there is a good chance you'll never get into trouble.

Also, the ASP.NET browser cookie may still go out-of-sync if you refresh the access token in another non-web application (see next topic). For instance, you have a console server app which runs on a timer and polls the user's mailbox every 10 minutes. This non-web application can access AspNetUserClaims table of your web application but it can't access the browser cookie as it works without any user interaction (so there is no browser to send cookie to). Still no big issue with that, however.

Using and refreshing access tokens in non-web applications

If you need to use access tokens stored in AspNetUserClaims table in other applications (such as Windows services which can do background activities in user accounts), check ReadAspNetUsers C#/VB samples in My Documents\MailBee.NET Objects\Samples\WinForms\.NET 4.5 OAuth folder.

The basic idea can be expressed as the code below:

  • C#
  • VB
IdentityDbContext dbCtx = new IdentityDbContext();
UserManager<IdentityUser> userMan = new UserManager<IdentityUser>(new UserStore<IdentityUser>(dbCtx));
IdentityUser user = userMan.FindByEmail(userEmail); // Primary e-mail address of the user.
string uid = user.Id;

// You may register only one provider if you don't need another one.
GoogleProviderHelper.Register(GoogleClientId, GoogleClientSecret);
MicrosoftProviderHelper.Register(MicrosoftClientId, MicrosoftClientSecret);

ExternalProviderHelper helper = ExternalProviderHelper.Create(provider); // "Microsoft" or "Google".
bool refreshed;
string accessToken = helper.GetActualAccessToken<IdentityUser>(userMan, uid, true, out refreshed);
string email = helper.GetUserProfile(userMan, uid).EmailAddress;
string xoAuthKey = MailBee.OAuth2.GetXOAuthKeyStatic(email, accessToken);

Imap imp = new Imap();
imp.Connect(helper.ImapHost);
imp.Login(null, xoAuthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, null);

Dim dbCtx As New IdentityDbContext()
Dim userMan As New UserManager(Of IdentityUser)(New UserStore(Of IdentityUser)(dbCtx))
Dim user As IdentityUser = userMan.FindByEmail(userEmail)
Dim uid As String = user.Id

' You may register only one provider if you don't need another one.
GoogleProviderHelper.Register(GoogleClientId, GoogleClientSecret)
MicrosoftProviderHelper.Register(MicrosoftClientId, MicrosoftClientSecret)

Dim helper As ExternalProviderHelper = ExternalProviderHelper.Create(provider)	' "Microsoft" or "Google".
Dim refreshed As Boolean
Dim accessToken As String = helper.GetActualAccessToken(Of IdentityUser)(userMan, uid, True, refreshed)
Dim email As String = helper.GetUserProfile(userMan, uid).EmailAddress
Dim xoAuthKey As String = MailBee.OAuth2.GetXOAuthKeyStatic(email, accessToken)

Dim imp As New Imap()
imp.Connect(helper.ImapHost)
imp.Login(Nothing, xoAuthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, Nothing)

ReadAspNetUsers sample actually provides more code including error checking, more explanations in code comments (including other ways to access users in AspNetUserClaims table), etc.

In case if you're searching the user by their e-mail address (with UserManager.FindByEmail method), be sure to specify the primary e-mail address of the user. External logins' e-mail addresses can be different (moreover, there can be multiple external logins per user account, each external login with its own e-mail address).

The sample also shows how to dynamically change the location where to find the ASP.NET Identity database (ChangeDataDirLocation method there). This lets ReadAspNetUsers sample use the database of OAuthMVC5 sample.

Get source code

All C# and VB samples discussed in this article are shipped with MailBee.NET Objects installer and get installed in My Documents\MailBee.NET Objects\Samples as follows:

  • OAuthMVC5 C# version: \ASP.NET\cs_2013_oauth_samples folder.
  • OAuthMVC5 VB version: \ASP.NET\vb_2013_oauth_samples folder.
  • ReadAspNetUsers C# version: \WinForms\NET 4.5 OAuth\C#\ReadAspNetUsers folder.
  • ReadAspNetUsers VB version: \WinForms\NET 4.5 OAuth\VB\ReadAspNetUsers folder.

ReadAspNetUsers sample is also available for .NET Core 2.0 (in \WinForms\.NET Core 2.0\C#\ReadAspNetUsers folder). It's a different sample intended for use with ASP.NET Core (and \ASP.NET\cs_netcore_oauth_samples\OAuthNetCoreMVC2 sample).

Send feedback to AfterLogic


OAuth 2.0 with IMAP/SMTP for Microsoft Outlook.com and Google Gmail in ASP.NET Core 2.0 MVC applications

  • Introduction
  • Note on Google Service Accounts
  • ASP.NET Core OAuth 2.0 technology features and limitations
  • OAuthNetCoreMVC2 project summary
  • The steps to get things done
  • Considerations for "web server is your local machine" case
  • Register Google project
  • Google Client ID and Client Secret
  • Enable access to Google e-mail address, IMAP and SMTP services
  • Register Microsoft project
  • Microsoft Client ID and Client Secret
  • Visual Studio ASP.NET Core MVC 2.0 project overview
  • Using and refreshing access tokens in non-web applications
  • Get source code

Introduction

You can create an ASP.NET Core web application which is able access Microsoft or Google account of a user via IMAP and SMTP without knowing the password of this user. This works with all the domains these providers support, such as:

  • Microsoft - Outlook.com, Live.com, Hotmail.com
  • Google - Gmail.com

We developed OAuthNetCoreMVC2 sample which encapsulates the matters mentioned in this tutorial. You can open/edit this sample (see Get source code for details) or create your own ASP.NET Core project.

To write or build OAuthNetCoreMVC2 sample, you need at least Visual Studio 2017 and .NET Core 2.0 or newer.

The sample works via https on localhost. To find instructions on how to configure a local IIS Express to run on a custom domain, see classic ASP.NET version of this tutorial.

localhost endpoint is intended for development only. In production, your app will run on its dedicated domain and you'll need to register the respective domains in Google and Microsoft admin panels.

OAuthNetCoreMVC2 sample was developed in C#.

Note on Google Service Accounts

Google Apps platform provides the special way of accessing user accounts in your domain with Service Accounts. IT'S VERY SIMPLE and can be used for both installed and web apps just the same way. See Google OAUTH2 for Service Accounts tutorial to learn more.

Microsoft does not yet support the concept of service accounts.

ASP.NET Core OAuth 2.0 technology features and limitations

The current version of ASP.NET Core provides native means of external authentication (including OAuth 2.0).

However, this API and Visual Studio MVC template provide only basic means of OAuth 2.0 functionality, while some important matters like refreshing short-lived access tokens are not fully covered. It also lacks the ability to share access tokens obtained during OAuth process with other applications (such as Windows services which need to perform background activities in the user's account). This tutorial aims to address these issues as well.

OAuthNetCoreMVC2 project summary

OAuthNetCoreMVC2 sample highlights these aspects related to OAuth 2.0 development with ASP.NET Core:

  • Creating Google and Microsoft projects in their developer consoles.
  • Configuring Visual Studio IIS Express to support connections from both Google and Microsoft providers to a web application on your local machine (for development and testing).
  • Support of multiple providers. You can have multiple external logins associated with a user at the same time and thus multiple e-mail addresses per user (e.g. Microsoft and Google accounts attached to a single user account in your system). And we don't rely on the fact that a user's e-mail address is always the same as the external login's e-mail (although they can be the same, no problem with that).
  • Storing access tokens and related data in AspNetUserTokens database table in addition to the cookies (the standard ASP.NET Core OAuth 2.0 implementation uses cookies only). This enables other parts of the code (and even other applications) to access this data.
  • Requesting Offline mode and refreshing access tokens (by default, they last just for an hour which may not be acceptable).
  • Checking a user's inbox via IMAP or sending an e-mail via SMTP using OAuth 2.0 for login.
  • A number of debugging tools such as logging of IMAP and SMTP sessions into a file, a special code path which refreshes access tokens on every request (to test token refresh mechanism without the need to wait an hour each time).

Unlike classic ASP.NET version, all the code is contained directly in the sample. There is no separate ExternalProviders library. In production, you're welcome to move all OAuth provider-specific code into a separate class or library.

The steps to get things done

The below is the common description of the procedure. Every step will be explained in detail in subsequent sections.

  • Register a project in Microsoft or Google developer console (or in both consoles if you want to support both providers). This way you notify Microsoft or Google servers on how they can let their users authorize your application to access their data.
  • Open OAuthNetCoreMVC2 project in My Documents\MailBee.NET Objects\Samples\ASP.NET\cs_netcore_oauth_samples. Alternatively, create ASP.NET Core application, select MVC template and set Individual Accounts for Authentication.

Other steps are only needed if you're creating a new ASP.NET project (rather than using OAuthMVC5 sample):

  • With NuGet, add references to MailBee.NET and Google.Apis.Auth (only if you need to support Google provider). For Microsoft provider, no additional libraries are used.
  • Modify Startup.cs to initialize OAuth logic.
  • Modify Controllers\AccountController.cs and ManageController.cs to inject some additional calls.
  • Add the logic to actually deal with IMAP or SMTP. In this sample, we do all the mail connections and related tasks like refreshing access tokens in Controllers\HomeController.cs code.

In OAuthNetCoreMVC2 we also made some changes to the templates to add some buttons (e.g. Send or Check Mail).

Considerations for "web server is your local machine" case

If you develop on your local machine (IIS Express or Kestrel), you'll most likely use localhost as the host name. Now both Microsoft and Google providers support this. In earlier days, you had to use a custom domain with Microsoft but this is no longer required.

For localhost, https is not required, http is fine. However, in production, when your real web host domain.com is used, https is a must. To it easier for you to make transition from localhost to the real Internet domain, we're using https://localhost here, even though https it's not required for localhost.

Register Google project

Skip this if you target Microsoft provider only.

First, you need to register a project in your Google Developer Console:

If you already have a Google project where you have credentials for an installed application, you can just create web application credentials for that project instead of creating a new project (useful in case if you want to have both web and Windows installed applications use the same credentials).

Now, at "API Manager/Credentials/OAuth consent screen" section specify your support e-mail address and your product name. People will see this info when authorizing your application on access to your mailbox:

Click Save.

Then, at "API Manager/Credentials/Credentials" section click Create Credentials and select OAuth Client ID. Create a new Client ID selecting "Web application" type, you can leave any name for client ID.

Now, let's have a closer look at the settings.

Authorized JavaScript Origins must point to the URL of your application.

We set it as https://localhost:44308/. Instead of 44308, there can be any number IIS Express associated for the port to run your web app on.

If you don't know which port to specify (e.g. your web app is not created yet), you can easily adjust the port number in Edit Client Settings dialog later.

Authorized Redirect URI denotes the particular URL where Google will redirect the application upon successful authorization. Set it to:

  • https://localhost:44308/signin-google

MVC template in Visual Studio by default reserves /signin-google as the redirect landing page so we tell Google to redirect there. Actually, it can be changed but we're fine with the default value.

Now, in "API Manager/Credentials/OAuth consent screen" section specify your support e-mail address and your product name. People will see this info when authorizing your application to access their mailboxes:

Also, make sure you have email, profile and openid scopes added in Scopes for Google APIs section:

Later, during the actual OAuth authorization process, your users may get "The app isn't verified" warning on the consent screen if you didn't confirm that your domain actually belongs to you in Google Developers Console. Obviously, localhost cannot be confirmed, so the users will have to click advanced to ignore this warning.

As soon as you run uploaded your web app on the actual Internet domain (not on localhost), you'll need to complete the domain Verification process ("API Manager/Credentials/Domain verification") to get rid of this warning.

Google Client ID and Client Secret

In "API Manager/Credentials/Credentials" section, click your web client's name to grab your Client ID and Client Secret which you'll specify in your ASP.NET app later.

Enable access to Google e-mail address, IMAP and SMTP services

You will also need to go to "API Manager/Library" and locate "Gmail API" and "Google+ API":

Click and enable "Gmail API" to let your application authenticate in Gmail services with XOAUTH2 (OAuth 2.0 extension for IMAP and SMTP):

Finally, repeat the same for "Google+ API" to let your application see the e-mail address of the user:

There can be a few minutes delay on Google end for these changes to take effect.

Register Microsoft project

Skip this if you target Google provider only.

Create an application in Application Registration Portal. You may need to create an account there first.

For OAuth 2.0, you should create a Converged application. Click Add an app in Converged applications section, then Add Platform in Platforms section and select Web.

Microsoft is changing things there often. You may be prompted to use Azure portal instead. Or, sometimes, Live SDK application performs better. Some trial and error may be needed to find out which options works for you. In our tests, both Converged application and Live SDK application worked well.

On the next screen, click Add Platform and select Web application, then save changes. You'll be redirected to the App Registration page:

In Application Secrets, click Generate New Password (in case of Converged application) and save the password for later use. Not needed for Live SDK application.

Add https://localhost:44308/signin-microsoft (or whatever port your ASP.NET Core app uses) in Redirect URLs section.

/signin-microsoft part of the URL is the default redirect target page for Microsoft provider in the MVC template.

In case of Live SDK application, Target Domain field is also displayed. You cannot specify localhost there, a unique domain must be used (even though it can be different from the one specified in the Redirect URL. We're using idh.mailbee.test.com. For Converged applications, you don't need to worry about Target Domain.

Be sure to add permissions to access the user's mailbox, retrieve their profile and email address. For that, in Microsoft Graph Permissions on the same page you need to add email, offline_access, profile, and User.Read:

Save changes.

Microsoft Client ID and Client Secret

On the same App Registration page, you can grab your Client ID and Client Secret which you'll specify in your ASP.NET Core app later:

Microsoft portal may show the password only once (in case of Converged application) so if you didn't save it elsewhere, you may not have a chance to retrieve it again (but you can create a new password instead).

Visual Studio ASP.NET Core MVC 2.0 project overview

The sample uses database (by default, mssqllocaldb), so need to run this in Nuget console:

Update-Database

If you want to change the database settings, you'll need to edit DefaultConnection in appsettings.json.

The app runs at https://localhost:44308 by default. If you run it from Visual Studio, it will be run under IIS Express by default. If you run it from the command line (compile.bat and run.bat in the project folder) or change the default configuration in Visual Studio, Kestrel web server will be used. In case of Kestrel, you'll need to set or generate a self-signed SSL certificate and let Kestrel know. That's how we do it (in Program.cs):

BuildWebHost

.UseKestrel(options =>
{
    options.Listen(IPAddress.Loopback, 44308, listenOptions =>
    {
        // Run this in the command line to create a self-signed cert if needed (assuming the current folder is the project folder):
        // dotnet dev-certs https -ep "localhost.pfx" -p 12345 --trust
        listenOptions.UseHttps("localhost.pfx", "12345");
    });
})

Again, the above won't have any effect in case if you're using IIS Express. For IIS Express, there is no need to generate the self-signed certificate, it will be supplied automatically.

Now, let's review the OAuth-specific code changes.

Startup.cs changes:

ConfigureServices

if (GoogleClientId != null)
{
    services.AddAuthentication().AddGoogle(googleOptions =>
    {
        googleOptions.ClientId = GoogleClientId;
        googleOptions.ClientSecret = GoogleClientSecret;
        googleOptions.Scope.Add("https://mail.google.com/");
        googleOptions.Scope.Add("profile");
        googleOptions.SaveTokens = true;
        googleOptions.AccessType = "offline";
        googleOptions.AuthorizationEndpoint += "?prompt=consent";
        googleOptions.Events.OnCreatingTicket = ctx =>
        {
        // This code is not need to run the sample. You can use for debugging (if you set a breakpoint here) to see which tokens are available to your application.
        List<AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();
            return Task.CompletedTask;
        };
    });
}

if (MicrosoftClientId != null)
{
    services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
    {
        microsoftOptions.ClientId = MicrosoftClientId;
        microsoftOptions.ClientSecret = MicrosoftClientSecret;
        microsoftOptions.SaveTokens = true;
        microsoftOptions.Scope.Add("wl.emails");
        microsoftOptions.Scope.Add("wl.offline_access");
        microsoftOptions.Scope.Add("wl.imap");
        microsoftOptions.TokenEndpoint = "https://login.live.com/oauth20_token.srf"; // The default endpoint doesn't support wl.* scopes so we're setting another one.
    });
}

In the above, we...

  • set scopes to request (they must match the scopes we enabled in the OAuth apps on the corresponding OAuth providers web sites)
  • demonstrate how OnCreatingTicket callback can be set (not required for tha app to run but lets you use the debugger to examine the tokens you application receives)
  • set SaveTokens to true (we need this to keep the tokens available to the code down the pipeline, this code will persist the tokens in the database)
  • change the default token endpoint for Microsoft provider because the default one does not support SMTP/IMAP related scopes (certainly a bug in their system) while the replacement seems to work well.

Controllers\AccountController.cs changes:

ExternalLoginCallback

// This will update access and refresh tokens in AspNetUserTokens table.
IdentityResult signInResult = await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

// This will update the user's display name and email in AspNetUserTokens table.
ApplicationUser appUser = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
await _userManager.SetAuthenticationTokenAsync(appUser, info.LoginProvider, Startup.DisplayName, info.Principal.Identity.Name);
await _userManager.SetAuthenticationTokenAsync(appUser, info.LoginProvider, Startup.Email, info.Principal.FindFirstValue(ClaimTypes.Email));

if (info.LoginProvider == Startup.MicrosoftProvider)
{
    // The current behavior of Microsoft server exhibits a bug. IMAP-related scopes are not enabled in the initial access token.
    // We need to refresh it at least once to have IMAP scopes included. Thus, we correct the expiration date to the current time.
    // This will make the token to be refreshed next time we access it (in HomeController).
    await _userManager.SetAuthenticationTokenAsync(appUser, Startup.MicrosoftProvider, Startup.ExpiresAt, DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture));
}

In the above, we...

  • persist the auth tokens in the database and also the e-mail address and the display name of the associated OAuth login
  • work around another currently existing bug of Microsoft provider because IMAP scopes only work for refreshed tokens (so we need to refresh it at least once).

ExternalLoginConfirmation - the same changes as in ExternalLoginCallback (in production app, you'll make a method or class to re-use the code and call this method from ExternalLoginCallback, ExternalLoginConfirmation, etc).

Controllers\ManageController.cs changes:

LinkLoginCallback - the same changes as above.

RemoveLogin

// Remove login data from AspNetUserTokens table.
_dbContext.UserTokens.RemoveRange(_dbContext.UserTokens.Where(ut => ut.UserId == user.Id && ut.LoginProvider == model.LoginProvider));
await _dbContext.SaveChangesAsync();

The above cleans up the tokens table in case if certain OAuth login is removed.

Controllers\HomeController.cs changes:

We...

  • define AccessTokenResponse class which respresents JSON response from Microsoft OAuth server
  • define DummyDataStore class, an instance of this class we'll then pass to Google Auth API (by default, Google API saves the tokens on the filesystem but we want to save them ourselves in AspNetUserTokens table so we're constructing a class which will prevent automatic saving tokens on the filesystem)
  • add parameters to HomeController constructor - public HomeController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
  • create GetGoogleTokenAsync and GetMicrosoftTokenAsync methods for reading (and refreshing if necessary) access tokens from the AspNetUserTokens table
  • create CheckInboxOrSendMail method which gets the access tokens for the desired provider and then uses them and MailBee.NET Objects to build XOAUTH2 key and then authenticates via IMAP/SMTP on Google or Microsoft mail servers to actually send or check e-mail.
private async Task<string> GetGoogleTokenAsync(ApplicationUser appUser, string externalAccessToken, string externalRefreshToken, DateTime externalExpiresAtUtc)
{
    TokenResponse token = new TokenResponse { AccessToken = externalAccessToken, RefreshToken = externalRefreshToken };

    // Dummy data source is used because we don't want RefreshTokenAsync to store anything to disk.
    // We'll store the token manually in the user's claims (AspNetUserClaims table).
    // Production code can be modified to implement custom IDataStore which will directly read/write
    // AspNetUserClaims table.
    UserCredential credential = new UserCredential(new GoogleAuthorizationCodeFlow(
        new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets() { ClientId = Startup.GoogleClientId, ClientSecret = Startup.GoogleClientSecret },
            DataStore = new DummyDataStore()
        }), null, token);

    DateTime nowUtcAdjusted = DateTime.UtcNow.AddMinutes(1);

    // Uncomment to test token refresh mechanism (uncommenting will make an access token expire every minute so you won't have to wait an hour for that).
    // nowUtcAdjusted = nowUtcAdjusted.AddMinutes(59);

    if (nowUtcAdjusted > externalExpiresAtUtc)
    {
        // Unfortunately, Google API v1.40 hangs here sometimes (especially if ClientID and ClientSecret are very long). Hopefully this will be fixed in newer versions.
        bool refreshResult = await credential.RefreshTokenAsync(CancellationToken.None);
        if (refreshResult)
        {
            externalAccessToken = credential.Token.AccessToken;
            await _userManager.SetAuthenticationTokenAsync(appUser, Startup.GoogleProvider, Startup.AccessToken, externalAccessToken);
            externalExpiresAtUtc = credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value);
            await _userManager.SetAuthenticationTokenAsync(appUser, Startup.GoogleProvider, Startup.ExpiresAt, externalExpiresAtUtc.ToString("o", CultureInfo.InvariantCulture));
        }
        else
        {
            return null;
        }
    }
    return externalAccessToken;
}

The above uses Google API to refresh access tokens. You can uncomment nowUtcAdjusted = nowUtcAdjusted.AddMinutes(59); line to make access token expire each time this page is accessed (by default, it will be refreshed every hour). This is useful for debugging in case if you want to test token refresh mechanism.

Updated token is saved in AspNetUserTokens table. Google API is not used for that.

private async Task<string> GetMicrosoftTokenAsync(ApplicationUser appUser, string externalAccessToken, string externalRefreshToken, DateTime externalExpiresAtUtc)
{
    const string refreshTokenUrl = "https://login.live.com/oauth20_token.srf";

    // We'll consider an access token expired if it expires in a minute from now.
    DateTime nowUtcAdjusted = DateTime.UtcNow.AddMinutes(1);

    // Uncomment to test token refresh mechanism (uncommenting will make an access token expire every minute so you won't have to wait an hour for that).
    // nowUtcAdjusted = nowUtcAdjusted.AddMinutes(59);

    if (nowUtcAdjusted > externalExpiresAtUtc)
    {
        // The code below refreshes an access token if it's expired or about to expire.
        // 'scope' parameter sets the IMAP/SMTP related scopes.
        HttpClient client = new HttpClient();
        string parameters = $"grant_type=refresh_token&refresh_token={ WebUtility.UrlEncode(externalRefreshToken) }&" +
            $"client_id={ WebUtility.UrlEncode(Startup.MicrosoftClientId) }&client_secret={ WebUtility.UrlEncode(Startup.MicrosoftClientSecret) }&" +
            $"scope={WebUtility.UrlEncode("wl.emails wl.offline_access wl.imap")}";
        var contentBody = new StringContent(parameters, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
        HttpResponseMessage response = await client.PostAsync(refreshTokenUrl, contentBody);
        if (!response.IsSuccessStatusCode)
        {
            // This can be useful for debugging.
            string errorMessage = await response.Content.ReadAsStringAsync();

            // You should process 400 (bad request) error here.
            return null;
        }
        else
        {
            AccessTokenResponse tokens;
            using (Stream responseStream = await response.Content.ReadAsStreamAsync())
            {
                var reader = new StreamReader(responseStream);
                string json = reader.ReadToEnd();
                reader.Close();
                tokens = JsonConvert.DeserializeObject(json, typeof(AccessTokenResponse)) as AccessTokenResponse;
            }
            externalAccessToken = tokens.AccessToken;
            await _userManager.SetAuthenticationTokenAsync(appUser, Startup.MicrosoftProvider, Startup.AccessToken, externalAccessToken);

            // Well, not absolutely accurate as we are using client's time, not server time but considering that we're refreshing tokens not waiting for full 60 minutes
            // (we have 30 seconds extra), a second or two of the difference shouldn't matter.
            externalExpiresAtUtc = DateTime.UtcNow.AddSeconds(tokens.Expiration);

            await _userManager.SetAuthenticationTokenAsync(appUser, Startup.MicrosoftProvider, Startup.ExpiresAt, externalExpiresAtUtc.ToString("o", CultureInfo.InvariantCulture));
        }
    }
    return externalAccessToken;
}

Microsoft version is similar although it does not use any specific API library from Microsoft but rather performs all OAuth requests directly via HttpClient.

public async Task<IActionResult> CheckInboxOrSendMail(string loginProvider, bool sendEmail)
{
    // Instead of passing loginProvider in parameters, we could have obtained it as below. We're not using this result, we just demonstrating other options and their effect.
    // The difference between loginProvider and externalProvider may occur if you connected more than one external login to your user (both Microsoft and Google). If so,
    // loginProvider might be Microsoft while externalProvider would be Google (if you're logged in with Google).
    // externalProvider can be even null if you registered with a login/password account (not externally) and then just added Microsoft or Google account.
    var externalProvider = User.FindFirstValue(ClaimTypes.AuthenticationMethod);

    ApplicationUser appUser = await _userManager.GetUserAsync(User);

    // Check that we're logged in.
    if (appUser != null)
    {
        string imapHost = null;
        string smtpHost = null;

        string externalAccessToken = await _userManager.GetAuthenticationTokenAsync(appUser, loginProvider, Startup.AccessToken);
        if (externalAccessToken != null)
        {
            DateTime externalExpiresAtUtc = DateTime.Parse(await _userManager.GetAuthenticationTokenAsync(appUser, loginProvider, Startup.ExpiresAt)).ToUniversalTime();
            string externalRefreshToken = await _userManager.GetAuthenticationTokenAsync(appUser, loginProvider, Startup.RefreshToken);

            switch (loginProvider)
            {
                case Startup.GoogleProvider:
                    externalAccessToken = await GetGoogleTokenAsync(appUser, externalAccessToken, externalRefreshToken, externalExpiresAtUtc);
                    imapHost = "imap.gmail.com";
                    smtpHost = "smtp.gmail.com";
                    break;
                case Startup.MicrosoftProvider:
                    externalAccessToken = await GetMicrosoftTokenAsync(appUser, externalAccessToken, externalRefreshToken, externalExpiresAtUtc);
                    imapHost = "imap-mail.outlook.com";
                    smtpHost = "smtp-mail.outlook.com";
                    break;
                default:
                    ViewBag.Message = "Unknown login provider";
                    externalAccessToken = null;
                    break;
            }

            if (externalAccessToken != null)
            {
                string email = appUser.Email; // Gives the primary e-mail of the current user. If it's your external provider email, that would be fine.

                // However, in case if you allow multiple logins (e.g. Microsoft, Google and login/password), the above won't work. That's why we store
                // the email address for each external provider's login. Get it from the database now.
                email = await _userManager.GetAuthenticationTokenAsync(appUser, loginProvider, Startup.Email);

                string displayName = await _userManager.GetAuthenticationTokenAsync(appUser, loginProvider, Startup.DisplayName);
                string xoAuthKey = OAuth2.GetXOAuthKeyStatic(email, externalAccessToken);

                try
                {
                    MailBee.Global.LicenseKey = Startup.MailBeeLicenseKey;
                }
                catch (MailBeeLicenseException e)
                {
                    ViewBag.Message = e.ToString();
                    return View();
                }

                if (!sendEmail)
                {
                    Imap imp = null;
                    try
                    {
                        imp = new Imap();
                    }
                    catch (MailBeeLicenseException e)
                    {
                        ViewBag.Message = e.ToString();
                        ViewBag.Log = "See or uncomment MailBee.Global.LicenseKey setting in HomeController.CheckInboxOrSendMail";
                    }

                    if (imp != null)
                    {
                        // Logging is optional but useful for debugging. We use memory logging to avoid issues
                        // with file permissions but you can configure the logger to write to a file if needed.
                        imp.Log.HidePasswords = false;
                        imp.Log.Enabled = true;
                        imp.Log.MemoryLog = true;

                        try
                        {
                            await imp.ConnectAsync(imapHost);
                            await imp.LoginAsync(null, xoAuthKey, AuthenticationMethods.SaslOAuth2,
                                MailBee.AuthenticationOptions.None, null);
                            await imp.SelectFolderAsync("INBOX");
                            ViewBag.Message = imp.MessageCount.ToString() + " message(s) in INBOX";
                            await imp.DisconnectAsync();
                        }
                        catch (MailBeeException e)
                        {
                            ViewBag.Message = e.ToString();
                        }
                        finally
                        {
                            ViewBag.Log = imp.Log.GetMemoryLog();
                            if (imp.IsConnected)
                            {
                                imp.Abort();
                            }
                        }
                    }
                }
                else
                {
                    Smtp mailer = null;
                    try
                    {
                        mailer = new Smtp();
                    }
                    catch (MailBeeLicenseException e)
                    {
                        ViewBag.Message = e.ToString();
                        ViewBag.Log = "See or uncomment MailBee.Global.LicenseKey setting in HomeController.MailAction";
                    }

                    if (mailer != null)
                    {
                        mailer.SmtpServers.Add(smtpHost, null, xoAuthKey, AuthenticationMethods.SaslOAuth2);

                        // Logging is not necessary but useful for debugging. See more details in IMAP section.
                        mailer.Log.HidePasswords = false;
                        mailer.Log.Enabled = true;
                        mailer.Log.MemoryLog = true;

                        mailer.From.Email = email;
                        mailer.To.Add(email, displayName);
                        mailer.Subject = "empty email to myself";

                        try
                        {
                            await mailer.SendAsync();
                            ViewBag.Message = "E-mail sent";
                        }
                        catch (MailBeeException e)
                        {
                            ViewBag.Message = e.ToString();
                        }
                        finally
                        {
                            ViewBag.Log = mailer.Log.GetMemoryLog();
                        }
                    }
                }
            }
            else
            {
                ViewBag.Message = "Error getting the access token";
            }
        }
        else
        {
            ViewBag.Message = "You need to log in with Google account";
        }
    }
    else
    {
        ViewBag.Message = "You need to log in first";
    }
    ViewBag.LoginProvider = loginProvider;
    return View();
}

The method above obtains the access token, refreshes it if necessary, builds XOAUTH2 key, and sends e-mail or displays the number of messages in the inbox. Log of the entire conversation with the mail server is displayed on the page (or the exception text in case of an error). Note that we set HidePasswords to false because XOAUTH2 keys are less sensitive then real passwords (XOAUTH2 key is based on an access token which lasts not longer than an hour). It doesn't mean you can expose XOAUTH2 keys freely, it just illustrates that exposing them is less security risk than exposing real passwords.

And don't forget to set your MailBee.NET license key in the value of Startup.MailBeeLicenseKey constant.

Using and refreshing access tokens in non-web applications

If you need to use access tokens stored in AspNetUserTokens table in other applications (such as Windows services which can do background activities in user accounts), check ReadAspNetUsers sample in My Documents\MailBee.NET Objects\Samples\WinForms.NET Core 2.0\C#.

The basic idea can be expressed as the code below:

Helper classes

    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationRole : IdentityRole
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
    }

Main method

static async Task Main(string[] args)
{
    DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>()
        .UseSqlServer(ConnectionString)
        .Options;
    ApplicationDbContext context = new ApplicationDbContext(options);
    var list = context.UserTokens.ToListAsync().Result;
    ApplicationUser user = await context.Users.FirstOrDefaultAsync();
    if (user != null)
    {
        List<IdentityUserToken<string>> tokens = await context.UserTokens.Where(t => t.UserId == user.Id).OrderBy(t => t.LoginProvider).ToListAsync();
        if (tokens.Count > 0)
        {
            string email = tokens.FirstOrDefault(t => t.Name == "Email")?.Value;
            string displayName = tokens.FirstOrDefault(t => t.Name == "DisplayName")?.Value;
            string loginProvider = tokens.FirstOrDefault()?.LoginProvider;
            IdentityUserToken<string> accessToken = tokens.FirstOrDefault(t => t.Name == "access_token");
            IdentityUserToken<string> exiresAt = tokens.FirstOrDefault(t => t.Name == "expires_at");
            if (loginProvider != null && accessToken != null && exiresAt != null)
            {
                DateTime expiresAtUtc = DateTime.Parse(exiresAt.Value).ToUniversalTime();
                DateTime nowUtcAdjusted = DateTime.UtcNow.AddMinutes(1);

                if (nowUtcAdjusted > expiresAtUtc)
                {
                    // Must renew the access token.
                    string refreshToken = tokens.FirstOrDefault(t => t.Name == "refresh_token")?.Value;
                    AspNetUsersAccessToken refreshedToken = null;
                    switch (loginProvider)
                    {
                        case "Google":
                            refreshedToken = await RefreshGoogleTokenAsync(refreshToken);
                            break;
                        case "Microsoft":
                            refreshedToken = await RefreshMicrosoftTokenAsync(refreshToken);
                            break;
                    }
                    if (refreshedToken == null)
                    {
                        return;
                    }
                    accessToken.Value = refreshedToken.AccessToken;
                    exiresAt.Value = refreshedToken.ExpiresAtString;
                    await context.SaveChangesAsync();
                }

                // Create XOAUTH2 key from the user's email and access token.
                string xoauthKey = OAuth2.GetXOAuthKeyStatic(email, accessToken.Value);

                ... now can use XOAUTH2 key for authenticating on the mail server, etc.
            }
        }
    }
}

By default, ReadAspNetUsers sample uses the database of OAuthNetCoreMVC2 sample.

Get source code

All samples discussed in this article are shipped with MailBee.NET Objects installer and get installed in My Documents\MailBee.NET Objects\Samples as follows:

  • OAuthNetCoreMVC2: \ASP.NET\cs_netcore_oauth_samples folder.
  • ReadAspNetUsers: \WinForms\.NET Core 2.0\C#\ReadAspNetUsers folder.

ReadAspNetUsers sample is also available for .NET Framework 4.5 (in \WinForms\.NET 4.5 OAuth\C#\ReadAspNetUsers folder). It's a different sample intended for use with ASP.NET for classic .NET Framework (and \ASP.NET\cs_2013_oauth_samples\OAuthMVC5 sample).

Send feedback to AfterLogic


OAuth 2.0 for Universal Windows apps

The idea is to demonstrate a UWP application which can access an account at Gmail.com (Google provider) or Outlook.com, Hotmail.com or Live.com (Microsoft provider) via IMAP and SMTP without knowing the password of that account.

  • The basic idea
  • Register Microsoft project
  • Register Google project
  • Create application in Visual Studio
  • Run application in Visual Studio

The basic idea

Unlike .NET Core version, we cannot use HttpListener to intercept the authorization code from the browser (UWP apps are not allowed to do that, at least not in production). Instead, we're using URL schema registration. The process is as follows:

  • We launch the system browser to open OAuth provider web site where ther user gives the consent to our application.
  • The provider web site then redirects to a page with certain URI protocol previously registered to our app. The system lets our app to process that page and grab the authorization code. The rest of the process is similar to other implementations (like for .NET Core, legacy .NET Framework and so on). In this guide, we use pw.oauth2 value for this protocol.

The advantage of the approach in this article is that it does not require you to keep OAuth ClientSecret in your app, storing ClientID is enough.

Register Microsoft project

This is needed only if you want to support Microsoft provider in your application.

Create an application in Application Registration Portal. You may need to create an account there first.

For OAuth 2.0, create a Live SDK application. Click Add an app in Live SDK applications section.

On the next screen, click Add Platform and select Native application, then save changes. If you already have an app (for instance, with Web platform added), you can add a platform to the existing app.

Application ID (Client ID) and is there, you'll need it in the UWP app later. Note that ClientSecret is not required.

Then add a pw.oauth2://oauth2redirect in Custom Redirect URIs section and save changes. pw.oauth2 must match the value from Package Manifest / Declarations / Protocol / Name of your UWP app. You can choose another name, just make sure it matches the name you selcted when adding a protocol in Package Manifest / Declarations. The protocol name must start with a letter and have a dot inside. oauth2redirect part is not important, can be anything, actually.

Make sure to add the required permissions (scopes) as well:

Microsoft is changing things there often. Sometimes, Live SDK app simply doesn't work and you may try creating a Converged application. Also, you may be asked to use Azure portal instead of apps.dev.microsoft.com site. At the moment of writing, Azure portal was not stable enough for that.

Register Google project

This is needed only if you want to support Google (Gmail.com) provider in your application.

First, you need to register a project in your Google Developer Console. See OAuth 2.0 for Google Regular Accounts (installed applications) how. The only difference is that you need to select iOS, not Other in Application type dialog. There is no UWP option but iOS option seems to work well.

Put a pw.oauth2 in Bundle ID field and click Create. pw.oauth2 must match the value from Package Manifest / Declarations / Protocol / Name of your UWP app. It's the protocol part of a redirectUri where the login provider will redirect upon the successful authorization.

You'll also need to set permissions to work with e-mail via IMAP/SMTP and access your e-mail address. See OAuth 2.0 for Google Regular Accounts (installed applications) how.

Configure application in Visual Studio

Open My Documents\MailBee.NET Objects\Samples\WinForms\.NET Core 2.0\C#\OAuthUniversalApp sample project.

In MainPage.xaml.cs, set MicrosoftClientID and/or GoogleClientID to the values you obtained from the respective providers. Set MailBeeLicenseKey field too.

If you changed the redirect URI protocol from pw.oauth2 value to something else, adjust RedirectUriProtocol constant as well.

Change _provider field from Google to Microsoft or vice versa, depending on which provider you want to test.

Run application in Visual Studio

Now build and run the application. How it works:

  • When the user clicks a button, we check if OAuth token data exists in ApplicationData.Current.LocalSettings the current folder. If yes, we read the stored OAuth token from there.
  • If no token available, we start the system browser which displays the consent screen on the OAuth login provider (Google or Microsoft) web site.
  • The user gives the consent and then the OAuth login provider's web site redirects the browser to pw.oauth2://oauth2redirect?code=somecode&some_other_params URI. Because pw.oauth2 URI protocol scheme is associated with our UWP app, the browser asks the user to let our app open this URI.
  • We then extract the authorization code from the URI. We also check some other parameters (state and code_verifier) to make sure the response from the login provider actually matches the original request from the UWP app.
  • We then use the authorization code to get the access and refresh tokens from the OAuth login provider, and store them in ApplicationData.Current.LocalSettings.
  • If the token is available, we check if the access token is not expired.
  • If the access token is expired, we refresh it using the refresh token. There is expiresAtUtc = expiresAtUtc.AddMinutes(-59); line which you can uncomment to test access token expiration without the need to wait for an hour (for debugging purposes).
  • Then, we get the profile of the user (e-mail address and display name). In production app, you should cache this info in the database to avoid getting the profile each time you're accessing the mailbox of the user (for performance sake).
  • We build XOAUTH2 key and use it to authenticate on the IMAP or SMTP server of the login provider, and display the number of e-mail in the inbox or send an e-mail from the user to themselves. useImap bool variable in the code controls whether the action to perform will be "checking mail" or "sending mail".

In case of Google, the redirect URI is pw.oauth2:/oauth2redirect, not pw.oauth2://oauth2redirect (single slash instead of double slash).

Miscellaneous:

  • This UWP app does not use any OAuth libraries from Microsoft or Google.
  • It targets .NETStandard 2.0 which (for UWP apps) requires Windows 10 Fall Creators Update or newer.
  • The app was tested on x86 and x64 platforms.

Send feedback to AfterLogic


Assembly Reference

This section lists the most frequently used classes of MailBee.NET Objects library.

Main classes

Class Name | Namespace | Description
Smtp | MailBee.SmtpMail | Sends single and bulk mail using SMTP protocol, makes forward and reverse DNS queries.
Pop3 | MailBee.Pop3Mail | Downloads mail from POP3 servers.
Imap | MailBee.ImapMail | Downloads and manages e-mails and folders on IMAP4 servers.
Ews | MailBee.EwsMail | Provides means for working with e-mails, folders and other items on MS Exchange and Office 365 server via Managed EWS API.
MailMessage | MailBee.Mime | Represents an e-mail message.
Smime | MailBee.Security | Encrypts, decrypts, signs and verifies e-mails (S/MIME).
DomainKeys | MailBee.Security | Signs and verifies e-mails (DomainKeys).
BayesFilter | MailBee.AntiSpam | Checks if e-mail is spam, by analyzing its content.
RblFilter | MailBee.AntiSpam | Checks if e-mail is spam, by looking up its originating IP address in online RBL DNS databases.
MsgConvert | MailBee.Outlook | Converts e-mails between Outlook .MSG and RFC822 .EML formats.
PstReader | MailBee.Outlook | Extracts folders, messages and other data from .PST files.
HtmlToPdf | MailBee.Pdf | Converts table-based HTML documents into PDF format.
EmailAddressValidator | MailBee.AddressCheck | Verifies a single e-mail address or a bulk of addresses for correct syntax or existence.
DeliveryStatusParser | MailBee.BounceMail | Checks if e-mail is delivery or non-delivery report.
MailBeeException | MailBee | The base class of all exceptions thrown by MailBee classes.

Helper classes for creating and displaying messages

Class Name | Namespace | Description
Attachment | MailBee.Mime | Represents an attachment or embedded picture.
AttachmentCollection | MailBee.Mime | Represents a list of attachments.
EmailAddress | MailBee.Mime | Represents an e-mail address (including display name and e-mail part).
EmailAddressCollection | MailBee.Mime | Represents a list of recipients.
MailMerge | MailBee.Mime | Provides advanced options for creating messages from templates.
MessageBuilderConfig | MailBee.Mime | Provides options for post-processing composed messages (such as creating plain-text version from HTML body).
MessageParserConfig | MailBee.Mime | Provides options for post-processing parsed messages (such as displaying embedded pictures).
Element | MailBee.Html | Allows the developer to manipulate Document Object Model of HTML documents (including HTML messages), remove or alter certain tags, examine the document structure, etc.

Helper classes for sending mail

Class Name | Namespace | Description
DeliveryNotificationOptions | MailBee.SmtpMail | Specifies Delivery Status Notification settings.
DnsServer | MailBee.DnsMX | Represents a DNS server to which send MX queries when no SMTP relay servers available.
DnsServerCollection | MailBee.DnsMX | Represents a list of DNS servers.
SmtpServer | MailBee.SmtpMail | Represents an SMTP relay server to send mail to.
SmtpServerCollection | MailBee.SmtpMail | Represents a list of SMTP relay servers.
SendMailJob | MailBee.SmtpMail | Represents a bulk mail job (sending multiple e-mails with or without database mail merge).

Miscellaneous classes

Class Name | Namespace | Description
ErrorCodes | MailBee | Lists all error codes defined in MailBee library.
Global | MailBee | Specifies MailBee library configuration settings.
Logger | MailBee | Provides file and memory logging capabilities for MailBee components.

Send feedback to AfterLogic


MailBee Namespace

MailBee.NET Objects
MailBee Namespace

MailBee namespace contains common classes, base classes, interface and enumerations used by all components in MailBee.NET Objects library.

Notable examples include clases for authentication, including OAuth 2, NTLM, Integrated Windows Authentication, classes for logging all activities into a file or memory, global settings, error-handling and exception related classes, and classes for localizing all messages generated by MailBee to other languages.

Classes
 | Class | Description
Public class | CommonEventArgs | Represents an abstract parent of all event data classes in MailBee.
Public class | ConnectedEventArgs | Contains the event data for Connected events (such as Smtp.Connected, Pop3.Connected or Imap.Connected).
Public class | DataTransferEventArgs | Contains the event data for data sending/receiving events (such as Smtp.DataSent, Smtp.DataReceived, Pop3.DataSent, Pop3.DataReceived, Imap.DataSent, Imap.DataReceived).
Public class | DisconnectedEventArgs | Contains the event data for Disconnected events (such as Smtp.Disconnected, Pop3.Disconnected or Imap.Disconnected).
Public class | ErrorCodes | Provides error code values returned by ErrorCode property of MailBee exceptions and LastResult property of MailBee classes implementing this property.
Public class | ErrorEventArgs | Contains the event data for ErrorOccurred events (such as Smtp.ErrorOccurred, Pop3.ErrorOccurred or Imap.ErrorOccurred).
Public class | Global | Provides properties specifying default values and parameter settings which apply to instances of all MailBee classes.
Public class | HostResolvedEventArgs | Contains the event data for HostResolved events (such as Smtp.HostResolved, Pop3.HostResolved or Imap.HostResolved).
Public class | LogEntry | Represents an entry to be added into the log file or memory log buffer.
Public class | LoggedInEventArgs | Contains the event data for LoggedIn events (such as Smtp.LoggedIn, Pop3.LoggedIn or Imap.LoggedIn).
 | Logger | Provides logging facilities for MailBee components such as Smtp, Pop3, and Imap.
Public class | LogNewEntryEventArgs | Contains the event data for LogNewEntry events (such as Smtp.LogNewEntry, Pop3.LogNewEntry or Imap.LogNewEntry).
Public class | MailBeeAbortedByRemoteHostException | The exception that is thrown when the remote host suddenly closes the connection.
Public class | MailBeeBatchException | The exception that is thrown when certain job in a batch of scheduled jobs fails and the component is configured to cancel processing in this case.
Public class | MailBeeConnectionException | An abstract parent for all connection-level exceptions which indicate the connection cannot be used any longer and must be immediately closed.
Public class | MailBeeDataParsingException | The exception that is thrown when an unexpected error occurs during converting a string or byte block into the required format (such as integer).
Public class | MailBeeDataSyntaxException | This exception indicates that MailBee determined that the data passed had wrong syntax.
Public class | MailBeeDateParsingException | The exception that is thrown when an unexpected error occurs during converting a string into DateTime.
Public class | MailBeeEmailProtocolException | An abstract parent for all exceptions which indicate that an e-mail protocol (such as POP3, IMAP4 or SMTP) error has occurred.
Public class | MailBeeEmailProtocolNegativeResponseException | An abstract parent for all exceptions which indicate that the mail server returned negative response, and the response data is available in text (i.e. string) form.
Public class | MailBeeException | An abstract parent for all exceptions which can be thrown by MailBee library.
Public class | MailBeeExternalException | The exception that is thrown when an error occurs in the code outside MailBee.
Public class | MailBeeGetHostNameException | An abstract parent for all exceptions that are thrown if an attempt to resolve a host name through the call of a method of Dns class failed.
Public class | MailBeeGetLocalHostNameException | The exception that is thrown if an attempt to get the local host name through the call of Dns class methods failed.
Public class | MailBeeGetRemoteHostNameException | The exception that is thrown if an attempt to resolve the remote host name through the call of Dns class methods failed.
Public class | MailBeeInternalException | The exception that is thrown when an unexpected error occurs in MailBee code.
Public class | MailBeeInvalidArgumentException | The exception that is thrown when an invalid argument value is passed to a method or property.
Public class | MailBeeInvalidResponseException | An abstract parent for all exceptions which indicate that a response received from the server cannot be parsed.
Public class | MailBeeInvalidStateException | The exception that is thrown when the requested operation cannot be performed in the current state.
Public class | MailBeeInvalidTextResponseException | The exception that is thrown when the text response received from the server cannot be parsed, and the response data is available.
Public class | MailBeeInvalidTextResponseItemException | The exception that is thrown when a particular element of the text response received from the server cannot be parsed, and the response data is available.
Public class | MailBeeIOException | The exception that is thrown when the IO operation with file or folder throws one of the following exceptions: IOException, UnauthorizedAccessException, FileNotFoundException, or XmlException.
Public class | MailBeeLicenseException | The exception that is thrown during instantiation of a MailBee component or calling a static (Shared in Visual Basic) method of a component in the case when no valid license has been assigned to the component.
Public class | MailBeeLocalException | The exception that is thrown when an error occurs due to user actions or problems with accessing local (not network) resources.
Public class | MailBeeLoginNoCredentialsException | The exception that is thrown when the authentication process cannot proceed, because no account name and/or password was provided by the application.
Public class | MailBeeLoginNoSupportedMethodsException | The exception that is thrown when the authentication process cannot proceed, because no authentication methods allowed by the application for authentication are supported by the server.
Public class | MailBeeLoginNotPossibleException | An abstract parent for all exceptions which indicate that the authentication process cannot proceed under current conditions.
Public class | MailBeeLoginWin32Exception | The exception that is thrown when underlying Win32 Schannel implementation of Integrated Windows Authentication returns an error.
Public class | MailBeeNetworkException | An abstract parent for all exceptions that are thrown when network errors occur.
Public class | MailBeeNoIP4HostFoundException | The exception that is thrown if no IPv4-compatible IP address was found for the given IPHostEntry during the connecting to the remote host.
Public class | MailBeeProtocolException | An abstract parent for all exceptions which indicate that an application-level protocol error has occurred.
Public class | MailBeeProtocolExtensionNotSupportedException | The exception that is thrown when the mail server does not support certain extension (capability) which is required for the current operation to complete successfully.
Public class | MailBeeRemoteHostException | An abstract parent for all exceptions which occur when MailBee attempts to establish connection or send/receive data to/from the server at the given IP address and port number.
Public class | MailBeeRemoteHostResponseTimeoutException | The exception that is thrown when the remote host returns the response so slowly that it cannot be tolerated by the client.
Public class | MailBeeSocketAbortedException | The exception that is thrown when underlying socket operation receives abort request from the software on the local machine and throws SocketException.
Public class | MailBeeSocketException | The exception that is thrown when underlying socket operation throws SocketException or IOException.
Public class | MailBeeSocketHostDownException | The exception that is thrown when underlying socket operation detects a dead host and throws SocketException.
Public class | MailBeeSocketHostNotFoundException | The exception that is thrown when underlying socket operation detects an unknown host and throws SocketException.
Public class | MailBeeSocketHostUnreachableException | The exception that is thrown when underlying socket operation detects there is no known route to the host and throws SocketException.
Public class | MailBeeSocketObjectDisposedException | The exception that is thrown when underlying socket operation unexpectedly throws ObjectDisposedException.
Public class | MailBeeSocketRefusedException | The exception that is thrown when underlying socket operation detects the remote machine refused the connection (which usually means no server program is running on the remote host) and throws SocketException.
Public class | MailBeeSocketResetException | The exception that is thrown when the connection was forcibly closed by the remote host so that underlying socket implementation throws SocketException.
Public class | MailBeeSocketTimeoutException | The exception that is thrown when underlying socket operation encounters a timeout and throws SocketException.
Public class | MailBeeStreamException | The exception that is thrown when the operation with data stream throws IOException.
Public class | MailBeeSystemSettingsException | The exception that is thrown when an attempt to request certain information from the system failed.
Public class | MailBeeUserAbortException | The exception that is thrown after Abort method of MailBee component has been called.
Public class | MailBeeWebException | The exception that is thrown when underlying network operation throws the WebException.
 | OAuth | This class provides methods for OAuth 1.0 authentication process.
 | OAuth2 | This class provides methods for OAuth 2.0 authentication process.
 | OpenID | Obsolete. This class provides methods for OpenID authentication process. It can be used with OAuth class for hybrid OpenID + OAuth authentication.
 | Resources | Provides localization and text customization framework for MailBee library.
 | SaslMethod | Provides a framework for developing custom SASL authentication mechanisms.
Public class | SocketConnectedEventArgs | Contains the event data for SocketConnected events (such as Smtp.SocketConnected, Pop3.SocketConnected or Imap.SocketConnected).
Public class | SocketCreatingEventArgs | Contains the event data for SocketCreating events (such as Smtp.SocketCreating, Pop3.SocketCreating or Imap.SocketCreating).
Public class | SortableByPriorityCollection | Represents an abstract parent for all MailBee collections sorted by Priority value of their elements.
Public class | TlsStartedEventArgs | Contains the event data for TlsStarted events (such as Smtp.TlsStarted, Pop3.TlsStarted or Imap.TlsStarted).
Interfaces
 | Interface | Description
Public interface | IMailBeeFatalException | When implemented by an exception class, indicates the exception is fatal and the component is no longer usable in the current state, so that any active tasks must be finished as soon as possible.
Public interface | IMailBeeLoginBadCredentialsException | When implemented by an exception class, indicates the authentication failed due to use of incorrect account name and/or password.
Public interface | IMailBeeLoginBadMethodException | When implemented by an exception class, indicates the server returned negative response during the authentication process because the requested authentication method is not available.
Public interface | IMailBeeLoginException | When implemented by an exception class, indicates the login process failed, and the application should try to authenticate using either another account name and password or another authentication method.
Public interface | IMailBeeLoginNegativeResponseException | When implemented by an exception class, indicates the server returned negative response during the authentication process, and the response data is available in text (i.e. string) form.
Public interface | IMailBeeNegativeResponseException | When implemented by an exception class, indicates the server returned negative response, and the response data is available.
Public interface | IMailBeeNegativeTextResponseException | When implemented by an exception class, indicates the server returned negative response, and the response data is available in text (i.e. string) form.
Public interface | IMailBeeSocketMustCloseException | When implemented by an exception class, indicates the network exception is connection level (not application protocol level), so that the connection is no longer valid and will be closed.
Public interface | IMailBeeWin32Exception | When implemented by an exception class, indicates that this exception is thrown when underlying Win32 function returns an error.
Delegates
 | Delegate | Description
Public delegate | ConnectedEventHandler | Represents the method that will handle Connected events (such as Smtp.Connected, Pop3.Connected or Imap.Connected).
Public delegate | DataTransferEventHandler | Represents the method that will handle events which occur on sending or receiving data to/from the server (such as Smtp.DataSent, Smtp.DataReceived, Pop3.DataSent, Pop3.DataReceived, Imap.DataSent, Imap.DataReceived).
Public delegate | DisconnectedEventHandler | Represents the method that will handle Disconnected events (such as Smtp.Disconnected, Pop3.Disconnected or Imap.Disconnected).
Public delegate | ErrorEventHandler | Represents the method that will handle ErrorOccurred events (such as Smtp.ErrorOccurred, Pop3.ErrorOccurred or Imap.ErrorOccurred).
Public delegate | HostResolvedEventHandler | Represents the method that will handle HostResolved events (such as Smtp.HostResolved, Pop3.HostResolved or Imap.HostResolved).
Public delegate | LoggedInEventHandler | Represents the method that will handle LoggedIn events (such as Smtp.LoggedIn, Pop3.LoggedIn or Imap.LoggedIn).
Public delegate | LogNewEntryEventHandler | Represents the method that will handle LogNewEntry events (such as Smtp.LogNewEntry, Pop3.LogNewEntry or Imap.LogNewEntry).
Public delegate | SocketConnectedEventHandler | Represents the method that will handle SocketConnected events (such as Smtp.SocketConnected, Pop3.SocketConnected or Imap.SocketConnected).
Public delegate | SocketCreatingEventHandler | Represents the method that will handle SocketCreating events (such as Smtp.SocketCreating, Pop3.SocketCreating or Imap.SocketCreating).
Public delegate | TlsStartedEventHandler | Represents the method that will handle TlsStarted events (such as Smtp.TlsStarted, Pop3.TlsStarted or Imap.TlsStarted).
Enumerations
 | Enumeration | Description
Public enumeration | AuthenticationMethods | Provides authentication methods to be used for logging in the user account on the server.
Public enumeration | AuthenticationOptions | Provides flags for tuning the authentication process.
 | LogFormatOptions | Provides flags which can be used to change formatting of log messages produced by MailBee.
Public enumeration | LogMessageType | Specifies the type of the log entry.
Public enumeration | TopLevelProtocolType | Defines types of MailBee main protocols.

Copyright © 2006-2019 AfterLogic Corporation. All rights reserved.

Send comments on this topic to AfterLogic


Event Classes

For ease of browsing the documentation, event and exception classes are brought together in the groups which are separate from other classes.

Send feedback to AfterLogic


CommonEventArgs Class

CommonEventArgs Class
Represents an abstract parent of all event data classes in MailBee.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
More...

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class CommonEventArgs : EventArgs
Public MustInherit Class CommonEventArgs
    Inherits EventArgs

The CommonEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components.
Top
See Also

Reference

MailBee Namespace
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.AddressCheckVerifiedEventArgs
MailBee.AddressCheckVerifyingEventArgs
MailBeeConnectedEventArgs
MailBeeDataTransferEventArgs
MailBeeDisconnectedEventArgs
MailBeeErrorEventArgs
MailBeeHostResolvedEventArgs
MailBee.ImapMailImapEnvelopeDataChunkReceivedEventArgs
MailBee.ImapMailImapEnvelopeDownloadedEventArgs
MailBee.ImapMailImapIdlingEventArgs
MailBee.ImapMailImapMessageStatusEventArgs
MailBee.ImapMailImapServerStatusEventArgs
MailBeeLoggedInEventArgs
MailBeeLogNewEntryEventArgs
MailBee.Pop3MailPop3MessageDataChunkReceivedEventArgs
MailBee.Pop3MailPop3MessageDownloadedEventArgs
MailBee.SmtpMailSmtpFinishingJobEventArgs
MailBee.SmtpMailSmtpMergingMessageEventArgs
MailBee.SmtpMailSmtpMessageDataChunkSentEventArgs
MailBee.SmtpMailSmtpMessageDirectSendDoneEventArgs
MailBee.SmtpMailSmtpMessageMXLookupDoneEventArgs
MailBee.SmtpMailSmtpMessageNotSentEventArgs
MailBee.SmtpMailSmtpMessageRecipientSubmittedEventArgs
MailBee.SmtpMailSmtpMessageSenderSubmittedEventArgs
MailBee.SmtpMailSmtpMessageSentEventArgs
MailBee.SmtpMailSmtpMessageSubmittedToPickupFolderEventArgs
MailBee.SmtpMailSmtpMessageSubmittedToServerEventArgs
MailBee.SmtpMailSmtpSendingMessageEventArgs
MailBee.SmtpMailSmtpSubmittingMessageToPickupFolderEventArgs
MailBee.SmtpMailSmtpTransientErrorOccurredEventArgs
MailBeeSocketConnectedEventArgs
MailBeeSocketCreatingEventArgs
MailBeeTlsStartedEventArgs


CommonEventArgs Methods

CommonEventArgs Methods

The CommonEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

CommonEventArgs Class
MailBee Namespace


CommonEventArgs Properties

CommonEventArgs Properties

The CommonEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components.
Top
See Also

Reference

CommonEventArgs Class
MailBee Namespace


CommonEventArgs.State Property

CommonEventArgsState Property
Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object State { get; }
Public ReadOnly Property State As Object
    Get

Property Value

Type: Object
A reference to the state object, or null (Nothing in Visual Basic) if the current event was generated by a synchronous method.
Remarks
State objects can be used by the developer in order to pass any data to event handlers. MailBee itself just passes the value of state parameter of asynchronous methods to this property, but does not use it in any other way.
See Also

Reference

CommonEventArgs Class
MailBee Namespace


ConnectedEventArgs Class

ConnectedEventArgs Class
Contains the event data for Connected events (such as Smtp.Connected, Pop3.Connected or Imap.Connected).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeConnectedEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ConnectedEventArgs : CommonEventArgs
Public Class ConnectedEventArgs
    Inherits CommonEventArgs

The ConnectedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the established connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection was established.
Public property | RemoteHostName | Gets the name of the remote host to which the connection was established.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


ConnectedEventArgs Methods

ConnectedEventArgs Methods

The ConnectedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ConnectedEventArgs Class
MailBee Namespace


ConnectedEventArgs Properties

ConnectedEventArgs Properties

The ConnectedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the established connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection was established.
Public property | RemoteHostName | Gets the name of the remote host to which the connection was established.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

ConnectedEventArgs Class
MailBee Namespace


ConnectedEventArgs.Protocol Property

ConnectedEventArgsProtocol Property
Gets application-level protocol of the established connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the established connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection will be used for.
See Also

Reference

ConnectedEventArgs Class
MailBee Namespace


ConnectedEventArgs.RemoteEndPoint Property

ConnectedEventArgsRemoteEndPoint Property
Gets a reference to the end point of the remote host to which the connection was established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the remote host.
See Also

Reference

ConnectedEventArgs Class
MailBee Namespace


ConnectedEventArgs.RemoteHostName Property

ConnectedEventArgsRemoteHostName Property
Gets the name of the remote host to which the connection was established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the name of the remote host.
See Also

Reference

ConnectedEventArgs Class
MailBee Namespace


ConnectedEventHandler Delegate

ConnectedEventHandler Delegate
Represents the method that will handle Connected events (such as Smtp.Connected, Pop3.Connected or Imap.Connected).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ConnectedEventHandler(
    Object sender,
    ConnectedEventArgs e
)
Public Delegate Sub ConnectedEventHandler (
    sender As Object,
    e As ConnectedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeConnectedEventArgs
See Also

Reference

MailBee Namespace


DataTransferEventArgs Class

DataTransferEventArgs Class
Contains the event data for data sending/receiving events (such as Smtp.DataSent, Smtp.DataReceived, Pop3.DataSent, Pop3.DataReceived, Imap.DataSent, Imap.DataReceived).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeDataTransferEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DataTransferEventArgs : CommonEventArgs
Public Class DataTransferEventArgs
    Inherits CommonEventArgs

The DataTransferEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Data | Gets a reference to the data block (chunk) sent or received.
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


DataTransferEventArgs Methods

DataTransferEventArgs Methods

The DataTransferEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DataTransferEventArgs Class
MailBee Namespace


DataTransferEventArgs Properties

DataTransferEventArgs Properties

The DataTransferEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a reference to the data block (chunk) sent or received.
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

DataTransferEventArgs Class
MailBee Namespace


DataTransferEventArgs.Data Property

DataTransferEventArgsData Property
Gets a reference to the data block (chunk) sent or received.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] Data { get; }
Public ReadOnly Property Data As Byte()
    Get

Property Value

Type: Byte
The data chunk which was sent or received.
See Also

Reference

DataTransferEventArgs Class
MailBee Namespace


DataTransferEventArgs.Protocol Property

DataTransferEventArgsProtocol Property
Gets application-level protocol of the current connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the current connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection is used for.
See Also

Reference

DataTransferEventArgs Class
MailBee Namespace


DataTransferEventArgs.RemoteEndPoint Property

DataTransferEventArgsRemoteEndPoint Property
Gets a reference to the end point of the server host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the server.
See Also

Reference

DataTransferEventArgs Class
MailBee Namespace


DataTransferEventArgs.RemoteHostName Property

DataTransferEventArgsRemoteHostName Property
Gets the host name of the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the host name of the server.
See Also

Reference

DataTransferEventArgs Class
MailBee Namespace


DataTransferEventHandler Delegate

DataTransferEventHandler Delegate
Represents the method that will handle events which occur on sending or receiving data to/from the server (such as Smtp.DataSent, Smtp.DataReceived, Pop3.DataSent, Pop3.DataReceived, Imap.DataSent, Imap.DataReceived).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void DataTransferEventHandler(
    Object sender,
    DataTransferEventArgs e
)
Public Delegate Sub DataTransferEventHandler (
    sender As Object,
    e As DataTransferEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeDataTransferEventArgs
See Also

Reference

MailBee Namespace


DisconnectedEventArgs Class

DisconnectedEventArgs Class
Contains the event data for Disconnected events (such as Smtp.Disconnected, Pop3.Disconnected or Imap.Disconnected).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeDisconnectedEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DisconnectedEventArgs : CommonEventArgs
Public Class DisconnectedEventArgs
    Inherits CommonEventArgs

The DisconnectedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | IsNormalShutdown | Indicates whether this event occurred as a result of calling Disconnect method so that the proper logout command was issued to the server, or the connection was terminated.
Public property | Protocol | Gets application-level protocol of the closed connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection was closed.
Public property | RemoteHostName | Gets the name of the remote host to which the connection was closed.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


DisconnectedEventArgs Methods

DisconnectedEventArgs Methods

The DisconnectedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DisconnectedEventArgs Class
MailBee Namespace


DisconnectedEventArgs Properties

DisconnectedEventArgs Properties

The DisconnectedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | IsNormalShutdown | Indicates whether this event occurred as a result of calling Disconnect method so that the proper logout command was issued to the server, or the connection was terminated.
Public property | Protocol | Gets application-level protocol of the closed connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection was closed.
Public property | RemoteHostName | Gets the name of the remote host to which the connection was closed.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

DisconnectedEventArgs Class
MailBee Namespace


DisconnectedEventArgs.IsNormalShutdown Property

DisconnectedEventArgsIsNormalShutdown Property
Indicates whether this event occurred as a result of calling Disconnect method so that the proper logout command was issued to the server, or the connection was terminated.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsNormalShutdown { get; }
Public ReadOnly Property IsNormalShutdown As Boolean
    Get

Property Value

Type: Boolean
true if logout command (such as QUIT for POP3 and SMTP protocols or LOGOUT for IMAP4) has been successfully issued prior to actual disconnecting from the server; otherwise, false.
Remarks
You can use this property value to learn whether the connection was closed properly or not. This is especially important in the case of Pop3.Disconnected event, since the POP3 server will not actually delete messages flagged for deletion during the POP3 session if the connection was terminated rather than properly closed.
See Also

Reference

DisconnectedEventArgs Class
MailBee Namespace


DisconnectedEventArgs.Protocol Property

DisconnectedEventArgsProtocol Property
Gets application-level protocol of the closed connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol which has been used with the connection until it was closed, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection was used for.
See Also

Reference

DisconnectedEventArgs Class
MailBee Namespace


DisconnectedEventArgs.RemoteEndPoint Property

DisconnectedEventArgsRemoteEndPoint Property
Gets a reference to the end point of the remote host to which the connection was closed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection which was just closed.
See Also

Reference

DisconnectedEventArgs Class
MailBee Namespace


DisconnectedEventArgs.RemoteHostName Property

DisconnectedEventArgsRemoteHostName Property
Gets the name of the remote host to which the connection was closed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the name of the remote host.
See Also

Reference

DisconnectedEventArgs Class
MailBee Namespace


DisconnectedEventHandler Delegate

DisconnectedEventHandler Delegate
Represents the method that will handle Disconnected events (such as Smtp.Disconnected, Pop3.Disconnected or Imap.Disconnected).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void DisconnectedEventHandler(
    Object sender,
    DisconnectedEventArgs e
)
Public Delegate Sub DisconnectedEventHandler (
    sender As Object,
    e As DisconnectedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeDisconnectedEventArgs
See Also

Reference

MailBee Namespace


ErrorEventArgs Class

ErrorEventArgs Class
Contains the event data for ErrorOccurred events (such as Smtp.ErrorOccurred, Pop3.ErrorOccurred or Imap.ErrorOccurred).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeErrorEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ErrorEventArgs : CommonEventArgs
Public Class ErrorEventArgs
    Inherits CommonEventArgs

The ErrorEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | IsFinalError | Indicates whether the exception caused the current event will be thrown by MailBee once the current event handler finished execution.
Public property | Reason | Gets the exception which caused the current event to be raised.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


ErrorEventArgs Methods

ErrorEventArgs Methods

The ErrorEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ErrorEventArgs Class
MailBee Namespace


ErrorEventArgs Properties

ErrorEventArgs Properties

The ErrorEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | IsFinalError | Indicates whether the exception caused the current event will be thrown by MailBee once the current event handler finished execution.
Public property | Reason | Gets the exception which caused the current event to be raised.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

ErrorEventArgs Class
MailBee Namespace


ErrorEventArgs.IsFinalError Property

ErrorEventArgsIsFinalError Property
Indicates whether the exception caused the current event will be thrown by MailBee once the current event handler finished execution.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsFinalError { get; }
Public ReadOnly Property IsFinalError As Boolean
    Get

Property Value

Type: Boolean
true if MailBee will throw the current exception once the event handler returns control to MailBee. false if MailBee will catch the exception and continue.
See Also

Reference

ErrorEventArgs Class
MailBee Namespace


ErrorEventArgs.Reason Property

ErrorEventArgsReason Property
Gets the exception which caused the current event to be raised.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailBeeException Reason { get; }
Public ReadOnly Property Reason As MailBeeException
    Get

Property Value

Type: MailBeeException
A reference to the exception.
See Also

Reference

ErrorEventArgs Class
MailBee Namespace


ErrorEventHandler Delegate

ErrorEventHandler Delegate
Represents the method that will handle ErrorOccurred events (such as Smtp.ErrorOccurred, Pop3.ErrorOccurred or Imap.ErrorOccurred).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ErrorEventHandler(
    Object sender,
    ErrorEventArgs e
)
Public Delegate Sub ErrorEventHandler (
    sender As Object,
    e As ErrorEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeErrorEventArgs
See Also

Reference

MailBee Namespace


HostResolvedEventArgs Class

HostResolvedEventArgs Class
Contains the event data for HostResolved events (such as Smtp.HostResolved, Pop3.HostResolved or Imap.HostResolved).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeHostResolvedEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class HostResolvedEventArgs : CommonEventArgs
Public Class HostResolvedEventArgs
    Inherits CommonEventArgs

The HostResolvedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | RemoteHost | Gets a reference to the resolved host data.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


HostResolvedEventArgs Methods

HostResolvedEventArgs Methods

The HostResolvedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

HostResolvedEventArgs Class
MailBee Namespace


HostResolvedEventArgs Properties

HostResolvedEventArgs Properties

The HostResolvedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | RemoteHost | Gets a reference to the resolved host data.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

HostResolvedEventArgs Class
MailBee Namespace


HostResolvedEventArgs.RemoteHost Property

HostResolvedEventArgsRemoteHost Property
Gets a reference to the resolved host data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPHostEntry RemoteHost { get; }
Public ReadOnly Property RemoteHost As IPHostEntry
    Get

Property Value

Type: IPHostEntry
The resolved host data.
See Also

Reference

HostResolvedEventArgs Class
MailBee Namespace


HostResolvedEventHandler Delegate

HostResolvedEventHandler Delegate
Represents the method that will handle HostResolved events (such as Smtp.HostResolved, Pop3.HostResolved or Imap.HostResolved).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void HostResolvedEventHandler(
    Object sender,
    HostResolvedEventArgs e
)
Public Delegate Sub HostResolvedEventHandler (
    sender As Object,
    e As HostResolvedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeHostResolvedEventArgs
See Also

Reference

MailBee Namespace


LoggedInEventArgs Class

LoggedInEventArgs Class
Contains the event data for LoggedIn events (such as Smtp.LoggedIn, Pop3.LoggedIn or Imap.LoggedIn).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeLoggedInEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class LoggedInEventArgs : CommonEventArgs
Public Class LoggedInEventArgs
    Inherits CommonEventArgs

The LoggedInEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


LoggedInEventArgs Methods

LoggedInEventArgs Methods

The LoggedInEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

LoggedInEventArgs Class
MailBee Namespace


LoggedInEventArgs Properties

LoggedInEventArgs Properties

The LoggedInEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

LoggedInEventArgs Class
MailBee Namespace


LoggedInEventArgs.Protocol Property

LoggedInEventArgsProtocol Property
Gets application-level protocol of the current connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the current connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection is used for.
See Also

Reference

LoggedInEventArgs Class
MailBee Namespace


LoggedInEventArgs.RemoteEndPoint Property

LoggedInEventArgsRemoteEndPoint Property
Gets a reference to the end point of the server host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the server.
See Also

Reference

LoggedInEventArgs Class
MailBee Namespace


LoggedInEventArgs.RemoteHostName Property

LoggedInEventArgsRemoteHostName Property
Gets the host name of the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the host name of the server.
See Also

Reference

LoggedInEventArgs Class
MailBee Namespace


LoggedInEventHandler Delegate

LoggedInEventHandler Delegate
Represents the method that will handle LoggedIn events (such as Smtp.LoggedIn, Pop3.LoggedIn or Imap.LoggedIn).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void LoggedInEventHandler(
    Object sender,
    LoggedInEventArgs e
)
Public Delegate Sub LoggedInEventHandler (
    sender As Object,
    e As LoggedInEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeLoggedInEventArgs
See Also

Reference

MailBee Namespace


LogNewEntryEventArgs Class

LogNewEntryEventArgs Class
Contains the event data for LogNewEntry events (such as Smtp.LogNewEntry, Pop3.LogNewEntry or Imap.LogNewEntry).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeLogNewEntryEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class LogNewEntryEventArgs : CommonEventArgs
Public Class LogNewEntryEventArgs
    Inherits CommonEventArgs

The LogNewEntryEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | NewEntry | Gets a reference to the log entry MailBee is going to put into the log file (or into the memory buffer if MemoryLog is true).
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
Remarks
The developer can cancel adding the log entry to the log file by setting AddThisEntry to false.
See Also

Reference

MailBee Namespace


LogNewEntryEventArgs Methods

LogNewEntryEventArgs Methods

The LogNewEntryEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

LogNewEntryEventArgs Class
MailBee Namespace


LogNewEntryEventArgs Properties

LogNewEntryEventArgs Properties

The LogNewEntryEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | NewEntry | Gets a reference to the log entry MailBee is going to put into the log file (or into the memory buffer if MemoryLog is true).
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

LogNewEntryEventArgs Class
MailBee Namespace


LogNewEntryEventArgs.NewEntry Property

LogNewEntryEventArgsNewEntry Property
Gets a reference to the log entry MailBee is going to put into the log file (or into the memory buffer if MemoryLog is true).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public LogEntry NewEntry { get; }
Public ReadOnly Property NewEntry As LogEntry
    Get

Property Value

Type: LogEntry
Returns a reference to the log entry.
See Also

Reference

LogNewEntryEventArgs Class
MailBee Namespace


LogNewEntryEventHandler Delegate

LogNewEntryEventHandler Delegate
Represents the method that will handle LogNewEntry events (such as Smtp.LogNewEntry, Pop3.LogNewEntry or Imap.LogNewEntry).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void LogNewEntryEventHandler(
    Object sender,
    LogNewEntryEventArgs e
)
Public Delegate Sub LogNewEntryEventHandler (
    sender As Object,
    e As LogNewEntryEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeLogNewEntryEventArgs
See Also

Reference

MailBee Namespace


SocketConnectedEventArgs Class

SocketConnectedEventArgs Class
Contains the event data for SocketConnected events (such as Smtp.SocketConnected, Pop3.SocketConnected or Imap.SocketConnected).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeSocketConnectedEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SocketConnectedEventArgs : CommonEventArgs
Public Class SocketConnectedEventArgs
    Inherits CommonEventArgs

The SocketConnectedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the established connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection was just established.
Public property | RemoteHostName | Gets the name of the remote host to which the connection was just established.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


SocketConnectedEventArgs Methods

SocketConnectedEventArgs Methods

The SocketConnectedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SocketConnectedEventArgs Class
MailBee Namespace


SocketConnectedEventArgs Properties

SocketConnectedEventArgs Properties

The SocketConnectedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the established connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection was just established.
Public property | RemoteHostName | Gets the name of the remote host to which the connection was just established.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

SocketConnectedEventArgs Class
MailBee Namespace


SocketConnectedEventArgs.Protocol Property

SocketConnectedEventArgsProtocol Property
Gets application-level protocol of the established connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the established connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection will be used for.
See Also

Reference

SocketConnectedEventArgs Class
MailBee Namespace


SocketConnectedEventArgs.RemoteEndPoint Property

SocketConnectedEventArgsRemoteEndPoint Property
Gets a reference to the end point of the remote host to which the connection was just established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the remote host.
See Also

Reference

SocketConnectedEventArgs Class
MailBee Namespace


SocketConnectedEventArgs.RemoteHostName Property

SocketConnectedEventArgsRemoteHostName Property
Gets the name of the remote host to which the connection was just established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the name of the remote host.
See Also

Reference

SocketConnectedEventArgs Class
MailBee Namespace


SocketConnectedEventHandler Delegate

SocketConnectedEventHandler Delegate
Represents the method that will handle SocketConnected events (such as Smtp.SocketConnected, Pop3.SocketConnected or Imap.SocketConnected).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SocketConnectedEventHandler(
    Object sender,
    SocketConnectedEventArgs e
)
Public Delegate Sub SocketConnectedEventHandler (
    sender As Object,
    e As SocketConnectedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeSocketConnectedEventArgs
See Also

Reference

MailBee Namespace


SocketCreatingEventArgs Class

SocketCreatingEventArgs Class
Contains the event data for SocketCreating events (such as Smtp.SocketCreating, Pop3.SocketCreating or Imap.SocketCreating).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeSocketCreatingEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SocketCreatingEventArgs : CommonEventArgs
Public Class SocketCreatingEventArgs
    Inherits CommonEventArgs

The SocketCreatingEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | NewSocket | Gets or sets the socket object which will be used to establish the connection.
Public property | Protocol | Gets application-level protocol of the to-be-established connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection will be established.
Public property | RemoteHostName | Gets the name of the remote host to which the connection will be established.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


SocketCreatingEventArgs Methods

SocketCreatingEventArgs Methods

The SocketCreatingEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SocketCreatingEventArgs Class
MailBee Namespace


SocketCreatingEventArgs Properties

SocketCreatingEventArgs Properties

The SocketCreatingEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | NewSocket | Gets or sets the socket object which will be used to establish the connection.
Public property | Protocol | Gets application-level protocol of the to-be-established connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the remote host to which the connection will be established.
Public property | RemoteHostName | Gets the name of the remote host to which the connection will be established.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

SocketCreatingEventArgs Class
MailBee Namespace


SocketCreatingEventArgs.NewSocket Property

SocketCreatingEventArgsNewSocket Property
Gets or sets the socket object which will be used to establish the connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Socket NewSocket { get; set; }
Public Property NewSocket As Socket
    Get
    Set

Property Value

Type: Socket
The Socket object to be used for making the connection, or a null reference (Nothing in Visual Basic) to let MailBee create the socket. The default value is null reference.
Remarks
You can set this property to provide your own (such as specially configured) socket object.
Note Note
You must be prepared to the situation when multiple sockets are requested for the same connection (for instance, the previous attempt failed because IPv6 endpoint was provided or more than one SMTP server was provided and several were tried, etc). You need to provide fresh socket object each time because sockets cannot be reused no matter if the connection attempt failed or not.
In case of UWP edition, this property has StreamSocket type.
See Also

Reference

SocketCreatingEventArgs Class
MailBee Namespace


SocketCreatingEventArgs.Protocol Property

SocketCreatingEventArgsProtocol Property
Gets application-level protocol of the to-be-established connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the to-be-established connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection will be used for.
See Also

Reference

SocketCreatingEventArgs Class
MailBee Namespace


SocketCreatingEventArgs.RemoteEndPoint Property

SocketCreatingEventArgsRemoteEndPoint Property
Gets a reference to the end point of the remote host to which the connection will be established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the remote host.
See Also

Reference

SocketCreatingEventArgs Class
MailBee Namespace


SocketCreatingEventArgs.RemoteHostName Property

SocketCreatingEventArgsRemoteHostName Property
Gets the name of the remote host to which the connection will be established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the name of the remote host.
See Also

Reference

SocketCreatingEventArgs Class
MailBee Namespace


SocketCreatingEventHandler Delegate

SocketCreatingEventHandler Delegate
Represents the method that will handle SocketCreating events (such as Smtp.SocketCreating, Pop3.SocketCreating or Imap.SocketCreating).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SocketCreatingEventHandler(
    Object sender,
    SocketCreatingEventArgs e
)
Public Delegate Sub SocketCreatingEventHandler (
    sender As Object,
    e As SocketCreatingEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeSocketCreatingEventArgs
See Also

Reference

MailBee Namespace


TlsStartedEventArgs Class

TlsStartedEventArgs Class
Contains the event data for TlsStarted events (such as Smtp.TlsStarted, Pop3.TlsStarted or Imap.TlsStarted).
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBeeTlsStartedEventArgs

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TlsStartedEventArgs : CommonEventArgs
Public Class TlsStartedEventArgs
    Inherits CommonEventArgs

The TlsStartedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee Namespace


TlsStartedEventArgs Methods

TlsStartedEventArgs Methods

The TlsStartedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TlsStartedEventArgs Class
MailBee Namespace


TlsStartedEventArgs Properties

TlsStartedEventArgs Properties

The TlsStartedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

TlsStartedEventArgs Class
MailBee Namespace


TlsStartedEventArgs.Protocol Property

TlsStartedEventArgsProtocol Property
Gets application-level protocol of the current connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the current connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection is used for.
See Also

Reference

TlsStartedEventArgs Class
MailBee Namespace


TlsStartedEventArgs.RemoteEndPoint Property

TlsStartedEventArgsRemoteEndPoint Property
Gets a reference to the end point of the server host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the server.
See Also

Reference

TlsStartedEventArgs Class
MailBee Namespace


TlsStartedEventArgs.RemoteHostName Property

TlsStartedEventArgsRemoteHostName Property
Gets the host name of the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the host name of the server.
See Also

Reference

TlsStartedEventArgs Class
MailBee Namespace


TlsStartedEventHandler Delegate

TlsStartedEventHandler Delegate
Represents the method that will handle TlsStarted events (such as Smtp.TlsStarted, Pop3.TlsStarted or Imap.TlsStarted).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void TlsStartedEventHandler(
    Object sender,
    TlsStartedEventArgs e
)
Public Delegate Sub TlsStartedEventHandler (
    sender As Object,
    e As TlsStartedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBeeTlsStartedEventArgs
See Also

Reference

MailBee Namespace


Exception Classes

For ease of browsing the documentation, event and exception classes are brought together in the groups which are separate from other classes.

Send feedback to AfterLogic


IMailBeeFatalException Interface

IMailBeeFatalException Interface
When implemented by an exception class, indicates the exception is fatal and the component is no longer usable in the current state, so that any active tasks must be finished as soon as possible.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeFatalException
Public Interface IMailBeeFatalException

Field Value

Type:
Typical examples of fatal errors are: the operation is aborted by the user, no valid license is assigned to the component, etc.
See Also

Reference

MailBee Namespace


IMailBeeLoginBadCredentialsException Interface

IMailBeeLoginBadCredentialsException Interface
When implemented by an exception class, indicates the authentication failed due to use of incorrect account name and/or password.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeLoginBadCredentialsException : IMailBeeLoginNegativeResponseException,
    IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public Interface IMailBeeLoginBadCredentialsException
    Inherits IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The IMailBeeLoginBadCredentialsException type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used for the authentication.
Public property | Password | Gets the account password which was used for the authentication.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

MailBee Namespace


IMailBeeLoginBadCredentialsException Properties

IMailBeeLoginBadCredentialsException Properties

The IMailBeeLoginBadCredentialsException type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used for the authentication.
Public property | Password | Gets the account password which was used for the authentication.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

IMailBeeLoginBadCredentialsException Interface
MailBee Namespace


IMailBeeLoginBadCredentialsException.AccountName Property

IMailBeeLoginBadCredentialsExceptionAccountName Property
Gets the account name which was used for the authentication.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
string AccountName { get; }
ReadOnly Property AccountName As String
    Get

Property Value

Type: String
The account name the authentication failed with.
See Also

Reference

IMailBeeLoginBadCredentialsException Interface
MailBee Namespace


IMailBeeLoginBadCredentialsException.Password Property

IMailBeeLoginBadCredentialsExceptionPassword Property
Gets the account password which was used for the authentication.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
string Password { get; }
ReadOnly Property Password As String
    Get

Property Value

Type: String
The account password the authentication failed with.
See Also

Reference

IMailBeeLoginBadCredentialsException Interface
MailBee Namespace


IMailBeeLoginBadMethodException Interface

IMailBeeLoginBadMethodException Interface
When implemented by an exception class, indicates the server returned negative response during the authentication process because the requested authentication method is not available.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeLoginBadMethodException : IMailBeeLoginNegativeResponseException,
    IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public Interface IMailBeeLoginBadMethodException
    Inherits IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The IMailBeeLoginBadMethodException type exposes the following members.

Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
Remarks
Such exception may also occur if FipsMode is enabled and the given authentication method is not FIPS-compliant.
See Also

Reference

MailBee Namespace


IMailBeeLoginBadMethodException Properties

IMailBeeLoginBadMethodException Properties

The IMailBeeLoginBadMethodException type exposes the following members.

Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

IMailBeeLoginBadMethodException Interface
MailBee Namespace


IMailBeeLoginBadMethodException.BadMethod Property

IMailBeeLoginBadMethodExceptionBadMethod Property
Gets the authentication method which was rejected by the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
AuthenticationMethods BadMethod { get; }
ReadOnly Property BadMethod As AuthenticationMethods
    Get

Property Value

Type: AuthenticationMethods
An AuthenticationMethods value which corresponds to the authentication method which was rejected by the server because this method is either not supported or disabled.
See Also

Reference

IMailBeeLoginBadMethodException Interface
MailBee Namespace


IMailBeeLoginException Interface

IMailBeeLoginException Interface
When implemented by an exception class, indicates the login process failed, and the application should try to authenticate using either another account name and password or another authentication method.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeLoginException
Public Interface IMailBeeLoginException
See Also

Reference

MailBee Namespace


IMailBeeLoginNegativeResponseException Interface

IMailBeeLoginNegativeResponseException Interface
When implemented by an exception class, indicates the server returned negative response during the authentication process, and the response data is available in text (i.e. string) form.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeLoginNegativeResponseException : IMailBeeLoginException,
    IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public Interface IMailBeeLoginNegativeResponseException
    Inherits IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The IMailBeeLoginNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

MailBee Namespace


IMailBeeLoginNegativeResponseException Properties

IMailBeeLoginNegativeResponseException Properties

The IMailBeeLoginNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

IMailBeeLoginNegativeResponseException Interface
MailBee Namespace


IMailBeeNegativeResponseException Interface

IMailBeeNegativeResponseException Interface
When implemented by an exception class, indicates the server returned negative response, and the response data is available.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeNegativeResponseException
Public Interface IMailBeeNegativeResponseException
See Also

Reference

MailBee Namespace


IMailBeeNegativeTextResponseException Interface

IMailBeeNegativeTextResponseException Interface
When implemented by an exception class, indicates the server returned negative response, and the response data is available in text (i.e. string) form.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeNegativeTextResponseException : IMailBeeNegativeResponseException
Public Interface IMailBeeNegativeTextResponseException
    Inherits IMailBeeNegativeResponseException

The IMailBeeNegativeTextResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string.
Public property | ResponseString | Gets the string which contains the negative response data.
Top
See Also

Reference

MailBee Namespace


IMailBeeNegativeTextResponseException Properties

IMailBeeNegativeTextResponseException Properties

The IMailBeeNegativeTextResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string.
Public property | ResponseString | Gets the string which contains the negative response data.
Top
See Also

Reference

IMailBeeNegativeTextResponseException Interface
MailBee Namespace


IMailBeeNegativeTextResponseException.ResponseEncoding Property

IMailBeeNegativeTextResponseExceptionResponseEncoding Property
Gets the encoding which was used to convert response bytes received from the server into a string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
Encoding ResponseEncoding { get; }
ReadOnly Property ResponseEncoding As Encoding
    Get

Property Value

Type: Encoding
The Encoding which was used to convert response bytes received from the server into a string.
Remarks
This encoding is taken from ResponseEncoding property value (such as Pop3.ResponseEncoding, Imap.ResponseEncoding or Smtp.ResponseEncoding).
See Also

Reference

IMailBeeNegativeTextResponseException Interface
MailBee Namespace


IMailBeeNegativeTextResponseException.ResponseString Property

IMailBeeNegativeTextResponseExceptionResponseString Property
Gets the string which contains the negative response data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
string ResponseString { get; }
ReadOnly Property ResponseString As String
    Get

Property Value

Type: String
The string which contains the negative response data.
See Also

Reference

IMailBeeNegativeTextResponseException Interface
MailBee Namespace


IMailBeeSocketMustCloseException Interface

IMailBeeSocketMustCloseException Interface
When implemented by an exception class, indicates the network exception is connection level (not application protocol level), so that the connection is no longer valid and will be closed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeSocketMustCloseException
Public Interface IMailBeeSocketMustCloseException
Remarks
Connection level network exceptions (timeout errors, unparseable server responses, socket exceptions, etc) make it impossible to continue using an existing connection. In contrast, application level network exceptions (such as negative responses from the server) do not require immediate disconnect. For instance, if login failed due to incorrect user account name and/or password, the connection may still be valid, and another login/password may be tried without reconnecting to the server.
See Also

Reference

MailBee Namespace


IMailBeeWin32Exception Interface

IMailBeeWin32Exception Interface
When implemented by an exception class, indicates that this exception is thrown when underlying Win32 function returns an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeWin32Exception
Public Interface IMailBeeWin32Exception

The IMailBeeWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | NativeErrorCode | The Win32 error code value returned by a function of Windows API.
Top
Remarks

Exceptions which implement IMailBeeWin32Exception can only be thrown by those methods of MailBee.NET assembly which make calls to unmanaged code. Although the assembly itself does not contain any unmanaged code, it still needs to call some Win32 functions related to security: TLS/SSL functionality, certificates, and Integrated Windows version of NTLM authentication.

The developer can obtain Win32 error code from NativeErrorCode property.
See Also

Reference

MailBee Namespace


IMailBeeWin32Exception Properties

IMailBeeWin32Exception Properties

The IMailBeeWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | NativeErrorCode | The Win32 error code value returned by a function of Windows API.
Top
See Also

Reference

IMailBeeWin32Exception Interface
MailBee Namespace


IMailBeeWin32Exception.NativeErrorCode Property

IMailBeeWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by a function of Windows API.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
int NativeErrorCode { get; }
ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by a function of Windows API.
See Also

Reference

IMailBeeWin32Exception Interface
MailBee Namespace


MailBeeAbortedByRemoteHostException Class

MailBeeAbortedByRemoteHostException Class
The exception that is thrown when the remote host suddenly closes the connection.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeAbortedByRemoteHostException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeAbortedByRemoteHostException : MailBeeConnectionException
<SerializableAttribute>
Public Class MailBeeAbortedByRemoteHostException
    Inherits MailBeeConnectionException

The MailBeeAbortedByRemoteHostException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeAbortedByRemoteHostException | Initializes a new instance of the MailBeeAbortedByRemoteHostException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeAbortedByRemoteHostException Constructor

MailBeeAbortedByRemoteHostException Constructor
Initializes a new instance of the MailBeeAbortedByRemoteHostException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeAbortedByRemoteHostException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeAbortedByRemoteHostException Class
MailBee Namespace


MailBeeAbortedByRemoteHostException Methods

MailBeeAbortedByRemoteHostException Methods

The MailBeeAbortedByRemoteHostException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeAbortedByRemoteHostException Class
MailBee Namespace


MailBeeAbortedByRemoteHostException Properties

MailBeeAbortedByRemoteHostException Properties

The MailBeeAbortedByRemoteHostException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeAbortedByRemoteHostException Class
MailBee Namespace


MailBeeAbortedByRemoteHostException Events

MailBeeAbortedByRemoteHostException Events

The MailBeeAbortedByRemoteHostException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeAbortedByRemoteHostException Class
MailBee Namespace


MailBeeBatchException Class

MailBeeBatchException Class
The exception that is thrown when certain job in a batch of scheduled jobs fails and the component is configured to cancel processing in this case.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeBatchException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeBatchException : MailBeeException
<SerializableAttribute>
Public Class MailBeeBatchException
    Inherits MailBeeException

The MailBeeBatchException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeBatchException | Initializes a new instance of the MailBeeBatchException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This exception typically occurs when Smtp component performs sending out multiple messages (bulk mail merge) and sending of certain mail message fails. This exception won't occur, however, if the component is allowed to skip failed messages and proceed (StopJobsOnError is false).
See Also

Reference

MailBee Namespace


MailBeeBatchException Constructor

MailBeeBatchException Constructor
Initializes a new instance of the MailBeeBatchException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeBatchException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeBatchException Class
MailBee Namespace


MailBeeBatchException Methods

MailBeeBatchException Methods

The MailBeeBatchException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeBatchException Class
MailBee Namespace


MailBeeBatchException Properties

MailBeeBatchException Properties

The MailBeeBatchException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeBatchException Class
MailBee Namespace


MailBeeBatchException Events

MailBeeBatchException Events

The MailBeeBatchException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeBatchException Class
MailBee Namespace


MailBeeConnectionException Class

MailBeeConnectionException Class
An abstract parent for all connection-level exceptions which indicate the connection cannot be used any longer and must be immediately closed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
More...

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeConnectionException : MailBeeRemoteHostException,
    IMailBeeSocketMustCloseException
Public MustInherit Class MailBeeConnectionException
    Inherits MailBeeRemoteHostException
    Implements IMailBeeSocketMustCloseException

The MailBeeConnectionException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeConnectionException | Initializes a new instance of the MailBeeConnectionException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace
MailBeeIMailBeeSocketMustCloseException
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeAbortedByRemoteHostException
MailBeeMailBeeInvalidResponseException
MailBeeMailBeeRemoteHostResponseTimeoutException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketObjectDisposedException
MailBee.ProxyMailBeeProxyException


MailBeeConnectionException Constructor

MailBeeConnectionException Constructor
Initializes a new instance of the MailBeeConnectionException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeConnectionException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeConnectionException Class
MailBee Namespace


MailBeeConnectionException Methods

MailBeeConnectionException Methods

The MailBeeConnectionException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeConnectionException Class
MailBee Namespace


MailBeeConnectionException Properties

MailBeeConnectionException Properties

The MailBeeConnectionException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeConnectionException Class
MailBee Namespace


MailBeeConnectionException Events

MailBeeConnectionException Events

The MailBeeConnectionException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeConnectionException Class
MailBee Namespace


MailBeeDataParsingException Class

MailBeeDataParsingException Class
The exception that is thrown when an unexpected error occurs during converting a string or byte block into the required format (such as integer).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeDataParsingException
MailBeeMailBeeDateParsingException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDataParsingException : MailBeeLocalException
<SerializableAttribute>
Public Class MailBeeDataParsingException
    Inherits MailBeeLocalException

The MailBeeDataParsingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDataParsingException | Initializes a new instance of the MailBeeDataParsingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
For instance, this exception may occur during reading Bayesian database. Another case is when the application tries to load an Outlook .MSG file like if it was .EML MIME file (not using MsgConvert class).
See Also

Reference

MailBee Namespace


MailBeeDataParsingException Constructor

MailBeeDataParsingException Constructor
Initializes a new instance of the MailBeeDataParsingException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDataParsingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDataParsingException Class
MailBee Namespace


MailBeeDataParsingException Methods

MailBeeDataParsingException Methods

The MailBeeDataParsingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDataParsingException Class
MailBee Namespace


MailBeeDataParsingException Properties

MailBeeDataParsingException Properties

The MailBeeDataParsingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDataParsingException Class
MailBee Namespace


MailBeeDataParsingException Events

MailBeeDataParsingException Events

The MailBeeDataParsingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDataParsingException Class
MailBee Namespace


MailBeeDataSyntaxException Class

MailBeeDataSyntaxException Class
This exception indicates that MailBee determined that the data passed had wrong syntax.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeDataSyntaxException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDataSyntaxException : MailBeeLocalException
<SerializableAttribute>
Public Class MailBeeDataSyntaxException
    Inherits MailBeeLocalException

The MailBeeDataSyntaxException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDataSyntaxException | Initializes a new instance of the MailBeeDataSyntaxException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This exception is not thrown directly. It may be the value of Reason property which indicates the reason why the e-mail address failed the check. In particular, if this property holds the value of MailBeeDataSyntaxException type, it means the e-mail address syntax was incorrect.
See Also

Reference

MailBee Namespace


MailBeeDataSyntaxException Constructor

MailBeeDataSyntaxException Constructor
Initializes a new instance of the MailBeeDataSyntaxException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDataSyntaxException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDataSyntaxException Class
MailBee Namespace


MailBeeDataSyntaxException Methods

MailBeeDataSyntaxException Methods

The MailBeeDataSyntaxException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDataSyntaxException Class
MailBee Namespace


MailBeeDataSyntaxException Properties

MailBeeDataSyntaxException Properties

The MailBeeDataSyntaxException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDataSyntaxException Class
MailBee Namespace


MailBeeDataSyntaxException Events

MailBeeDataSyntaxException Events

The MailBeeDataSyntaxException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDataSyntaxException Class
MailBee Namespace


MailBeeDateParsingException Class

MailBeeDateParsingException Class
The exception that is thrown when an unexpected error occurs during converting a string into DateTime.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeDataParsingException
MailBeeMailBeeDateParsingException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDateParsingException : MailBeeDataParsingException
<SerializableAttribute>
Public Class MailBeeDateParsingException
    Inherits MailBeeDataParsingException

The MailBeeDateParsingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDateParsingException | Initializes a new instance of the MailBeeDateParsingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
For instance, this exception may occur during reading Date property value.
See Also

Reference

MailBee Namespace


MailBeeDateParsingException Constructor

MailBeeDateParsingException Constructor
Initializes a new instance of the MailBeeDateParsingException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDateParsingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDateParsingException Class
MailBee Namespace


MailBeeDateParsingException Methods

MailBeeDateParsingException Methods

The MailBeeDateParsingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDateParsingException Class
MailBee Namespace


MailBeeDateParsingException Properties

MailBeeDateParsingException Properties

The MailBeeDateParsingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDateParsingException Class
MailBee Namespace


MailBeeDateParsingException Events

MailBeeDateParsingException Events

The MailBeeDateParsingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDateParsingException Class
MailBee Namespace


MailBeeEmailProtocolException Class

MailBeeEmailProtocolException Class
An abstract parent for all exceptions which indicate that an e-mail protocol (such as POP3, IMAP4 or SMTP) error has occurred.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
More...

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeEmailProtocolException : MailBeeProtocolException
Public MustInherit Class MailBeeEmailProtocolException
    Inherits MailBeeProtocolException

The MailBeeEmailProtocolException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeEmailProtocolException | Initializes a new instance of the MailBeeEmailProtocolException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Typical example of the application-level protocol error is a negative server response.
See Also

Reference

MailBee Namespace
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.EwsMailMailBeeEwsException
MailBee.ImapMailMailBeeImapInvalidEnvelopeException
MailBee.ImapMailMailBeeImapMessageIndexNotFoundException
MailBee.ImapMailMailBeeImapResponseNotFoundException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBeeMailBeeLoginNotPossibleException
MailBeeMailBeeProtocolExtensionNotSupportedException
MailBee.SmtpMailMailBeeSmtp8bitDataNotSupportedException
MailBee.SmtpMailMailBeeSmtpMessageNotAllowedException
MailBee.SmtpMailMailBeeSmtpNoAcceptedRecipientsException


MailBeeEmailProtocolException Constructor

MailBeeEmailProtocolException Constructor
Initializes a new instance of the MailBeeEmailProtocolException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeEmailProtocolException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeEmailProtocolException Class
MailBee Namespace


MailBeeEmailProtocolException Methods

MailBeeEmailProtocolException Methods

The MailBeeEmailProtocolException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeEmailProtocolException Class
MailBee Namespace


MailBeeEmailProtocolException Properties

MailBeeEmailProtocolException Properties

The MailBeeEmailProtocolException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeEmailProtocolException Class
MailBee Namespace


MailBeeEmailProtocolException Events

MailBeeEmailProtocolException Events

The MailBeeEmailProtocolException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeEmailProtocolException Class
MailBee Namespace


MailBeeEmailProtocolNegativeResponseException Class

MailBeeEmailProtocolNegativeResponseException Class
An abstract parent for all exceptions which indicate that the mail server returned negative response, and the response data is available in text (i.e. string) form.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.ImapMailMailBeeImapNegativeResponseException
MailBee.Pop3MailMailBeePop3NegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeEmailProtocolNegativeResponseException : MailBeeEmailProtocolException,
    IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public MustInherit Class MailBeeEmailProtocolNegativeResponseException
    Inherits MailBeeEmailProtocolException
    Implements IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The MailBeeEmailProtocolNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeEmailProtocolNegativeResponseException | Initializes a new instance of the MailBeeEmailProtocolNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string.
Public property | ResponseString | Gets the string which contains the negative response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeEmailProtocolNegativeResponseException Constructor

MailBeeEmailProtocolNegativeResponseException Constructor
Initializes a new instance of the MailBeeEmailProtocolNegativeResponseException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeEmailProtocolNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeEmailProtocolNegativeResponseException Class
MailBee Namespace


MailBeeEmailProtocolNegativeResponseException Methods

MailBeeEmailProtocolNegativeResponseException Methods

The MailBeeEmailProtocolNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeEmailProtocolNegativeResponseException Class
MailBee Namespace


MailBeeEmailProtocolNegativeResponseException Properties

MailBeeEmailProtocolNegativeResponseException Properties

The MailBeeEmailProtocolNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string.
Public property | ResponseString | Gets the string which contains the negative response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeEmailProtocolNegativeResponseException Class
MailBee Namespace


MailBeeEmailProtocolNegativeResponseException.ResponseEncoding Property

MailBeeEmailProtocolNegativeResponseExceptionResponseEncoding Property
Gets the encoding which was used to convert response bytes received from the server into a string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ResponseEncoding { get; }
Public ReadOnly Property ResponseEncoding As Encoding
    Get

Property Value

Type: Encoding
The Encoding which was used to convert response bytes received from the server into a string.

Implements

IMailBeeNegativeTextResponseExceptionResponseEncoding
Remarks
This encoding is taken from ResponseEncoding property value (such as Pop3.ResponseEncoding, Imap.ResponseEncoding or Smtp.ResponseEncoding).
See Also

Reference

MailBeeEmailProtocolNegativeResponseException Class
MailBee Namespace


MailBeeEmailProtocolNegativeResponseException.ResponseString Property

MailBeeEmailProtocolNegativeResponseExceptionResponseString Property
Gets the string which contains the negative response data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ResponseString { get; }
Public ReadOnly Property ResponseString As String
    Get

Property Value

Type: String
The string which contains the negative response data.

Implements

IMailBeeNegativeTextResponseExceptionResponseString
See Also

Reference

MailBeeEmailProtocolNegativeResponseException Class
MailBee Namespace


MailBeeEmailProtocolNegativeResponseException Events

MailBeeEmailProtocolNegativeResponseException Events

The MailBeeEmailProtocolNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeEmailProtocolNegativeResponseException Class
MailBee Namespace


MailBeeException Class

MailBeeException Class
An abstract parent for all exceptions which can be thrown by MailBee library.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
More...

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeException : ApplicationException
Public MustInherit Class MailBeeException
    Inherits ApplicationException

The MailBeeException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeException | Initializes a new instance of the MailBeeException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code.
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
In .NET Core and UWP, this class is derived directly from Exception as there is no ApplicationException in .NET Standard 1.6.
See Also

Reference

MailBee Namespace
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeBatchException
MailBeeMailBeeInvalidArgumentException
MailBeeMailBeeInvalidStateException
MailBeeMailBeeLocalException
MailBeeMailBeeNetworkException
MailBeeMailBeeStreamException
MailBeeMailBeeWebException
MailBee.SecurityMailBeeSslException


MailBeeException Constructor

MailBeeException Constructor
Initializes a new instance of the MailBeeException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeException Class
MailBee Namespace


MailBeeException Methods

MailBeeException Methods

The MailBeeException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeException Class
MailBee Namespace


MailBeeException Properties

MailBeeException Properties

The MailBeeException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code.
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeException Class
MailBee Namespace


MailBeeException.ErrorCode Property

MailBeeExceptionErrorCode Property
Gets the error code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int ErrorCode { get; }
Public ReadOnly Property ErrorCode As Integer
    Get

Property Value

Type: Int32
Remarks
The error code returned by this property is the one of field values defined in ErrorCodes class.
See Also

Reference

MailBeeException Class
MailBee Namespace


MailBeeException Events

MailBeeException Events

The MailBeeException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeException Class
MailBee Namespace


MailBeeExternalException Class

MailBeeExternalException Class
The exception that is thrown when an error occurs in the code outside MailBee.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeExternalException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeExternalException : MailBeeLocalException,
    IMailBeeFatalException
<SerializableAttribute>
Public Class MailBeeExternalException
    Inherits MailBeeLocalException
    Implements IMailBeeFatalException

The MailBeeExternalException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeExternalException | Initializes a new instance of the MailBeeExternalException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Usually, this exception is thrown in the following scenario. Let's say the application is subscribed to a certain MailBee event. Now MailBee raises this event and starts executing the event handler supplied by the developer. If the event handler code (external code to MailBee) throws an exception, MailBee's event raiser catches this exception and throws MailBeeExternalException specifying the original exception in InnerException property value.
See Also

Reference

MailBee Namespace


MailBeeExternalException Constructor

MailBeeExternalException Constructor
Initializes a new instance of the MailBeeExternalException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeExternalException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeExternalException Class
MailBee Namespace


MailBeeExternalException Methods

MailBeeExternalException Methods

The MailBeeExternalException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeExternalException Class
MailBee Namespace


MailBeeExternalException Properties

MailBeeExternalException Properties

The MailBeeExternalException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeExternalException Class
MailBee Namespace


MailBeeExternalException Events

MailBeeExternalException Events

The MailBeeExternalException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeExternalException Class
MailBee Namespace


MailBeeGetHostNameException Class

MailBeeGetHostNameException Class
An abstract parent for all exceptions that are thrown if an attempt to resolve a host name through the call of a method of Dns class failed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeGetHostNameException
MailBeeMailBeeGetLocalHostNameException
MailBeeMailBeeGetRemoteHostNameException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeGetHostNameException : MailBeeNetworkException
Public MustInherit Class MailBeeGetHostNameException
    Inherits MailBeeNetworkException

The MailBeeGetHostNameException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeGetHostNameException | Initializes a new instance of the MailBeeGetHostNameException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeGetHostNameException Constructor

MailBeeGetHostNameException Constructor
Initializes a new instance of the MailBeeGetHostNameException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeGetHostNameException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeGetHostNameException Class
MailBee Namespace


MailBeeGetHostNameException Methods

MailBeeGetHostNameException Methods

The MailBeeGetHostNameException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetHostNameException Class
MailBee Namespace


MailBeeGetHostNameException Properties

MailBeeGetHostNameException Properties

The MailBeeGetHostNameException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetHostNameException Class
MailBee Namespace


MailBeeGetHostNameException Events

MailBeeGetHostNameException Events

The MailBeeGetHostNameException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetHostNameException Class
MailBee Namespace


MailBeeGetLocalHostNameException Class

MailBeeGetLocalHostNameException Class
The exception that is thrown if an attempt to get the local host name through the call of Dns class methods failed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeGetHostNameException
MailBeeMailBeeGetLocalHostNameException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeGetLocalHostNameException : MailBeeGetHostNameException
<SerializableAttribute>
Public Class MailBeeGetLocalHostNameException
    Inherits MailBeeGetHostNameException

The MailBeeGetLocalHostNameException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeGetLocalHostNameException | Initializes a new instance of the MailBeeGetLocalHostNameException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
When this exception is thrown, InnerException property always contains the original exception thrown by Dns class.
See Also

Reference

MailBee Namespace


MailBeeGetLocalHostNameException Constructor

MailBeeGetLocalHostNameException Constructor
Initializes a new instance of the MailBeeGetLocalHostNameException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeGetLocalHostNameException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeGetLocalHostNameException Class
MailBee Namespace


MailBeeGetLocalHostNameException Methods

MailBeeGetLocalHostNameException Methods

The MailBeeGetLocalHostNameException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetLocalHostNameException Class
MailBee Namespace


MailBeeGetLocalHostNameException Properties

MailBeeGetLocalHostNameException Properties

The MailBeeGetLocalHostNameException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetLocalHostNameException Class
MailBee Namespace


MailBeeGetLocalHostNameException Events

MailBeeGetLocalHostNameException Events

The MailBeeGetLocalHostNameException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetLocalHostNameException Class
MailBee Namespace


MailBeeGetRemoteHostNameException Class

MailBeeGetRemoteHostNameException Class
The exception that is thrown if an attempt to resolve the remote host name through the call of Dns class methods failed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeGetHostNameException
MailBeeMailBeeGetRemoteHostNameException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeGetRemoteHostNameException : MailBeeGetHostNameException
<SerializableAttribute>
Public Class MailBeeGetRemoteHostNameException
    Inherits MailBeeGetHostNameException

The MailBeeGetRemoteHostNameException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeGetRemoteHostNameException | Initializes a new instance of the MailBeeGetRemoteHostNameException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets the host name which was not resolved.
Public property | HostProtocol | Gets the type of application-level protocol for which the connection with this host would be used if it was established.
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
When this exception is thrown, InnerException property always contains the original exception thrown by Dns class.
See Also

Reference

MailBee Namespace


MailBeeGetRemoteHostNameException Constructor

MailBeeGetRemoteHostNameException Constructor
Initializes a new instance of the MailBeeGetRemoteHostNameException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeGetRemoteHostNameException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeGetRemoteHostNameException Class
MailBee Namespace


MailBeeGetRemoteHostNameException Methods

MailBeeGetRemoteHostNameException Methods

The MailBeeGetRemoteHostNameException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetRemoteHostNameException Class
MailBee Namespace


MailBeeGetRemoteHostNameException Properties

MailBeeGetRemoteHostNameException Properties

The MailBeeGetRemoteHostNameException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets the host name which was not resolved.
Public property | HostProtocol | Gets the type of application-level protocol for which the connection with this host would be used if it was established.
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetRemoteHostNameException Class
MailBee Namespace


MailBeeGetRemoteHostNameException.HostName Property

MailBeeGetRemoteHostNameExceptionHostName Property
Gets the host name which was not resolved.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HostName { get; }
Public ReadOnly Property HostName As String
    Get

Property Value

Type: String
A string containing the host name which was not resolved.
See Also

Reference

MailBeeGetRemoteHostNameException Class
MailBee Namespace


MailBeeGetRemoteHostNameException.HostProtocol Property

MailBeeGetRemoteHostNameExceptionHostProtocol Property
Gets the type of application-level protocol for which the connection with this host would be used if it was established.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType HostProtocol { get; }
Public ReadOnly Property HostProtocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
Application-level protocol which was planned to be used if the connection with the host was established.
See Also

Reference

MailBeeGetRemoteHostNameException Class
MailBee Namespace


MailBeeGetRemoteHostNameException Events

MailBeeGetRemoteHostNameException Events

The MailBeeGetRemoteHostNameException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeGetRemoteHostNameException Class
MailBee Namespace


MailBeeInternalException Class

MailBeeInternalException Class
The exception that is thrown when an unexpected error occurs in MailBee code.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeInternalException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeInternalException : MailBeeLocalException,
    IMailBeeFatalException
<SerializableAttribute>
Public Class MailBeeInternalException
    Inherits MailBeeLocalException
    Implements IMailBeeFatalException

The MailBeeInternalException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInternalException | Initializes a new instance of the MailBeeInternalException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Please contact AfterLogic support team if you've got this exception.
See Also

Reference

MailBee Namespace


MailBeeInternalException Constructor

MailBeeInternalException Constructor
Initializes a new instance of the MailBeeInternalException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInternalException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInternalException Class
MailBee Namespace


MailBeeInternalException Methods

MailBeeInternalException Methods

The MailBeeInternalException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInternalException Class
MailBee Namespace


MailBeeInternalException Properties

MailBeeInternalException Properties

The MailBeeInternalException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInternalException Class
MailBee Namespace


MailBeeInternalException Events

MailBeeInternalException Events

The MailBeeInternalException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInternalException Class
MailBee Namespace


MailBeeInvalidArgumentException Class

MailBeeInvalidArgumentException Class
The exception that is thrown when an invalid argument value is passed to a method or property.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeInvalidArgumentException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeInvalidArgumentException : MailBeeException
<SerializableAttribute>
Public Class MailBeeInvalidArgumentException
    Inherits MailBeeException

The MailBeeInvalidArgumentException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInvalidArgumentException | Initializes a new instance of the MailBeeInvalidArgumentException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception can be thrown even if ThrowExceptions property value of MailBee component (such as Smtp, Pop3, and Imap) is set to false because it may indicate there is an error in the application code (for instance, network port to connect to cannot be a negative value).

See Also

Reference

MailBee Namespace


MailBeeInvalidArgumentException Constructor

MailBeeInvalidArgumentException Constructor
Initializes a new instance of the MailBeeInvalidArgumentException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInvalidArgumentException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInvalidArgumentException Class
MailBee Namespace


MailBeeInvalidArgumentException Methods

MailBeeInvalidArgumentException Methods

The MailBeeInvalidArgumentException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidArgumentException Class
MailBee Namespace


MailBeeInvalidArgumentException Properties

MailBeeInvalidArgumentException Properties

The MailBeeInvalidArgumentException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidArgumentException Class
MailBee Namespace


MailBeeInvalidArgumentException Events

MailBeeInvalidArgumentException Events

The MailBeeInvalidArgumentException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidArgumentException Class
MailBee Namespace


MailBeeInvalidResponseException Class

MailBeeInvalidResponseException Class
An abstract parent for all exceptions which indicate that a response received from the server cannot be parsed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeInvalidResponseException
MailBee.DnsMXMailBeeInvalidBinaryResponseException
MailBeeMailBeeInvalidTextResponseException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeInvalidResponseException : MailBeeConnectionException
Public MustInherit Class MailBeeInvalidResponseException
    Inherits MailBeeConnectionException

The MailBeeInvalidResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInvalidResponseException | Initializes a new instance of the MailBeeInvalidResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Typical example of the situation when the server response cannot be parsed is an attempt to connect to a POP3 server via the SMTP protocol (or vice versa).
See Also

Reference

MailBee Namespace


MailBeeInvalidResponseException Constructor

MailBeeInvalidResponseException Constructor
Initializes a new instance of the MailBeeInvalidResponseException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInvalidResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInvalidResponseException Class
MailBee Namespace


MailBeeInvalidResponseException Methods

MailBeeInvalidResponseException Methods

The MailBeeInvalidResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidResponseException Class
MailBee Namespace


MailBeeInvalidResponseException Properties

MailBeeInvalidResponseException Properties

The MailBeeInvalidResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeInvalidResponseException Class
MailBee Namespace


MailBeeInvalidResponseException Events

MailBeeInvalidResponseException Events

The MailBeeInvalidResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidResponseException Class
MailBee Namespace


MailBeeInvalidStateException Class

MailBeeInvalidStateException Class
The exception that is thrown when the requested operation cannot be performed in the current state.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeInvalidStateException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeInvalidStateException : MailBeeException
<SerializableAttribute>
Public Class MailBeeInvalidStateException
    Inherits MailBeeException

The MailBeeInvalidStateException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInvalidStateException | Initializes a new instance of the MailBeeInvalidStateException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is thrown even if ThrowExceptions property value of MailBee component (such as Smtp, Pop3, and Imap) is set to false because it indicates there is an error in the application code (for instance, Connect method is called when already connected).

MailBeeInvalidStateException should never occur if the application is written correctly.

See Also

Reference

MailBee Namespace


MailBeeInvalidStateException Constructor

MailBeeInvalidStateException Constructor
Initializes a new instance of the MailBeeInvalidStateException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInvalidStateException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInvalidStateException Class
MailBee Namespace


MailBeeInvalidStateException Methods

MailBeeInvalidStateException Methods

The MailBeeInvalidStateException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidStateException Class
MailBee Namespace


MailBeeInvalidStateException Properties

MailBeeInvalidStateException Properties

The MailBeeInvalidStateException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidStateException Class
MailBee Namespace


MailBeeInvalidStateException Events

MailBeeInvalidStateException Events

The MailBeeInvalidStateException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidStateException Class
MailBee Namespace


MailBeeInvalidTextResponseException Class

MailBeeInvalidTextResponseException Class
The exception that is thrown when the text response received from the server cannot be parsed, and the response data is available.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeInvalidResponseException
MailBeeMailBeeInvalidTextResponseException
MailBeeMailBeeInvalidTextResponseItemException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeInvalidTextResponseException : MailBeeInvalidResponseException
<SerializableAttribute>
Public Class MailBeeInvalidTextResponseException
    Inherits MailBeeInvalidResponseException

The MailBeeInvalidTextResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInvalidTextResponseException | Initializes a new instance of the MailBeeInvalidTextResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string.
Public property | ResponseString | Gets the string which contains the invalid response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeInvalidTextResponseException Constructor

MailBeeInvalidTextResponseException Constructor
Initializes a new instance of the MailBeeInvalidTextResponseException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInvalidTextResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInvalidTextResponseException Class
MailBee Namespace


MailBeeInvalidTextResponseException Methods

MailBeeInvalidTextResponseException Methods

The MailBeeInvalidTextResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidTextResponseException Class
MailBee Namespace


MailBeeInvalidTextResponseException Properties

MailBeeInvalidTextResponseException Properties

The MailBeeInvalidTextResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string.
Public property | ResponseString | Gets the string which contains the invalid response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeInvalidTextResponseException Class
MailBee Namespace


MailBeeInvalidTextResponseException.ResponseEncoding Property

MailBeeInvalidTextResponseExceptionResponseEncoding Property
Gets the encoding which was used to convert response bytes received from the server into a string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ResponseEncoding { get; }
Public ReadOnly Property ResponseEncoding As Encoding
    Get

Property Value

Type: Encoding
The Encoding which was used to convert response bytes received from the server into a string.
Remarks
This encoding is taken from ResponseEncoding property value (such as Pop3.ResponseEncoding, Imap.ResponseEncoding or Smtp.ResponseEncoding).
See Also

Reference

MailBeeInvalidTextResponseException Class
MailBee Namespace


MailBeeInvalidTextResponseException.ResponseString Property

MailBeeInvalidTextResponseExceptionResponseString Property
Gets the string which contains the invalid response data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ResponseString { get; }
Public ReadOnly Property ResponseString As String
    Get

Property Value

Type: String
The string which contains the invalid response data.
See Also

Reference

MailBeeInvalidTextResponseException Class
MailBee Namespace


MailBeeInvalidTextResponseException Events

MailBeeInvalidTextResponseException Events

The MailBeeInvalidTextResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidTextResponseException Class
MailBee Namespace


MailBeeInvalidTextResponseItemException Class

MailBeeInvalidTextResponseItemException Class
The exception that is thrown when a particular element of the text response received from the server cannot be parsed, and the response data is available.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeInvalidResponseException
MailBeeMailBeeInvalidTextResponseException
MailBeeMailBeeInvalidTextResponseItemException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeInvalidTextResponseItemException : MailBeeInvalidTextResponseException
<SerializableAttribute>
Public Class MailBeeInvalidTextResponseItemException
    Inherits MailBeeInvalidTextResponseException

The MailBeeInvalidTextResponseItemException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInvalidTextResponseItemException | Initializes a new instance of the MailBeeInvalidTextResponseItemException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeInvalidTextResponseException.)
Public property | ResponseString | Gets the string which contains the invalid response data. (Inherited from MailBeeInvalidTextResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
For instance, this exception may occur if the response is expected to contain a number, but the actual value cannot be converted into a number.
See Also

Reference

MailBee Namespace


MailBeeInvalidTextResponseItemException Constructor

MailBeeInvalidTextResponseItemException Constructor
Initializes a new instance of the MailBeeInvalidTextResponseItemException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInvalidTextResponseItemException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInvalidTextResponseItemException Class
MailBee Namespace


MailBeeInvalidTextResponseItemException Methods

MailBeeInvalidTextResponseItemException Methods

The MailBeeInvalidTextResponseItemException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidTextResponseItemException Class
MailBee Namespace


MailBeeInvalidTextResponseItemException Properties

MailBeeInvalidTextResponseItemException Properties

The MailBeeInvalidTextResponseItemException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeInvalidTextResponseException.)
Public property | ResponseString | Gets the string which contains the invalid response data. (Inherited from MailBeeInvalidTextResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeInvalidTextResponseItemException Class
MailBee Namespace


MailBeeInvalidTextResponseItemException Events

MailBeeInvalidTextResponseItemException Events

The MailBeeInvalidTextResponseItemException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidTextResponseItemException Class
MailBee Namespace


MailBeeIOException Class

MailBeeIOException Class
The exception that is thrown when the IO operation with file or folder throws one of the following exceptions: IOException, UnauthorizedAccessException, FileNotFoundException, or XmlException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeIOException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeIOException : MailBeeLocalException
<SerializableAttribute>
Public Class MailBeeIOException
    Inherits MailBeeLocalException

The MailBeeIOException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeIOException | Initializes a new instance of the MailBeeIOException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeIOException Constructor

MailBeeIOException Constructor
Initializes a new instance of the MailBeeIOException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeIOException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeIOException Class
MailBee Namespace


MailBeeIOException Methods

MailBeeIOException Methods

The MailBeeIOException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeIOException Class
MailBee Namespace


MailBeeIOException Properties

MailBeeIOException Properties

The MailBeeIOException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeIOException Class
MailBee Namespace


MailBeeIOException Events

MailBeeIOException Events

The MailBeeIOException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeIOException Class
MailBee Namespace


MailBeeLicenseException Class

MailBeeLicenseException Class
The exception that is thrown during instantiation of a MailBee component or calling a static (Shared in Visual Basic) method of a component in the case when no valid license has been assigned to the component.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeLicenseException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeLicenseException : MailBeeLocalException,
    IMailBeeFatalException
<SerializableAttribute>
Public Class MailBeeLicenseException
    Inherits MailBeeLocalException
    Implements IMailBeeFatalException

The MailBeeLicenseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeLicenseException | Initializes a new instance of the MailBeeLicenseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Make sure MailBee.Global.LicenseKey static property is already assigned to the correct license key to the moment of creating an instance or calling static method of the licensed class.
See Also

Reference

MailBee Namespace


MailBeeLicenseException Constructor

MailBeeLicenseException Constructor
Initializes a new instance of the MailBeeLicenseException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeLicenseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeLicenseException Class
MailBee Namespace


MailBeeLicenseException Methods

MailBeeLicenseException Methods

The MailBeeLicenseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLicenseException Class
MailBee Namespace


MailBeeLicenseException Properties

MailBeeLicenseException Properties

The MailBeeLicenseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLicenseException Class
MailBee Namespace


MailBeeLicenseException Events

MailBeeLicenseException Events

The MailBeeLicenseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLicenseException Class
MailBee Namespace


MailBeeLocalException Class

MailBeeLocalException Class
The exception that is thrown when an error occurs due to user actions or problems with accessing local (not network) resources.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
More...

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeLocalException : MailBeeException
<SerializableAttribute>
Public Class MailBeeLocalException
    Inherits MailBeeException

The MailBeeLocalException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeLocalException | Initializes a new instance of the MailBeeLocalException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Examples of local errors are: file not found, database error, aborted by user, license error, etc.
See Also

Reference

MailBee Namespace
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.DnsMXMailBeeDnsServerDisabledException
MailBeeMailBeeDataParsingException
MailBeeMailBeeDataSyntaxException
MailBeeMailBeeExternalException
MailBeeMailBeeInternalException
MailBeeMailBeeIOException
MailBeeMailBeeLicenseException
MailBeeMailBeeLoginWin32Exception
MailBeeMailBeeSystemSettingsException
MailBeeMailBeeUserAbortException
MailBee.OutlookMailBeeOutlookMsgException
MailBee.OutlookMailBeePstException
MailBee.SecurityMailBeeCertificateException
MailBee.SecurityMailBeeCertificateStoreException
MailBee.SecurityMailBeeCryptoProviderException
MailBee.SecurityMailBeeDomainKeysException
MailBee.SecurityMailBeeImpersonationException
MailBee.SecurityMailBeeSmimeException
MailBee.TnefMailBeeTnefException


MailBeeLocalException Constructor

MailBeeLocalException Constructor
Initializes a new instance of the MailBeeLocalException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeLocalException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeLocalException Class
MailBee Namespace


MailBeeLocalException Methods

MailBeeLocalException Methods

The MailBeeLocalException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLocalException Class
MailBee Namespace


MailBeeLocalException Properties

MailBeeLocalException Properties

The MailBeeLocalException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLocalException Class
MailBee Namespace


MailBeeLocalException Events

MailBeeLocalException Events

The MailBeeLocalException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLocalException Class
MailBee Namespace


MailBeeLoginNoCredentialsException Class

MailBeeLoginNoCredentialsException Class
The exception that is thrown when the authentication process cannot proceed, because no account name and/or password was provided by the application.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeLoginNotPossibleException
MailBeeMailBeeLoginNoCredentialsException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeLoginNoCredentialsException : MailBeeLoginNotPossibleException
<SerializableAttribute>
Public Class MailBeeLoginNoCredentialsException
    Inherits MailBeeLoginNotPossibleException

The MailBeeLoginNoCredentialsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeLoginNoCredentialsException | Initializes a new instance of the MailBeeLoginNoCredentialsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | AccountName | Gets the account name which was provided by the application.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Password | Gets the account password which was provided by the application.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeLoginNoCredentialsException Constructor

MailBeeLoginNoCredentialsException Constructor
Initializes a new instance of the MailBeeLoginNoCredentialsException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeLoginNoCredentialsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeLoginNoCredentialsException Class
MailBee Namespace


MailBeeLoginNoCredentialsException Methods

MailBeeLoginNoCredentialsException Methods

The MailBeeLoginNoCredentialsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginNoCredentialsException Class
MailBee Namespace


MailBeeLoginNoCredentialsException Properties

MailBeeLoginNoCredentialsException Properties

The MailBeeLoginNoCredentialsException type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets the account name which was provided by the application.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Password | Gets the account password which was provided by the application.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeLoginNoCredentialsException Class
MailBee Namespace


MailBeeLoginNoCredentialsException.AccountName Property

MailBeeLoginNoCredentialsExceptionAccountName Property
Gets the account name which was provided by the application.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; }
Public ReadOnly Property AccountName As String
    Get

Property Value

Type: String
The account name which was passed by the application, or Empty if no account name was specified.
See Also

Reference

MailBeeLoginNoCredentialsException Class
MailBee Namespace


MailBeeLoginNoCredentialsException.Password Property

MailBeeLoginNoCredentialsExceptionPassword Property
Gets the account password which was provided by the application.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; }
Public ReadOnly Property Password As String
    Get

Property Value

Type: String
The account password which was passed by the application, or Empty if no account password was specified.
See Also

Reference

MailBeeLoginNoCredentialsException Class
MailBee Namespace


MailBeeLoginNoCredentialsException Events

MailBeeLoginNoCredentialsException Events

The MailBeeLoginNoCredentialsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginNoCredentialsException Class
MailBee Namespace


MailBeeLoginNoSupportedMethodsException Class

MailBeeLoginNoSupportedMethodsException Class
The exception that is thrown when the authentication process cannot proceed, because no authentication methods allowed by the application for authentication are supported by the server.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeLoginNotPossibleException
MailBeeMailBeeLoginNoSupportedMethodsException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeLoginNoSupportedMethodsException : MailBeeLoginNotPossibleException
<SerializableAttribute>
Public Class MailBeeLoginNoSupportedMethodsException
    Inherits MailBeeLoginNotPossibleException

The MailBeeLoginNoSupportedMethodsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeLoginNoSupportedMethodsException | Initializes a new instance of the MailBeeLoginNoSupportedMethodsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | RequestedMethods | Gets a set of authentication methods which were requested by the application as allowed for the login process.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | SupportedMethods | Gets a set of authentication methods which are supported by the server.
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
If this exception occurs, the developer may consider to use Auto as a value of:
  • authMethods parameter of Connect(String, Int32, Boolean) method (for POP3)
  • authMethods parameter of Connect(String, Int32, Socket, EndPoint) method (for IMAP4)
  • AuthMethods property (for SMTP)
This exception may also occur if the server supports only authentication methods based on the weak MD5 algorithm (like SaslCramMD5 but the current system is FIPS-compliant and FipsMode is enabled. Such methods, even if they are supported by the server, will be ignored during authentication.
See Also

Reference

MailBee Namespace


MailBeeLoginNoSupportedMethodsException Constructor

MailBeeLoginNoSupportedMethodsException Constructor
Initializes a new instance of the MailBeeLoginNoSupportedMethodsException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeLoginNoSupportedMethodsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeLoginNoSupportedMethodsException Class
MailBee Namespace


MailBeeLoginNoSupportedMethodsException Methods

MailBeeLoginNoSupportedMethodsException Methods

The MailBeeLoginNoSupportedMethodsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginNoSupportedMethodsException Class
MailBee Namespace


MailBeeLoginNoSupportedMethodsException Properties

MailBeeLoginNoSupportedMethodsException Properties

The MailBeeLoginNoSupportedMethodsException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | RequestedMethods | Gets a set of authentication methods which were requested by the application as allowed for the login process.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | SupportedMethods | Gets a set of authentication methods which are supported by the server.
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeLoginNoSupportedMethodsException Class
MailBee Namespace


MailBeeLoginNoSupportedMethodsException.RequestedMethods Property

MailBeeLoginNoSupportedMethodsExceptionRequestedMethods Property
Gets a set of authentication methods which were requested by the application as allowed for the login process.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods RequestedMethods { get; }
Public ReadOnly Property RequestedMethods As AuthenticationMethods
    Get

Property Value

Type: AuthenticationMethods
An AuthenticationMethods value containing bitwise combination of values of individual authentication methods allowed for the login process by the application.
See Also

Reference

MailBeeLoginNoSupportedMethodsException Class
MailBee Namespace


MailBeeLoginNoSupportedMethodsException.SupportedMethods Property

MailBeeLoginNoSupportedMethodsExceptionSupportedMethods Property
Gets a set of authentication methods which are supported by the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods SupportedMethods { get; }
Public ReadOnly Property SupportedMethods As AuthenticationMethods
    Get

Property Value

Type: AuthenticationMethods
An AuthenticationMethods value containing bitwise combination of values of individual authentication methods supported by the server.
See Also

Reference

MailBeeLoginNoSupportedMethodsException Class
MailBee Namespace


MailBeeLoginNoSupportedMethodsException Events

MailBeeLoginNoSupportedMethodsException Events

The MailBeeLoginNoSupportedMethodsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginNoSupportedMethodsException Class
MailBee Namespace


MailBeeLoginNotPossibleException Class

MailBeeLoginNotPossibleException Class
An abstract parent for all exceptions which indicate that the authentication process cannot proceed under current conditions.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeLoginNotPossibleException
MailBeeMailBeeLoginNoCredentialsException
MailBeeMailBeeLoginNoSupportedMethodsException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeLoginNotPossibleException : MailBeeEmailProtocolException,
    IMailBeeLoginException
Public MustInherit Class MailBeeLoginNotPossibleException
    Inherits MailBeeEmailProtocolException
    Implements IMailBeeLoginException

The MailBeeLoginNotPossibleException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeLoginNotPossibleException | Initializes a new instance of the MailBeeLoginNotPossibleException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This kind of exception can be thought of as "nothing to try". For instance, the account name is not specified, the authentication methods requested by the application are missing in the server capabilities list, etc.
See Also

Reference

MailBee Namespace


MailBeeLoginNotPossibleException Constructor

MailBeeLoginNotPossibleException Constructor
Initializes a new instance of the MailBeeLoginNotPossibleException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeLoginNotPossibleException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeLoginNotPossibleException Class
MailBee Namespace


MailBeeLoginNotPossibleException Methods

MailBeeLoginNotPossibleException Methods

The MailBeeLoginNotPossibleException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginNotPossibleException Class
MailBee Namespace


MailBeeLoginNotPossibleException Properties

MailBeeLoginNotPossibleException Properties

The MailBeeLoginNotPossibleException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeLoginNotPossibleException Class
MailBee Namespace


MailBeeLoginNotPossibleException Events

MailBeeLoginNotPossibleException Events

The MailBeeLoginNotPossibleException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginNotPossibleException Class
MailBee Namespace


MailBeeLoginWin32Exception Class

MailBeeLoginWin32Exception Class
The exception that is thrown when underlying Win32 Schannel implementation of Integrated Windows Authentication returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeLoginWin32Exception

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeLoginWin32Exception : MailBeeLocalException,
    IMailBeeLoginException, IMailBeeWin32Exception
<SerializableAttribute>
Public Class MailBeeLoginWin32Exception
    Inherits MailBeeLocalException
    Implements IMailBeeLoginException, IMailBeeWin32Exception

The MailBeeLoginWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeLoginWin32Exception | Initializes a new instance of the MailBeeLoginWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the operating system function related to Integrated Windows Authentication implementation.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
The developer can obtain Win32 error code from NativeErrorCode property.
See Also

Reference

MailBee Namespace


MailBeeLoginWin32Exception Constructor

MailBeeLoginWin32Exception Constructor
Initializes a new instance of the MailBeeLoginWin32Exception class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeLoginWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeLoginWin32Exception Class
MailBee Namespace


MailBeeLoginWin32Exception Methods

MailBeeLoginWin32Exception Methods

The MailBeeLoginWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginWin32Exception Class
MailBee Namespace


MailBeeLoginWin32Exception Properties

MailBeeLoginWin32Exception Properties

The MailBeeLoginWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the operating system function related to Integrated Windows Authentication implementation.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginWin32Exception Class
MailBee Namespace


MailBeeLoginWin32Exception.NativeErrorCode Property

MailBeeLoginWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by the operating system function related to Integrated Windows Authentication implementation.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by one of the functions of Microsoft NTLM security package.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeLoginWin32Exception Class
MailBee Namespace


MailBeeLoginWin32Exception Events

MailBeeLoginWin32Exception Events

The MailBeeLoginWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeLoginWin32Exception Class
MailBee Namespace


MailBeeNetworkException Class

MailBeeNetworkException Class
An abstract parent for all exceptions that are thrown when network errors occur.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeGetHostNameException
MailBeeMailBeeNoIP4HostFoundException
MailBeeMailBeeRemoteHostException
MailBee.SmtpMailMailBeeDnsRecordsDisabledException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeNetworkException : MailBeeException
Public MustInherit Class MailBeeNetworkException
    Inherits MailBeeException

The MailBeeNetworkException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeNetworkException | Initializes a new instance of the MailBeeNetworkException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeNetworkException Constructor

MailBeeNetworkException Constructor
Initializes a new instance of the MailBeeNetworkException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeNetworkException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeNetworkException Class
MailBee Namespace


MailBeeNetworkException Methods

MailBeeNetworkException Methods

The MailBeeNetworkException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeNetworkException Class
MailBee Namespace


MailBeeNetworkException Properties

MailBeeNetworkException Properties

The MailBeeNetworkException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeNetworkException Class
MailBee Namespace


MailBeeNetworkException Events

MailBeeNetworkException Events

The MailBeeNetworkException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeNetworkException Class
MailBee Namespace


MailBeeNoIP4HostFoundException Class

MailBeeNoIP4HostFoundException Class
The exception that is thrown if no IPv4-compatible IP address was found for the given IPHostEntry during the connecting to the remote host.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeNoIP4HostFoundException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeNoIP4HostFoundException : MailBeeNetworkException
<SerializableAttribute>
Public Class MailBeeNoIP4HostFoundException
    Inherits MailBeeNetworkException

The MailBeeNoIP4HostFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeNoIP4HostFoundException | Initializes a new instance of the MailBeeNoIP4HostFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostEntry | Gets a reference to the resolved host data.
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Port | Gets the port number to which the attempt to connect to the remote host was made.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeNoIP4HostFoundException Constructor

MailBeeNoIP4HostFoundException Constructor
Initializes a new instance of the MailBeeNoIP4HostFoundException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeNoIP4HostFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeNoIP4HostFoundException Class
MailBee Namespace


MailBeeNoIP4HostFoundException Methods

MailBeeNoIP4HostFoundException Methods

The MailBeeNoIP4HostFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeNoIP4HostFoundException Class
MailBee Namespace


MailBeeNoIP4HostFoundException Properties

MailBeeNoIP4HostFoundException Properties

The MailBeeNoIP4HostFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostEntry | Gets a reference to the resolved host data.
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Port | Gets the port number to which the attempt to connect to the remote host was made.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeNoIP4HostFoundException Class
MailBee Namespace


MailBeeNoIP4HostFoundException.HostEntry Property

MailBeeNoIP4HostFoundExceptionHostEntry Property
Gets a reference to the resolved host data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPHostEntry HostEntry { get; }
Public ReadOnly Property HostEntry As IPHostEntry
    Get

Property Value

Type: IPHostEntry
The resolved host data which does not contain any IPv4-compatible IP addresses.
See Also

Reference

MailBeeNoIP4HostFoundException Class
MailBee Namespace


MailBeeNoIP4HostFoundException.Port Property

MailBeeNoIP4HostFoundExceptionPort Property
Gets the port number to which the attempt to connect to the remote host was made.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Port { get; }
Public ReadOnly Property Port As Integer
    Get

Property Value

Type: Int32
An integer value which contains the port number of the failed connection.
See Also

Reference

MailBeeNoIP4HostFoundException Class
MailBee Namespace


MailBeeNoIP4HostFoundException Events

MailBeeNoIP4HostFoundException Events

The MailBeeNoIP4HostFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeNoIP4HostFoundException Class
MailBee Namespace


MailBeeProtocolException Class

MailBeeProtocolException Class
An abstract parent for all exceptions which indicate that an application-level protocol error has occurred.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBee.DnsMXMailBeeDnsProtocolException
MailBeeMailBeeEmailProtocolException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeProtocolException : MailBeeRemoteHostException
Public MustInherit Class MailBeeProtocolException
    Inherits MailBeeRemoteHostException

The MailBeeProtocolException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeProtocolException | Initializes a new instance of the MailBeeProtocolException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Typical example of the application-level protocol error is a negative server response.
See Also

Reference

MailBee Namespace


MailBeeProtocolException Constructor

MailBeeProtocolException Constructor
Initializes a new instance of the MailBeeProtocolException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeProtocolException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeProtocolException Class
MailBee Namespace


MailBeeProtocolException Methods

MailBeeProtocolException Methods

The MailBeeProtocolException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProtocolException Class
MailBee Namespace


MailBeeProtocolException Properties

MailBeeProtocolException Properties

The MailBeeProtocolException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeProtocolException Class
MailBee Namespace


MailBeeProtocolException Events

MailBeeProtocolException Events

The MailBeeProtocolException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProtocolException Class
MailBee Namespace


MailBeeProtocolExtensionNotSupportedException Class

MailBeeProtocolExtensionNotSupportedException Class
The exception that is thrown when the mail server does not support certain extension (capability) which is required for the current operation to complete successfully.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeProtocolExtensionNotSupportedException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeProtocolExtensionNotSupportedException : MailBeeEmailProtocolException
<SerializableAttribute>
Public Class MailBeeProtocolExtensionNotSupportedException
    Inherits MailBeeEmailProtocolException

The MailBeeProtocolExtensionNotSupportedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeProtocolExtensionNotSupportedException | Initializes a new instance of the MailBeeProtocolExtensionNotSupportedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeProtocolExtensionNotSupportedException Constructor

MailBeeProtocolExtensionNotSupportedException Constructor
Initializes a new instance of the MailBeeProtocolExtensionNotSupportedException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeProtocolExtensionNotSupportedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeProtocolExtensionNotSupportedException Class
MailBee Namespace


MailBeeProtocolExtensionNotSupportedException Methods

MailBeeProtocolExtensionNotSupportedException Methods

The MailBeeProtocolExtensionNotSupportedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProtocolExtensionNotSupportedException Class
MailBee Namespace


MailBeeProtocolExtensionNotSupportedException Properties

MailBeeProtocolExtensionNotSupportedException Properties

The MailBeeProtocolExtensionNotSupportedException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeProtocolExtensionNotSupportedException Class
MailBee Namespace


MailBeeProtocolExtensionNotSupportedException Events

MailBeeProtocolExtensionNotSupportedException Events

The MailBeeProtocolExtensionNotSupportedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProtocolExtensionNotSupportedException Class
MailBee Namespace


MailBeeRemoteHostException Class

MailBeeRemoteHostException Class
An abstract parent for all exceptions which occur when MailBee attempts to establish connection or send/receive data to/from the server at the given IP address and port number.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeProtocolException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeRemoteHostException : MailBeeNetworkException
Public MustInherit Class MailBeeRemoteHostException
    Inherits MailBeeNetworkException

The MailBeeRemoteHostException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeRemoteHostException | Initializes a new instance of the MailBeeRemoteHostException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred.
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeRemoteHostException Constructor

MailBeeRemoteHostException Constructor
Initializes a new instance of the MailBeeRemoteHostException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeRemoteHostException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException Methods

MailBeeRemoteHostException Methods

The MailBeeRemoteHostException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException Properties

MailBeeRemoteHostException Properties

The MailBeeRemoteHostException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host.
Public property | RemoteHostName | Gets the host name of the server.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred.
Top
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException.Protocol Property

MailBeeRemoteHostExceptionProtocol Property
Gets application-level protocol of the current connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TopLevelProtocolType Protocol { get; }
Public ReadOnly Property Protocol As TopLevelProtocolType
    Get

Property Value

Type: TopLevelProtocolType
The protocol of the current connection, or Unknown if the protocol is unknown.
Remarks
This value indicates the protocol this connection is used for.
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException.RemoteEndPoint Property

MailBeeRemoteHostExceptionRemoteEndPoint Property
Gets a reference to the end point of the server host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPEndPoint RemoteEndPoint { get; }
Public ReadOnly Property RemoteEndPoint As IPEndPoint
    Get

Property Value

Type: IPEndPoint
The end point which provides information about IP address and port of the connection with the server.
Remarks
This value is a null reference (Nothing in Visual Basic) if Protocol is Ews.
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException.RemoteHostName Property

MailBeeRemoteHostExceptionRemoteHostName Property
Gets the host name of the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteHostName { get; }
Public ReadOnly Property RemoteHostName As String
    Get

Property Value

Type: String
A string indicating the host name of the server.
Remarks
This value is an Exchange server URL if Protocol is Ews.
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException.WasConnected Property

MailBeeRemoteHostExceptionWasConnected Property
Gets if the connection with the server had already been established to the moment when the exception occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool WasConnected { get; }
Public ReadOnly Property WasConnected As Boolean
    Get

Property Value

Type: Boolean
true if the exception occurred after the server had already accepted the incoming connection from MailBee and returned the initial prompt; otherwise, false.
Remarks

If the server accepted the incoming connection but not yet returned the initial response, it's considered the connection hasn't been established yet. Typical case when this can occur (the socket connected but the full connection procedure was not complete) is when an error occurs during SSL handshake which occurs right between socket connection and returning an initial response to the client.

Not used for Exchange (EWS) protocol.

See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostException Events

MailBeeRemoteHostException Events

The MailBeeRemoteHostException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeRemoteHostException Class
MailBee Namespace


MailBeeRemoteHostResponseTimeoutException Class

MailBeeRemoteHostResponseTimeoutException Class
The exception that is thrown when the remote host returns the response so slowly that it cannot be tolerated by the client.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeRemoteHostResponseTimeoutException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeRemoteHostResponseTimeoutException : MailBeeConnectionException
<SerializableAttribute>
Public Class MailBeeRemoteHostResponseTimeoutException
    Inherits MailBeeConnectionException

The MailBeeRemoteHostResponseTimeoutException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeRemoteHostResponseTimeoutException | Initializes a new instance of the MailBeeRemoteHostResponseTimeoutException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is thrown when the server does return data (and technically, there is no socket timeout because each new chunk arrives in the time less than socket timeout interval) but the overall performance is not satisfactory.

In other words, socket timeouts occur when the time of waiting for next data chunk of the response exceeds certain limit while the current exception indicates the total summed time of receiving all data chunks of the server response to the current command exceeds the limit.

Currently, this exception can only be thrown during making SMTP connections. There are servers which start responding, but very slowly. They send something like "220 Hello, I'm Server ZYZ, nice to meet you" in 1-byte chunks, each one takes 10-20 seconds, thus the total reply may take 10-15 minutes. MailBee won't let your application hang for such a long time and will disconnect throwing the current exception.

The error code associated with this exception is ResponseTimeout.

See Also

Reference

MailBee Namespace


MailBeeRemoteHostResponseTimeoutException Constructor

MailBeeRemoteHostResponseTimeoutException Constructor
Initializes a new instance of the MailBeeRemoteHostResponseTimeoutException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeRemoteHostResponseTimeoutException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeRemoteHostResponseTimeoutException Class
MailBee Namespace


MailBeeRemoteHostResponseTimeoutException Methods

MailBeeRemoteHostResponseTimeoutException Methods

The MailBeeRemoteHostResponseTimeoutException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeRemoteHostResponseTimeoutException Class
MailBee Namespace


MailBeeRemoteHostResponseTimeoutException Properties

MailBeeRemoteHostResponseTimeoutException Properties

The MailBeeRemoteHostResponseTimeoutException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeRemoteHostResponseTimeoutException Class
MailBee Namespace


MailBeeRemoteHostResponseTimeoutException Events

MailBeeRemoteHostResponseTimeoutException Events

The MailBeeRemoteHostResponseTimeoutException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeRemoteHostResponseTimeoutException Class
MailBee Namespace


MailBeeSocketAbortedException Class

MailBeeSocketAbortedException Class
The exception that is thrown when underlying socket operation receives abort request from the software on the local machine and throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketAbortedException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketAbortedException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketAbortedException
    Inherits MailBeeSocketException

The MailBeeSocketAbortedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketAbortedException | Initializes a new instance of the MailBeeSocketAbortedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This error corresponds to WSAECONNABORTED Win32 error. InnerException property contains the original SocketException.
See Also

Reference

MailBee Namespace


MailBeeSocketAbortedException Constructor

MailBeeSocketAbortedException Constructor
Initializes a new instance of the MailBeeSocketAbortedException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketAbortedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketAbortedException Class
MailBee Namespace


MailBeeSocketAbortedException Methods

MailBeeSocketAbortedException Methods

The MailBeeSocketAbortedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketAbortedException Class
MailBee Namespace


MailBeeSocketAbortedException Properties

MailBeeSocketAbortedException Properties

The MailBeeSocketAbortedException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketAbortedException Class
MailBee Namespace


MailBeeSocketAbortedException Events

MailBeeSocketAbortedException Events

The MailBeeSocketAbortedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketAbortedException Class
MailBee Namespace


MailBeeSocketException Class

MailBeeSocketException Class
The exception that is thrown when underlying socket operation throws SocketException or IOException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
More...

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketException : MailBeeConnectionException
<SerializableAttribute>
Public Class MailBeeSocketException
    Inherits MailBeeConnectionException

The MailBeeSocketException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketException | Initializes a new instance of the MailBeeSocketException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
InnerException property contains the original SocketException or IOException.
Note Note
There is another exception type, MailBeeIOException. Such exceptions are thrown when underlying code throws IOException but that code is not related to a mail or DNS server connectivity (e.g. disk I/O).
See Also

Reference

MailBee Namespace
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketAbortedException
MailBeeMailBeeSocketHostDownException
MailBeeMailBeeSocketHostNotFoundException
MailBeeMailBeeSocketHostUnreachableException
MailBeeMailBeeSocketRefusedException
MailBeeMailBeeSocketResetException
MailBeeMailBeeSocketTimeoutException


MailBeeSocketException Constructor

MailBeeSocketException Constructor
Initializes a new instance of the MailBeeSocketException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketException Class
MailBee Namespace


MailBeeSocketException Methods

MailBeeSocketException Methods

The MailBeeSocketException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketException Class
MailBee Namespace


MailBeeSocketException Properties

MailBeeSocketException Properties

The MailBeeSocketException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketException Class
MailBee Namespace


MailBeeSocketException Events

MailBeeSocketException Events

The MailBeeSocketException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketException Class
MailBee Namespace


MailBeeSocketHostDownException Class

MailBeeSocketHostDownException Class
The exception that is thrown when underlying socket operation detects a dead host and throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketHostDownException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketHostDownException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketHostDownException
    Inherits MailBeeSocketException

The MailBeeSocketHostDownException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketHostDownException | Initializes a new instance of the MailBeeSocketHostDownException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This error corresponds to WSAEHOSTDOWN Win32 error. InnerException property contains the original SocketException.
See Also

Reference

MailBee Namespace


MailBeeSocketHostDownException Constructor

MailBeeSocketHostDownException Constructor
Initializes a new instance of the MailBeeSocketHostDownException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketHostDownException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketHostDownException Class
MailBee Namespace


MailBeeSocketHostDownException Methods

MailBeeSocketHostDownException Methods

The MailBeeSocketHostDownException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketHostDownException Class
MailBee Namespace


MailBeeSocketHostDownException Properties

MailBeeSocketHostDownException Properties

The MailBeeSocketHostDownException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketHostDownException Class
MailBee Namespace


MailBeeSocketHostDownException Events

MailBeeSocketHostDownException Events

The MailBeeSocketHostDownException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketHostDownException Class
MailBee Namespace


MailBeeSocketHostNotFoundException Class

MailBeeSocketHostNotFoundException Class
The exception that is thrown when underlying socket operation detects an unknown host and throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketHostNotFoundException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketHostNotFoundException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketHostNotFoundException
    Inherits MailBeeSocketException

The MailBeeSocketHostNotFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketHostNotFoundException | Initializes a new instance of the MailBeeSocketHostNotFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This error corresponds to WSAHOST_NOT_FOUND Win32 error. InnerException property contains the original SocketException.
See Also

Reference

MailBee Namespace


MailBeeSocketHostNotFoundException Constructor

MailBeeSocketHostNotFoundException Constructor
Initializes a new instance of the MailBeeSocketHostNotFoundException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketHostNotFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketHostNotFoundException Class
MailBee Namespace


MailBeeSocketHostNotFoundException Methods

MailBeeSocketHostNotFoundException Methods

The MailBeeSocketHostNotFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketHostNotFoundException Class
MailBee Namespace


MailBeeSocketHostNotFoundException Properties

MailBeeSocketHostNotFoundException Properties

The MailBeeSocketHostNotFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketHostNotFoundException Class
MailBee Namespace


MailBeeSocketHostNotFoundException Events

MailBeeSocketHostNotFoundException Events

The MailBeeSocketHostNotFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketHostNotFoundException Class
MailBee Namespace


MailBeeSocketHostUnreachableException Class

MailBeeSocketHostUnreachableException Class
The exception that is thrown when underlying socket operation detects there is no known route to the host and throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketHostUnreachableException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketHostUnreachableException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketHostUnreachableException
    Inherits MailBeeSocketException

The MailBeeSocketHostUnreachableException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketHostUnreachableException | Initializes a new instance of the MailBeeSocketHostUnreachableException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This error corresponds to WSAEHOSTUNREACH Win32 error. InnerException property contains the original SocketException.
See Also

Reference

MailBee Namespace


MailBeeSocketHostUnreachableException Constructor

MailBeeSocketHostUnreachableException Constructor
Initializes a new instance of the MailBeeSocketHostUnreachableException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketHostUnreachableException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketHostUnreachableException Class
MailBee Namespace


MailBeeSocketHostUnreachableException Methods

MailBeeSocketHostUnreachableException Methods

The MailBeeSocketHostUnreachableException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketHostUnreachableException Class
MailBee Namespace


MailBeeSocketHostUnreachableException Properties

MailBeeSocketHostUnreachableException Properties

The MailBeeSocketHostUnreachableException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketHostUnreachableException Class
MailBee Namespace


MailBeeSocketHostUnreachableException Events

MailBeeSocketHostUnreachableException Events

The MailBeeSocketHostUnreachableException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketHostUnreachableException Class
MailBee Namespace


MailBeeSocketObjectDisposedException Class

MailBeeSocketObjectDisposedException Class
The exception that is thrown when underlying socket operation unexpectedly throws ObjectDisposedException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketObjectDisposedException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketObjectDisposedException : MailBeeConnectionException
<SerializableAttribute>
Public Class MailBeeSocketObjectDisposedException
    Inherits MailBeeConnectionException

The MailBeeSocketObjectDisposedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketObjectDisposedException | Initializes a new instance of the MailBeeSocketObjectDisposedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

InnerException property contains the original ObjectDisposedException.

This exception corresponds to SocketDisposed error code.

See Also

Reference

MailBee Namespace


MailBeeSocketObjectDisposedException Constructor

MailBeeSocketObjectDisposedException Constructor
Initializes a new instance of the MailBeeSocketObjectDisposedException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketObjectDisposedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketObjectDisposedException Class
MailBee Namespace


MailBeeSocketObjectDisposedException Methods

MailBeeSocketObjectDisposedException Methods

The MailBeeSocketObjectDisposedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketObjectDisposedException Class
MailBee Namespace


MailBeeSocketObjectDisposedException Properties

MailBeeSocketObjectDisposedException Properties

The MailBeeSocketObjectDisposedException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketObjectDisposedException Class
MailBee Namespace


MailBeeSocketObjectDisposedException Events

MailBeeSocketObjectDisposedException Events

The MailBeeSocketObjectDisposedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketObjectDisposedException Class
MailBee Namespace


MailBeeSocketRefusedException Class

MailBeeSocketRefusedException Class
The exception that is thrown when underlying socket operation detects the remote machine refused the connection (which usually means no server program is running on the remote host) and throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketRefusedException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketRefusedException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketRefusedException
    Inherits MailBeeSocketException

The MailBeeSocketRefusedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketRefusedException | Initializes a new instance of the MailBeeSocketRefusedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This error corresponds to WSAECONNREFUSED Win32 error. InnerException property contains the original SocketException.
See Also

Reference

MailBee Namespace


MailBeeSocketRefusedException Constructor

MailBeeSocketRefusedException Constructor
Initializes a new instance of the MailBeeSocketRefusedException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketRefusedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketRefusedException Class
MailBee Namespace


MailBeeSocketRefusedException Methods

MailBeeSocketRefusedException Methods

The MailBeeSocketRefusedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketRefusedException Class
MailBee Namespace


MailBeeSocketRefusedException Properties

MailBeeSocketRefusedException Properties

The MailBeeSocketRefusedException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketRefusedException Class
MailBee Namespace


MailBeeSocketRefusedException Events

MailBeeSocketRefusedException Events

The MailBeeSocketRefusedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketRefusedException Class
MailBee Namespace


MailBeeSocketResetException Class

MailBeeSocketResetException Class
The exception that is thrown when the connection was forcibly closed by the remote host so that underlying socket implementation throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketResetException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketResetException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketResetException
    Inherits MailBeeSocketException

The MailBeeSocketResetException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketResetException | Initializes a new instance of the MailBeeSocketResetException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This error corresponds to WSAECONNABORTED Win32 error. InnerException property contains the original SocketException.

Getting this exception during TLS/SSL negotiation often indicates the server does not support the selected security protocol (see SecurityProtocol topic for details).

See Also

Reference

MailBee Namespace


MailBeeSocketResetException Constructor

MailBeeSocketResetException Constructor
Initializes a new instance of the MailBeeSocketResetException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketResetException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketResetException Class
MailBee Namespace


MailBeeSocketResetException Methods

MailBeeSocketResetException Methods

The MailBeeSocketResetException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketResetException Class
MailBee Namespace


MailBeeSocketResetException Properties

MailBeeSocketResetException Properties

The MailBeeSocketResetException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketResetException Class
MailBee Namespace


MailBeeSocketResetException Events

MailBeeSocketResetException Events

The MailBeeSocketResetException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketResetException Class
MailBee Namespace


MailBeeSocketTimeoutException Class

MailBeeSocketTimeoutException Class
The exception that is thrown when underlying socket operation encounters a timeout and throws SocketException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeSocketException
MailBeeMailBeeSocketTimeoutException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSocketTimeoutException : MailBeeSocketException
<SerializableAttribute>
Public Class MailBeeSocketTimeoutException
    Inherits MailBeeSocketException

The MailBeeSocketTimeoutException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSocketTimeoutException | Initializes a new instance of the MailBeeSocketTimeoutException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This error corresponds to WSAETIMEDOUT Win32 error. InnerException property contains the original SocketException.
See Also

Reference

MailBee Namespace


MailBeeSocketTimeoutException Constructor

MailBeeSocketTimeoutException Constructor
Initializes a new instance of the MailBeeSocketTimeoutException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSocketTimeoutException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSocketTimeoutException Class
MailBee Namespace


MailBeeSocketTimeoutException Methods

MailBeeSocketTimeoutException Methods

The MailBeeSocketTimeoutException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketTimeoutException Class
MailBee Namespace


MailBeeSocketTimeoutException Properties

MailBeeSocketTimeoutException Properties

The MailBeeSocketTimeoutException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSocketTimeoutException Class
MailBee Namespace


MailBeeSocketTimeoutException Events

MailBeeSocketTimeoutException Events

The MailBeeSocketTimeoutException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSocketTimeoutException Class
MailBee Namespace


MailBeeStreamException Class

MailBeeStreamException Class
The exception that is thrown when the operation with data stream throws IOException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeStreamException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeStreamException : MailBeeException
<SerializableAttribute>
Public Class MailBeeStreamException
    Inherits MailBeeException

The MailBeeStreamException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeStreamException | Initializes a new instance of the MailBeeStreamException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeStreamException Constructor

MailBeeStreamException Constructor
Initializes a new instance of the MailBeeStreamException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeStreamException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeStreamException Class
MailBee Namespace


MailBeeStreamException Methods

MailBeeStreamException Methods

The MailBeeStreamException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeStreamException Class
MailBee Namespace


MailBeeStreamException Properties

MailBeeStreamException Properties

The MailBeeStreamException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeStreamException Class
MailBee Namespace


MailBeeStreamException Events

MailBeeStreamException Events

The MailBeeStreamException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeStreamException Class
MailBee Namespace


MailBeeSystemSettingsException Class

MailBeeSystemSettingsException Class
The exception that is thrown when an attempt to request certain information from the system failed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeSystemSettingsException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSystemSettingsException : MailBeeLocalException
<SerializableAttribute>
Public Class MailBeeSystemSettingsException
    Inherits MailBeeLocalException

The MailBeeSystemSettingsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSystemSettingsException | Initializes a new instance of the MailBeeSystemSettingsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
For instance, this exception can be thrown on direct send attempt using QuickSend(MailMessage) method when there are no DNS servers registered in the system.
See Also

Reference

MailBee Namespace


MailBeeSystemSettingsException Constructor

MailBeeSystemSettingsException Constructor
Initializes a new instance of the MailBeeSystemSettingsException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSystemSettingsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSystemSettingsException Class
MailBee Namespace


MailBeeSystemSettingsException Methods

MailBeeSystemSettingsException Methods

The MailBeeSystemSettingsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSystemSettingsException Class
MailBee Namespace


MailBeeSystemSettingsException Properties

MailBeeSystemSettingsException Properties

The MailBeeSystemSettingsException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSystemSettingsException Class
MailBee Namespace


MailBeeSystemSettingsException Events

MailBeeSystemSettingsException Events

The MailBeeSystemSettingsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSystemSettingsException Class
MailBee Namespace


MailBeeUserAbortException Class

MailBeeUserAbortException Class
The exception that is thrown after Abort method of MailBee component has been called.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBeeMailBeeUserAbortException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeUserAbortException : MailBeeLocalException,
    IMailBeeFatalException
<SerializableAttribute>
Public Class MailBeeUserAbortException
    Inherits MailBeeLocalException
    Implements IMailBeeFatalException

The MailBeeUserAbortException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeUserAbortException | Initializes a new instance of the MailBeeUserAbortException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
For instance, if the Pop3 component is downloading mail (DownloadEntireMessage(Int32) method is in progress), and Abort is called, DownloadEntireMessage(Int32) method will throw this exception.
See Also

Reference

MailBee Namespace


MailBeeUserAbortException Constructor

MailBeeUserAbortException Constructor
Initializes a new instance of the MailBeeUserAbortException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeUserAbortException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeUserAbortException Class
MailBee Namespace


MailBeeUserAbortException Methods

MailBeeUserAbortException Methods

The MailBeeUserAbortException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeUserAbortException Class
MailBee Namespace


MailBeeUserAbortException Properties

MailBeeUserAbortException Properties

The MailBeeUserAbortException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeUserAbortException Class
MailBee Namespace


MailBeeUserAbortException Events

MailBeeUserAbortException Events

The MailBeeUserAbortException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeUserAbortException Class
MailBee Namespace


MailBeeWebException Class

MailBeeWebException Class
The exception that is thrown when underlying network operation throws the WebException.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeWebException

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeWebException : MailBeeException
<SerializableAttribute>
Public Class MailBeeWebException
    Inherits MailBeeException

The MailBeeWebException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeWebException | Initializes a new instance of the MailBeeWebException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee Namespace


MailBeeWebException Constructor

MailBeeWebException Constructor
Initializes a new instance of the MailBeeWebException class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeWebException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeWebException Class
MailBee Namespace


MailBeeWebException Methods

MailBeeWebException Methods

The MailBeeWebException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeWebException Class
MailBee Namespace


MailBeeWebException Properties

MailBeeWebException Properties

The MailBeeWebException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeWebException Class
MailBee Namespace


MailBeeWebException Events

MailBeeWebException Events

The MailBeeWebException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeWebException Class
MailBee Namespace


AuthenticationMethods Enumeration

AuthenticationMethods Enumeration
Provides authentication methods to be used for logging in the user account on the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum AuthenticationMethods
<FlagsAttribute>
Public Enumeration AuthenticationMethods
Members
Member name | Value | Description
None | 0 | No authentication. Sometimes used with Smtp when the server allows relay for anonymous senders.
Regular | 1 | Standard authentication. Passwords are transmitted as clear-text. Not supported by SMTP servers.
Apop | 2 | Secure APOP authentication. Supported by many POP3 servers but cannot be used with other servers like SMTP because APOP is POP3-specific. Disabled when FipsMode is enabled.
SaslUserDefined | 4 | A custom SASL authentication method implemented by the developer.
SaslLogin | 8 | SASL LOGIN authentication. Not secure but widely supported. Passwords are transmitted as Base64 strings. Note for IMAP users: this is AUTHENTICATE LOGIN command, not just LOGIN command (which corresponds to Regular method).
SaslPlain | 16 | SASL PLAIN authentication. Not secure but widely supported. Passwords are transmitted as Base64 strings.
SaslCramMD5 | 32 | Secure SASL CRAM-MD5 authentication. Might not be supported by particular server implementations. Disabled when FipsMode is enabled.
SaslDigestMD5 | 64 | Secure SASL DIGEST-MD5 authentication. Might not be supported by particular server implementations. Disabled when FipsMode is enabled.
SaslNtlm | 128 | Secure SASL NTLM authentication (also known as Secure Password Authentication - SPA). In Windows domain environment such as Active Directory, can also be used to authenticate the current Windows user (in this case, the developer should pass a null reference (Nothing in Visual Basic) as accountName and password values). Might not be supported by particular server implementations. May not work in UWP apps, consider GSSAPI instead. See remarks section for futher details regarding Integrated Windows Authentication.
SaslMsn | 256 | Secure SASL MSN authentication (equivalent to NTLM). Not widely supported nowadays.
SaslGssApi | 512 | Secure SASL GSSAPI authentication (through Kerberos or NTLM). Like SaslNtlm, supports Integrated Windows Authentication mode. The internal implementation (Kerberos or NTLM) is selected upon whether targetName of Login method is an empty string or not (for SMTP case, TargetName). Empty string denotes NTLM, all other values (including a null reference) denote Kerberos. Also, the underlying implementation downgrades to NTLM from Kerberos if targetName is not empty but not valid (denotes non-existent SPN).
SaslOAuth | 1024 | OAuth v1.0 authentication (widely used by Google in the past). It's a password-only authentication. To create a key to be supplied as the OAuth password, use OAuth class. As the OAuth account name, specify a null reference (Nothing in Visual Basic). Note that if you supplied both the password and the account name when logging in, MailBee will exclude OAuth from the set of authentication methods to be tried unless SaslOAuth is the only method listed in this set. This is because OAuth is not compatible with other authentication methods which require a login and a password, not a "key". You can, however, specify non-null account name if you explicitly specified SaslOAuth method to be used for login. This account name can be any string, it won't be used during the login process itself (because it uses only the password) but it will be displayed in the log file in place of the account name.
SaslOAuth2 | 2048 | OAuth v2.0 authentication. A newer and recommended version of OAuth. All MailBee-specific details (listed above in SaslOAuth description) are valid for this method as well.
Auto | 4095 | Tells MailBee to automatically select the best supported authentication method and downgrade to insecure methods if secure methods are not supported by the server. This behavior can be changed with AuthenticationOptions flags.
Remarks

A SASL method can be used with all protocols (SMTP, POP3, IMAP) provided that the server supports the given method. Non-SASL methods are protocol-specific.

You can implement your own authentication methods. See SaslMethod topic for details.

Note Note
When the application is a web application which operates under context of anonymous user, Integrated Windows Authentication will use the context of this anonymous user (which most likely doesn't have an account on the mail server). Thus, using Integrated Windows Authentication does not make sense for web apps operating under anonymous user account (Internet Guest User).
See Also

Reference

MailBee Namespace
MailBeeAuthenticationOptions
Pop3Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
ImapLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
SmtpServerAuthMethods
SmtpServerAuthPopBeforeSmtp


AuthenticationOptions Enumeration

AuthenticationOptions Enumeration
Provides flags for tuning the authentication process.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum AuthenticationOptions
<FlagsAttribute>
Public Enumeration AuthenticationOptions
Members
Member name | Value | Description
None | 0 | No flags set.
TryUnsupportedMethods | 1 | Force MailBee to try authentication methods regardless whether they are advertized by the server in its capabilities or not.
UseSingleMethodOnly | 2 | Force MailBee not to switch to other authentication methods if the best (most secure) of the desired methods is not supported by the server. Usually makes sense only if TryUnsupportedMethods flag is set too because otherwise the possibly unsupported methods won't even be tried at all.
PreferSimpleMethods | 4 | Force MailBee to try simple (i.e. non-secure) authentication methods before secure ones. In other words, MailBee will iterate through the list of desired methods in reverse order. This option is useful for communicating with mail servers which have errors in their secure authentication implementations. This flag is also set by default if SafeMode was true. However, if you would better prefer to use secure methods if possible, consider using DisableSimpleMethodAfterSecure flag.
DisableSimpleMethodAfterSecure | 8 | If this flag is set, MailBee won't retry the login attempt with a simple method if the currently tried secure method failed the authentication. Set this flag if you require the client to always use secure authentication. Do not set this flag if the server has problems with its implementation of security algorithms (many servers advertize secure authentication capability but in fact do not implement it correctly). The flag has no effect if non-secure methods are not available (e.g. when IMAP server advertizes LOGINDISABLED or SMTP server advertizes nothing but NTLM), or if PreferSimpleMethods flag is set (because the simple method would have already been tried to the moment), or if UseSingleMethodOnly flag is set (because it assumes the highest level of security).
PreferSspiOverNegotiateStream | 16 | If this flag is set, MailBee will use SSPI implementation of NTLM and GSSAPI methods. This implementation requires UnmanagedCode permission due to the need to access Windows API. If this flag is not set, MailBee will use NegotiateStream managed implementation and thus not require UnmanagedCode permission. Setting this flag sometimes helps with MS Exchange connectivity. Also, this flag has no effect for UWP and .NET Core apps as they can't work with NegotiateStream and SSPI implementation is used even if this flag is not set.
UseLocalDomainAsDefault | 32 | If this flag is set and no domain is specified (neither in account name nor in separate domain parameter), MailBee will use the local domain name for that. If not set, MailBee will use empty domain name in this case. This flag is only used with NTLM and GSSAPI authentication methods.
BypassLoginProcedure | 64 | Set this flag if Login method must only change the internal state of the component to "logged in", no actual commands to the mail server will be sent. Useful when the login itself is performed with custom commands.
Remarks

These flags affect how MailBee selects authentication methods for login process.

By default, MailBee takes the list of the desired authentication methods (specified by authMethods parameter of Pop3.Login method for Pop3, authMethods parameter of Imap.Login method for Imap, or by SmtpServer.AuthMethods property for Smtp), filters out the methods not advertized by the server in its capabilities, and then tries the remained methods until compatible method is found. If such method was found, it's used for the authentication process. If not, an exception is thrown if exceptions are enabled.

The flags in this enumeration allow the developer to change the default behavior of MailBee.

The above means that the authentication process is actually two-step. First, the appropriate method is selected, then, it's tried. Most flags affect how the appropriate method is selected (i.e. the first step). DisableSimpleMethodAfterSecure flag, however, affects what happens after the second step (what to do if the authentication fails).

See Also

Reference

MailBee Namespace
MailBeeAuthenticationMethods
Pop3Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
ImapLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
SmtpServerAuthMethods


ErrorCodes Class

ErrorCodes Class
Provides error code values returned by ErrorCode property of MailBee exceptions and LastResult property of MailBee classes implementing this property.
Inheritance Hierarchy
SystemObject
MailBeeErrorCodes

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ErrorCodes
Public Class ErrorCodes

The ErrorCodes type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Fields
Name | Description
AbortedByLocalHost | The software on the local computer has aborted the connection.
AbortedByServer | The remote host has aborted the connection.
AbortedByUser | The current operation was aborted by user.
AlreadyConnected | Already connected to the server.
AlreadyLoggedIn | Already logged in the user account on the server.
AlreadySsl | Already in SSL/TLS mode.
ArgumentEmpty | A null reference (Nothing in Visual Basic) or an empty string/array/collection is not allowed as the argument value.
ArgumentInvalid | The specified argument value is invalid.
ArgumentNull | A null reference (Nothing in Visual Basic) is not allowed as the argument value.
ArgumentOutOfRange | The argument value is out of range.
BadCredentials | Invalid account name and/or password was supplied for the login.
BadDnsResponseHeader | The response from the DNS server contains invalid header.
BadMessageData | The SMTP server rejected the message data sent by the client.
BadRecipient | The SMTP server refused the e-mail address of the mail message recipient.
BadSender | The SMTP server refused the e-mail address of the mail message sender.
BdatRejected | The server responded with a negative reply to BDAT command (although the server claims to support CHUNKING extension).
BdatTimeout | Socket timeout during SMTP BDAT command.
Busy | The component is busy with lengthy or asynchronous operation.
CertificateDataInvalid | Could not restore the certificate from the supplied data.
CertificateStoreWin32Error | Win32 function related to certificate store API returned an error.
CertificateValidationError | Certificate validation failed.
CertificateWin32Error | Certificate-related Win32 function returned an error.
ConnectionRefused | The remote host refused the connection attempt initiated by the client.
ConnectionReset | An existing connection was forcibly closed by the remote host.
Conversion8bitTo7Bit | 7bit-to-8bit conversion of the message data is required.
CryptographicException | CryptographicException occurred.
CryptoPrivateKeyInvalid | Could not decode the private key.
CryptoProviderWin32Error | Win32 function related to a crypto provider API returned an error.
DataNotAllowed | The SMTP server responded with a negative reply to the DATA command.
DeadDomainSmtpMXesInCache | It's known (from the DNS cache) that all DNS MX records for the domain point to dead hosts.
DnsFailureReply | The DNS server replied with "Server failure" status code.
DnsFormatErrorReply | The DNS server replied with "Format Error" status code.
DnsInvalidQName | The specified host name does not conform with Domain Name System rules.
DnsNameErrorReply | The DNS server replied with "Name Error" status code.
DnsNotSupportedReply | The DNS server replied with "Not Implemented" status code.
DnsQueryMismatch | The ID of the DNS server response if different from the ID of the request sent by the client.
DnsQueryRefusedReply | The DNS server replied with "Refused" status code.
DnsRecursionRequired | The DNS server must support recursion in order to complete the request.
DnsUnknownReply | The DNS server replied with unknown status code.
EhloNotSupported | The SMTP server does not support any ESMTP extensions.
EmptyHostNameForDnsQuery | Cannot perform DNS query for an empty host name.
EmptyResponseLine | The response from the server contains just a response terminator but no data.
EncodingError | An exception occurred while performing string conversion.
EwsFolderAlreadyExists | EWS folder already exists.
EwsFolderNotFound | EWS folder not found.
EwsLocalException | Client-side EWS error occurred.
EwsRemoteException | Server-side EWS error occurred.
ExternalError | The application code threw an exception while handling MailBee event.
FileNotFoundException | FileNotFoundException occurred.
HostDown | The specified host is down.
HostNotFound | The specified host was not found.
HostUnreachable | There is no known network route to the specified host.
IllegalContext | The requested operation cannot be performed in the current context.
IllegalInCurrentState | The method cannot run in the current state of the object.
IllegalInMultiThreadMode | The requested operation cannot be performed in multi-thread mode.
IllegalRaiseEventsMode | Wait method cannot be used if RaiseEventsViaMessageLoop is true.
ImapFolderNotSelected | This command requires a folder be selected on the IMAP4 server. Call SelectFolder(String) or ExamineFolder(String) first.
ImapIdleNotSupported | The IMAP4 server does not support IDLE capability required to go into IDLE mode.
ImapMessageIndexNotFound | The message with the specified index does not exist on the server.
ImapNamespaceNotSupported | The IMAP4 server does not support NAMESPACE capability.
ImapQuotaNotSupported | The IMAP4 server does not support QUOTA capability required to obtain account and folder quotas.
ImapResponseNotFound | No required data found in the server response.
ImapSortNotSupported | The IMAP4 server does not support SORT capability required to perform sorted search.
ImapUidPlusNotSupported | The IMAP4 server does not support UIDPLUS capability required for the current operation to complete.
ImpersonationWin32Error | Impersonation-related WinAPI function returned an error.
InconsistentResponse | The response data received from the server do not match the data previously received from the server.
InternalError | MailBee internal error. Please contact Afterlogic support team if you encounter this error.
InvalidBase64DataInResponse | The server response is expected to contain Base64 encoded data but this data cannot be decoded from base64.
InvalidBinaryResponse | The response received from the DNS server cannot be parsed.
InvalidDataFormat | The supplied data string or byte block has invalid format.
InvalidDataSyntax | The supplied data string (such as an e-mail address) has invalid syntax.
InvalidDateFormat | The supplied datetime string has invalid format.
InvalidDomainInCache | It's known (from the DNS cache) that the requested domain name does not exist.
InvalidImapEnvelope | The envelope data is corrupted or incorrect. Some properties of Envelope object may contain invalid values.
InvalidOperationException | InvalidOperationException occurred.
InvalidResponse | The response received from the server cannot be parsed.
InvalidResponseItem | A particular element of the response data cannot be parsed.
IOException | IOException occurred.
JobInBatchFailed | One of the jobs in a batch failed and the component is configured to stop processing when this happens.
LicenseError | The license key is invalid or not specified.
LoginWin32Error | Win32 function related to Integrated Windows Authentication returned an error.
MessageDataTooLarge | The message is too large.
NegativeResponse | The server responded with the negative reply.
NoAllowedRecipients | The SMTP server refused the e-mail addresses of all the recipients of the mail message.
NoCredentials | No account name and/or password was supplied for the login.
NoDnsAttemptsLeft | The DNS server is down, and no more retry attempts left.
NoDnsServersAvailable | At least one DNS server IP must be registered in the system in order to start the requested operation.
NoDnsServersSpecified | At least one DNS server must be specified in order to start the requested operation.
NoDomainsForMXLookup | The list of recipient domains is empty.
NoDomainsToSendFor | The list of MX servers of recipient domains is empty.
NoIP4AddressesFound | No IPv4 compatible address has been found for the specified host.
NoMessageInImapResponse | No required mail message data found in the server response.
NoOperationToEnd | Asynchonous method completion with EndXXX method is not possible, since no corresponding BeginXXX method has been called before.
NoRecipients | No recipients are specified for the mail message.
NoSender | No sender is specified for the mail message. No longer used.
NoSmtpOrDnsServersSpecified | At least one DNS or SMTP relay server must be specified in order to send mail.
NoSmtpServersSpecified | At least one SMTP relay server must be specified in order to start the requested operation.
NoSupportedLoginMethods | None of the requested authentication methods is supported by the server.
NotConnected | Not yet connected to the server. Call Connect first.
NotHelloed | Not yet sent initial greeting to the SMTP server. Call Hello first.
NotImpersonated | Not impersonated yet. Call LogonAs(String, String, String) first.
NotLoggedIn | Not yet logged in the user account on the server. Call Login first.
ObjectReadOnly | The object (e.g. collection) is read-only for user code.
OK | No error.
OleDocBuildingError | An OLE2 building error occurred.
OleDocParsingError | An OLE2 parsing error occurred.
OutlookPstParsingError | Outlook .PST file parsing error occurred.
Pop3AuthCommandUnknown | The POP3 server does not support optional AUTH command. SASL authentication will be disabled.
Pop3CapaCommandUnknown | The POP3 server does not support optional CAPA command. Certain POP3 extensions will be disabled.
ProxyAuthMethodsNotAccepted | None of the methods listed by the client to the proxy server are acceptable.
ProxyConnectionDeclined | The proxy server declined to act as a proxy gateway for the given client.
ProxyGssApiAuthFailed | Proxy GSSAPI authentication Failed.
ProxyUserPassAuthFailed | Proxy Username/Password authentication failed.
ResponseTimeout | The operation was aborted because the total response time exceeded the limit set by the application.
SaslAnswerRejected | The server refused the authentication data sent by the client. Authentication failed.
SmimeWin32Error | S/MIME-related Win32 function returned an error.
SocketDisposed | The Socket object was unexpectedly closed.
SocketException | SocketException occurred.
SocketTimeout | The network operation has timed out.
SslNegoAuthException | SSL negotiation failed with AuthenticationException.
SslNegoException | SSL negotiation failed with Exception.
SslNegoIOException | SSL negotiation failed with IOException.
SslNegoNotSupportedException | SSL negotiation failed with NotSupportedException.
SslWin32Error | SSL-related Win32 function returned an error.
StartTlsNotAvailable | The server does not advertize STARTTLS extension.
StreamCannotRead | The supplied Stream object cannot be read.
StreamCannotWrite | The supplied Stream object cannot be written to.
TnefAttributeChecksumInvalid | Invalid checksum on TNEF attribute.
TnefAttributeLevelInvalid | Invalid TNEF attribute level.
TnefCompressedRtfCrc32Failed | Compressed-RTF CRC32 failed.
TnefCompressedRtfDataSizeMismatch | Compressed-RTF data size mismatch.
TnefCompressedRtfHeaderInvalid | Invalid compressed-RTF header.
TnefGuidInvalid | Invalid TNEF Guid.
TnefLevelTypeInvalid | Invalid TNEF level type.
TnefMapiPropTypeInvalid | Invalid MAPI property type of TNEF data.
TnefMapiTypeUnknown | Unknown MAPI type of TNEF data.
TnefMapiValueInvalid | Invalid MAPI property value of TNEF data.
TnefSignatureInvalid | The supplied data does not have a valid TNEF signature.
TnefUnexpectedEndOfStream | Unexpected end of TNEF stream.
TnefUnknownRtfCompressionType | Unknown compression type.
UnauthorizedAccessException | UnauthorizedAccessException occurred.
Unknown | Unknown error.
UnsupportedLoginMethod | The requested authentication method is not supported by the server.
WebException | WebException occurred.
XmlException | XmlException occurred.
Top
Remarks

The MailBee classes implementing LastResult property are:

  • Smtp class (LastResult property)
  • Pop3 class (LastResult property)
  • Imap class (LastResult property)
  • MailMessage class (LastResult property)
  • Attachment class (LastResult property)
  • AttachmentCollection class (LastResult property)

The following table lists all the error codes in ascending order:

Name | Value
OK | 0
LicenseError | 1
Unknown | 2
Busy | 3
NoOperationToEnd | 4
AbortedByUser | 5
InternalError | 6
ExternalError | 7
IllegalInMultiThreadMode | 8
IllegalContext | 9
IllegalRaiseEventsMode | 10
IllegalInCurrentState | 11
ObjectReadOnly | 12
JobInBatchFailed | 13
ArgumentInvalid | 20
ArgumentNull | 21
ArgumentEmpty | 22
ArgumentOutOfRange | 23
IOException | 30
FileNotFoundException | 31
UnauthorizedAccessException | 32
XmlException | 33
WebException | 34
CryptographicException | 35
InvalidOperationException | 36
StreamCannotRead | 40
StreamCannotWrite | 41
EncodingError | 42
InvalidDateFormat | 43
InvalidDataFormat | 44
SocketException | 50
NoIP4AddressesFound | 51
SocketTimeout | 52
AbortedByLocalHost | 53
ConnectionRefused | 54
AbortedByServer | 55
HostNotFound | 56
HostDown | 57
HostUnreachable | 58
ConnectionReset | 59
SocketDisposed | 60
ProxyConnectionDeclined | 70
ProxyAuthMethodsNotAccepted | 71
ProxyUserPassAuthFailed | 72
ProxyGssApiAuthFailed | 73
NotConnected | 100
AlreadyConnected | 101
AlreadySsl | 102
NotLoggedIn | 110
AlreadyLoggedIn | 111
NoCredentials | 112
BadCredentials | 113
UnsupportedLoginMethod | 114
NoSupportedLoginMethods | 115
SaslAnswerRejected | 116
LoginWin32Error | 117
NegativeResponse | 120
InvalidResponse | 121
EmptyResponseLine | 122
InvalidBinaryResponse | 123
InconsistentResponse | 124
InvalidResponseItem | 125
InvalidBase64DataInResponse | 126
StartTlsNotAvailable | 130
SslWin32Error | 140
BadDnsResponseHeader | 200
DnsInvalidQName | 201
DnsQueryMismatch | 210
DnsRecursionRequired | 211
NoDnsServersSpecified | 212
NoDnsAttemptsLeft | 213
NoDnsServersAvailable | 214
DnsFormatErrorReply | 220
DnsFailureReply | 221
DnsNameErrorReply | 222
DnsNotSupportedReply | 223
DnsQueryRefusedReply | 224
DnsUnknownReply | 225
NoSmtpServersSpecified | 300
NotHelloed | 310
EhloNotSupported | 311
NoSender | 312
BadSender | 313
NoRecipients | 314
BadRecipient | 315
NoAllowedRecipients | 316
DataNotAllowed | 317
BadMessageData | 318
BdatRejected | 319
MessageDataTooLarge | 320
Conversion8bitTo7Bit | 330
NoSmtpOrDnsServersSpecified | 400
NoDomainsToSendFor | 401
NoDomainsForMXLookup | 402
EmptyHostNameForDnsQuery | 403
InvalidDomainInCache | 410
DeadDomainSmtpMXesInCache | 411
Pop3AuthCommandUnknown | 500
Pop3CapaCommandUnknown | 501
ImapFolderNotSelected | 600
ImapResponseNotFound | 610
ImapMessageIndexNotFound | 611
NoMessageInImapResponse | 612
InvalidImapEnvelope | 613
ImapUidPlusNotSupported | 620
ImapQuotaNotSupported | 621
ImapIdleNotSupported | 622
ImapSortNotSupported | 623
ImapNamespaceNotSupported | 624
EwsLocalException | 700
EwsRemoteException | 701
EwsFolderNotFound | 710
EwsFolderAlreadyExists | 711
TnefSignatureInvalid | 1000
TnefUnexpectedEndOfStream | 1001
TnefLevelTypeInvalid | 1002
TnefAttributeChecksumInvalid | 1003
TnefAttributeLevelInvalid | 1004
TnefMapiTypeUnknown | 1005
TnefGuidInvalid | 1006
TnefCompressedRtfHeaderInvalid | 1007
TnefCompressedRtfDataSizeMismatch | 1008
TnefCompressedRtfCrc32Failed | 1009
TnefUnknownRtfCompressionType | 1010
CryptoProviderWin32Error | 1100
CertificateStoreWin32Error | 1101
CertificateWin32Error | 1102
SmimeWin32Error | 1103
CertificateValidationError | 1110
CertificateDataInvalid | 1111
NotImpersonated | 1120
ImpersonationWin32Error | 1121
CryptoPrivateKeyInvalid | 1130
OleDocParsingError | 1200
OleDocBuildingError | 1201

See Also

Reference

MailBee Namespace


ErrorCodes Fields

ErrorCodes Fields

The ErrorCodes type exposes the following members.

Fields
Name | Description
AbortedByLocalHost | The software on the local computer has aborted the connection.
AbortedByServer | The remote host has aborted the connection.
AbortedByUser | The current operation was aborted by user.
AlreadyConnected | Already connected to the server.
AlreadyLoggedIn | Already logged in the user account on the server.
AlreadySsl | Already in SSL/TLS mode.
ArgumentEmpty | A null reference (Nothing in Visual Basic) or an empty string/array/collection is not allowed as the argument value.
ArgumentInvalid | The specified argument value is invalid.
ArgumentNull | A null reference (Nothing in Visual Basic) is not allowed as the argument value.
ArgumentOutOfRange | The argument value is out of range.
BadCredentials | Invalid account name and/or password was supplied for the login.
BadDnsResponseHeader | The response from the DNS server contains invalid header.
BadMessageData | The SMTP server rejected the message data sent by the client.
BadRecipient | The SMTP server refused the e-mail address of the mail message recipient.
BadSender | The SMTP server refused the e-mail address of the mail message sender.
BdatRejected | The server responded with a negative reply to BDAT command (although the server claims to support CHUNKING extension).
BdatTimeout | Socket timeout during SMTP BDAT command.
Busy | The component is busy with lengthy or asynchronous operation.
CertificateDataInvalid | Could not restore the certificate from the supplied data.
CertificateStoreWin32Error | Win32 function related to certificate store API returned an error.
CertificateValidationError | Certificate validation failed.
CertificateWin32Error | Certificate-related Win32 function returned an error.
ConnectionRefused | The remote host refused the connection attempt initiated by the client.
ConnectionReset | An existing connection was forcibly closed by the remote host.
Conversion8bitTo7Bit | 7bit-to-8bit conversion of the message data is required.
CryptographicException | CryptographicException occurred.
CryptoPrivateKeyInvalid | Could not decode the private key.
CryptoProviderWin32Error | Win32 function related to a crypto provider API returned an error.
DataNotAllowed | The SMTP server responded with a negative reply to the DATA command.
DeadDomainSmtpMXesInCache | It's known (from the DNS cache) that all DNS MX records for the domain point to dead hosts.
DnsFailureReply | The DNS server replied with "Server failure" status code.
DnsFormatErrorReply | The DNS server replied with "Format Error" status code.
DnsInvalidQName | The specified host name does not conform with Domain Name System rules.
DnsNameErrorReply | The DNS server replied with "Name Error" status code.
DnsNotSupportedReply | The DNS server replied with "Not Implemented" status code.
DnsQueryMismatch | The ID of the DNS server response if different from the ID of the request sent by the client.
DnsQueryRefusedReply | The DNS server replied with "Refused" status code.
DnsRecursionRequired | The DNS server must support recursion in order to complete the request.
DnsUnknownReply | The DNS server replied with unknown status code.
EhloNotSupported | The SMTP server does not support any ESMTP extensions.
EmptyHostNameForDnsQuery | Cannot perform DNS query for an empty host name.
EmptyResponseLine | The response from the server contains just a response terminator but no data.
EncodingError | An exception occurred while performing string conversion.
EwsFolderAlreadyExists | EWS folder already exists.
EwsFolderNotFound | EWS folder not found.
EwsLocalException | Client-side EWS error occurred.
EwsRemoteException | Server-side EWS error occurred.
ExternalError | The application code threw an exception while handling MailBee event.
FileNotFoundException | FileNotFoundException occurred.
HostDown | The specified host is down.
HostNotFound | The specified host was not found.
HostUnreachable | There is no known network route to the specified host.
IllegalContext | The requested operation cannot be performed in the current context.
IllegalInCurrentState | The method cannot run in the current state of the object.
IllegalInMultiThreadMode | The requested operation cannot be performed in multi-thread mode.
IllegalRaiseEventsMode | Wait method cannot be used if RaiseEventsViaMessageLoop is true.
ImapFolderNotSelected | This command requires a folder be selected on the IMAP4 server. Call SelectFolder(String) or ExamineFolder(String) first.
ImapIdleNotSupported | The IMAP4 server does not support IDLE capability required to go into IDLE mode.
ImapMessageIndexNotFound | The message with the specified index does not exist on the server.
ImapNamespaceNotSupported | The IMAP4 server does not support NAMESPACE capability.
ImapQuotaNotSupported | The IMAP4 server does not support QUOTA capability required to obtain account and folder quotas.
ImapResponseNotFound | No required data found in the server response.
ImapSortNotSupported | The IMAP4 server does not support SORT capability required to perform sorted search.
ImapUidPlusNotSupported | The IMAP4 server does not support UIDPLUS capability required for the current operation to complete.
ImpersonationWin32Error | Impersonation-related WinAPI function returned an error.
InconsistentResponse | The response data received from the server do not match the data previously received from the server.
InternalError | MailBee internal error. Please contact Afterlogic support team if you encounter this error.
InvalidBase64DataInResponse | The server response is expected to contain Base64 encoded data but this data cannot be decoded from base64.
InvalidBinaryResponse | The response received from the DNS server cannot be parsed.
InvalidDataFormat | The supplied data string or byte block has invalid format.
InvalidDataSyntax | The supplied data string (such as an e-mail address) has invalid syntax.
InvalidDateFormat | The supplied datetime string has invalid format.
InvalidDomainInCache | It's known (from the DNS cache) that the requested domain name does not exist.
InvalidImapEnvelope | The envelope data is corrupted or incorrect. Some properties of Envelope object may contain invalid values.
InvalidOperationException | InvalidOperationException occurred.
InvalidResponse | The response received from the server cannot be parsed.
InvalidResponseItem | A particular element of the response data cannot be parsed.
IOException | IOException occurred.
JobInBatchFailed | One of the jobs in a batch failed and the component is configured to stop processing when this happens.
LicenseError | The license key is invalid or not specified.
LoginWin32Error | Win32 function related to Integrated Windows Authentication returned an error.
MessageDataTooLarge | The message is too large.
NegativeResponse | The server responded with the negative reply.
NoAllowedRecipients | The SMTP server refused the e-mail addresses of all the recipients of the mail message.
NoCredentials | No account name and/or password was supplied for the login.
NoDnsAttemptsLeft | The DNS server is down, and no more retry attempts left.
NoDnsServersAvailable | At least one DNS server IP must be registered in the system in order to start the requested operation.
NoDnsServersSpecified | At least one DNS server must be specified in order to start the requested operation.
NoDomainsForMXLookup | The list of recipient domains is empty.
NoDomainsToSendFor | The list of MX servers of recipient domains is empty.
NoIP4AddressesFound | No IPv4 compatible address has been found for the specified host.
NoMessageInImapResponse | No required mail message data found in the server response.
NoOperationToEnd | Asynchonous method completion with EndXXX method is not possible, since no corresponding BeginXXX method has been called before.
NoRecipients | No recipients are specified for the mail message.
NoSender | No sender is specified for the mail message. No longer used.
NoSmtpOrDnsServersSpecified | At least one DNS or SMTP relay server must be specified in order to send mail.
NoSmtpServersSpecified | At least one SMTP relay server must be specified in order to start the requested operation.
NoSupportedLoginMethods | None of the requested authentication methods is supported by the server.
NotConnected | Not yet connected to the server. Call Connect first.
NotHelloed | Not yet sent initial greeting to the SMTP server. Call Hello first.
NotImpersonated | Not impersonated yet. Call LogonAs(String, String, String) first.
NotLoggedIn | Not yet logged in the user account on the server. Call Login first.
ObjectReadOnly | The object (e.g. collection) is read-only for user code.
OK | No error.
OleDocBuildingError | An OLE2 building error occurred.
OleDocParsingError | An OLE2 parsing error occurred.
OutlookPstParsingError | Outlook .PST file parsing error occurred.
Pop3AuthCommandUnknown | The POP3 server does not support optional AUTH command. SASL authentication will be disabled.
Pop3CapaCommandUnknown | The POP3 server does not support optional CAPA command. Certain POP3 extensions will be disabled.
ProxyAuthMethodsNotAccepted | None of the methods listed by the client to the proxy server are acceptable.
ProxyConnectionDeclined | The proxy server declined to act as a proxy gateway for the given client.
ProxyGssApiAuthFailed | Proxy GSSAPI authentication Failed.
ProxyUserPassAuthFailed | Proxy Username/Password authentication failed.
ResponseTimeout | The operation was aborted because the total response time exceeded the limit set by the application.
SaslAnswerRejected | The server refused the authentication data sent by the client. Authentication failed.
SmimeWin32Error | S/MIME-related Win32 function returned an error.
SocketDisposed | The Socket object was unexpectedly closed.
SocketException | SocketException occurred.
SocketTimeout | The network operation has timed out.
SslNegoAuthException | SSL negotiation failed with AuthenticationException.
SslNegoException | SSL negotiation failed with Exception.
SslNegoIOException | SSL negotiation failed with IOException.
SslNegoNotSupportedException | SSL negotiation failed with NotSupportedException.
SslWin32Error | SSL-related Win32 function returned an error.
StartTlsNotAvailable | The server does not advertize STARTTLS extension.
StreamCannotRead | The supplied Stream object cannot be read.
StreamCannotWrite | The supplied Stream object cannot be written to.
TnefAttributeChecksumInvalid | Invalid checksum on TNEF attribute.
TnefAttributeLevelInvalid | Invalid TNEF attribute level.
TnefCompressedRtfCrc32Failed | Compressed-RTF CRC32 failed.
TnefCompressedRtfDataSizeMismatch | Compressed-RTF data size mismatch.
TnefCompressedRtfHeaderInvalid | Invalid compressed-RTF header.
TnefGuidInvalid | Invalid TNEF Guid.
TnefLevelTypeInvalid | Invalid TNEF level type.
TnefMapiPropTypeInvalid | Invalid MAPI property type of TNEF data.
TnefMapiTypeUnknown | Unknown MAPI type of TNEF data.
TnefMapiValueInvalid | Invalid MAPI property value of TNEF data.
TnefSignatureInvalid | The supplied data does not have a valid TNEF signature.
TnefUnexpectedEndOfStream | Unexpected end of TNEF stream.
TnefUnknownRtfCompressionType | Unknown compression type.
UnauthorizedAccessException | UnauthorizedAccessException occurred.
Unknown | Unknown error.
UnsupportedLoginMethod | The requested authentication method is not supported by the server.
WebException | WebException occurred.
XmlException | XmlException occurred.
Top
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.AbortedByLocalHost Field

ErrorCodesAbortedByLocalHost Field
The software on the local computer has aborted the connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int AbortedByLocalHost
Public Const AbortedByLocalHost As Integer

Field Value

Type: Int32
Remarks
This error indicates some software (such as firewall, anti-virus, etc), operating on the same machine where MailBee is running, aborted the connection.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.AbortedByServer Field

ErrorCodesAbortedByServer Field
The remote host has aborted the connection.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int AbortedByServer
Public Const AbortedByServer As Integer

Field Value

Type: Int32
Remarks
This error indicates zero-length data packet has been received from the server at unexpected time.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.AbortedByUser Field

ErrorCodesAbortedByUser Field
The current operation was aborted by user.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int AbortedByUser
Public Const AbortedByUser As Integer

Field Value

Type: Int32
Remarks
This error indicates Abort method was called.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.AlreadyConnected Field

ErrorCodesAlreadyConnected Field
Already connected to the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int AlreadyConnected
Public Const AlreadyConnected As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.AlreadyLoggedIn Field

ErrorCodesAlreadyLoggedIn Field
Already logged in the user account on the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int AlreadyLoggedIn
Public Const AlreadyLoggedIn As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.AlreadySsl Field

ErrorCodesAlreadySsl Field
Already in SSL/TLS mode.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int AlreadySsl
Public Const AlreadySsl As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ArgumentEmpty Field

ErrorCodesArgumentEmpty Field
A null reference (Nothing in Visual Basic) or an empty string/array/collection is not allowed as the argument value.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ArgumentEmpty
Public Const ArgumentEmpty As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ArgumentInvalid Field

ErrorCodesArgumentInvalid Field
The specified argument value is invalid.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ArgumentInvalid
Public Const ArgumentInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ArgumentNull Field

ErrorCodesArgumentNull Field
A null reference (Nothing in Visual Basic) is not allowed as the argument value.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ArgumentNull
Public Const ArgumentNull As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ArgumentOutOfRange Field

ErrorCodesArgumentOutOfRange Field
The argument value is out of range.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ArgumentOutOfRange
Public Const ArgumentOutOfRange As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BadCredentials Field

ErrorCodesBadCredentials Field
Invalid account name and/or password was supplied for the login.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BadCredentials
Public Const BadCredentials As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BadDnsResponseHeader Field

ErrorCodesBadDnsResponseHeader Field
The response from the DNS server contains invalid header.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BadDnsResponseHeader
Public Const BadDnsResponseHeader As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BadMessageData Field

ErrorCodesBadMessageData Field
The SMTP server rejected the message data sent by the client.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BadMessageData
Public Const BadMessageData As Integer

Field Value

Type: Int32
Remarks
The most common reasons of this error:
  • The message is too large
  • The server thinks the message contains SPAM or virus
  • The message contains invalid headers
  • The message sender and/or recipients specified in the message header differ from the actual sender/recipients, and the server does not allow this (the developer may consider adding Resent-From: header to the message specifying the actual sender e-mail address as the header value)
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BadRecipient Field

ErrorCodesBadRecipient Field
The SMTP server refused the e-mail address of the mail message recipient.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BadRecipient
Public Const BadRecipient As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BadSender Field

ErrorCodesBadSender Field
The SMTP server refused the e-mail address of the mail message sender.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BadSender
Public Const BadSender As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BdatRejected Field

ErrorCodesBdatRejected Field
The server responded with a negative reply to BDAT command (although the server claims to support CHUNKING extension).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BdatRejected
Public Const BdatRejected As Integer

Field Value

Type: Int32
The developer may consider to disable CHUNKING by setting NoChunking flag in SmtpOptions value.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.BdatTimeout Field

ErrorCodesBdatTimeout Field
Socket timeout during SMTP BDAT command.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int BdatTimeout
Public Const BdatTimeout As Integer

Field Value

Type: Int32
Remarks
If network timeout occurs during BDAT command, this may indicate that SMTP CHUNKING is not working correctly with this server. Try setting [!:ExtendedSmtpOptions.NoChunking] flag in [!:SmtpServer.SmtpOptions] property of the [!:SmtpServer] object which represents the SMTP server you're sending with.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.Busy Field

ErrorCodesBusy Field
The component is busy with lengthy or asynchronous operation.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int Busy
Public Const Busy As Integer

Field Value

Type: Int32
Remarks
For instance, this error may occur if asynchronous operation started with BeginXXX method was not completed with EndXXX method call.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CertificateDataInvalid Field

ErrorCodesCertificateDataInvalid Field
Could not restore the certificate from the supplied data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CertificateDataInvalid
Public Const CertificateDataInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CertificateStoreWin32Error Field

ErrorCodesCertificateStoreWin32Error Field
Win32 function related to certificate store API returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CertificateStoreWin32Error
Public Const CertificateStoreWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CertificateValidationError Field

ErrorCodesCertificateValidationError Field
Certificate validation failed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CertificateValidationError
Public Const CertificateValidationError As Integer

Field Value

Type: Int32
Remarks
The developer can use Validate method to find out which properties of the certificate failed.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CertificateWin32Error Field

ErrorCodesCertificateWin32Error Field
Certificate-related Win32 function returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CertificateWin32Error
Public Const CertificateWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ConnectionRefused Field

ErrorCodesConnectionRefused Field
The remote host refused the connection attempt initiated by the client.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ConnectionRefused
Public Const ConnectionRefused As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ConnectionReset Field

ErrorCodesConnectionReset Field
An existing connection was forcibly closed by the remote host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ConnectionReset
Public Const ConnectionReset As Integer

Field Value

Type: Int32
Remarks
This error indicates socket error WSAECONNRESET (10054) has occurred.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.Conversion8bitTo7Bit Field

ErrorCodesConversion8bitTo7Bit Field
7bit-to-8bit conversion of the message data is required.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int Conversion8bitTo7Bit
Public Const Conversion8bitTo7Bit As Integer

Field Value

Type: Int32
Remarks
Occurs if the following conditions are met:
  • The message contains 8bit data
  • The server does not support transmitting 8bit data
  • MailBee is told not to ignore 7bit-to-8bit issue (Conversion8BitTo7bit value is not DoNothing)
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CryptographicException Field

ErrorCodesCryptographicException Field
CryptographicException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CryptographicException
Public Const CryptographicException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CryptoPrivateKeyInvalid Field

ErrorCodesCryptoPrivateKeyInvalid Field
Could not decode the private key.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CryptoPrivateKeyInvalid
Public Const CryptoPrivateKeyInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.CryptoProviderWin32Error Field

ErrorCodesCryptoProviderWin32Error Field
Win32 function related to a crypto provider API returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int CryptoProviderWin32Error
Public Const CryptoProviderWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DataNotAllowed Field

ErrorCodesDataNotAllowed Field
The SMTP server responded with a negative reply to the DATA command.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DataNotAllowed
Public Const DataNotAllowed As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DeadDomainSmtpMXesInCache Field

ErrorCodesDeadDomainSmtpMXesInCache Field
It's known (from the DNS cache) that all DNS MX records for the domain point to dead hosts.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DeadDomainSmtpMXesInCache
Public Const DeadDomainSmtpMXesInCache As Integer

Field Value

Type: Int32
Remarks
It does not make sense to connect to any of the SMTP MX server of this domain since the previous attempt to do so failed and this fact was recorded in the DNS cache. The developer can use Clear and Timeout members of DnsCache class to affect this behavior.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsFailureReply Field

ErrorCodesDnsFailureReply Field
The DNS server replied with "Server failure" status code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsFailureReply
Public Const DnsFailureReply As Integer

Field Value

Type: Int32
Remarks
The name server was unable to process this query due to a problem with the name server.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsFormatErrorReply Field

ErrorCodesDnsFormatErrorReply Field
The DNS server replied with "Format Error" status code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsFormatErrorReply
Public Const DnsFormatErrorReply As Integer

Field Value

Type: Int32
Remarks
The name server was unable to interpret the query.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsInvalidQName Field

ErrorCodesDnsInvalidQName Field
The specified host name does not conform with Domain Name System rules.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsInvalidQName
Public Const DnsInvalidQName As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsNameErrorReply Field

ErrorCodesDnsNameErrorReply Field
The DNS server replied with "Name Error" status code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsNameErrorReply
Public Const DnsNameErrorReply As Integer

Field Value

Type: Int32
Remarks
Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsNotSupportedReply Field

ErrorCodesDnsNotSupportedReply Field
The DNS server replied with "Not Implemented" status code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsNotSupportedReply
Public Const DnsNotSupportedReply As Integer

Field Value

Type: Int32
Remarks
The name server does not support the requested kind of query.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsQueryMismatch Field

ErrorCodesDnsQueryMismatch Field
The ID of the DNS server response if different from the ID of the request sent by the client.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsQueryMismatch
Public Const DnsQueryMismatch As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsQueryRefusedReply Field

ErrorCodesDnsQueryRefusedReply Field
The DNS server replied with "Refused" status code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsQueryRefusedReply
Public Const DnsQueryRefusedReply As Integer

Field Value

Type: Int32
Remarks
The name server refuses to perform the specified operation for policy reasons. For example, a name server may not wish to provide the information to the particular requester, or a name server may not wish to perform a particular operation (e.g., zone transfer) for particular data.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsRecursionRequired Field

ErrorCodesDnsRecursionRequired Field
The DNS server must support recursion in order to complete the request.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsRecursionRequired
Public Const DnsRecursionRequired As Integer

Field Value

Type: Int32
Remarks
If this error occurs, the developer should try another DNS server.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.DnsUnknownReply Field

ErrorCodesDnsUnknownReply Field
The DNS server replied with unknown status code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int DnsUnknownReply
Public Const DnsUnknownReply As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EhloNotSupported Field

ErrorCodesEhloNotSupported Field
The SMTP server does not support any ESMTP extensions.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EhloNotSupported
Public Const EhloNotSupported As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EmptyHostNameForDnsQuery Field

ErrorCodesEmptyHostNameForDnsQuery Field
Cannot perform DNS query for an empty host name.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EmptyHostNameForDnsQuery
Public Const EmptyHostNameForDnsQuery As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EmptyResponseLine Field

ErrorCodesEmptyResponseLine Field
The response from the server contains just a response terminator but no data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EmptyResponseLine
Public Const EmptyResponseLine As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EncodingError Field

ErrorCodesEncodingError Field
An exception occurred while performing string conversion.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EncodingError
Public Const EncodingError As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EwsFolderAlreadyExists Field

ErrorCodesEwsFolderAlreadyExists Field
EWS folder already exists.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EwsFolderAlreadyExists
Public Const EwsFolderAlreadyExists As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EwsFolderNotFound Field

ErrorCodesEwsFolderNotFound Field
EWS folder not found.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EwsFolderNotFound
Public Const EwsFolderNotFound As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EwsLocalException Field

ErrorCodesEwsLocalException Field
Client-side EWS error occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EwsLocalException
Public Const EwsLocalException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.EwsRemoteException Field

ErrorCodesEwsRemoteException Field
Server-side EWS error occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int EwsRemoteException
Public Const EwsRemoteException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ExternalError Field

ErrorCodesExternalError Field
The application code threw an exception while handling MailBee event.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ExternalError
Public Const ExternalError As Integer

Field Value

Type: Int32
Remarks
This error code indicates the application is subscribed to a certain MailBee event, MailBee raises this event, and the application code responsible for handling this event throws an exception. The developer should fix the event handling code in order to get rid of this error.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.FileNotFoundException Field

ErrorCodesFileNotFoundException Field
FileNotFoundException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int FileNotFoundException
Public Const FileNotFoundException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.HostDown Field

ErrorCodesHostDown Field
The specified host is down.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int HostDown
Public Const HostDown As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.HostNotFound Field

ErrorCodesHostNotFound Field
The specified host was not found.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int HostNotFound
Public Const HostNotFound As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.HostUnreachable Field

ErrorCodesHostUnreachable Field
There is no known network route to the specified host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int HostUnreachable
Public Const HostUnreachable As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.IllegalContext Field

ErrorCodesIllegalContext Field
The requested operation cannot be performed in the current context.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int IllegalContext
Public Const IllegalContext As Integer

Field Value

Type: Int32
Remarks
For instance, it's not possible to get the SMTP server response using GetServerResponse method when the component is performing MX lookup query against the DNS server.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.IllegalInCurrentState Field

ErrorCodesIllegalInCurrentState Field
The method cannot run in the current state of the object.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int IllegalInCurrentState
Public Const IllegalInCurrentState As Integer

Field Value

Type: Int32
Remarks
For instance, it's not possible to append a partial message (i.e. call AppendPartialMessage(MailMessage)) to the message which is not partial.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.IllegalInMultiThreadMode Field

ErrorCodesIllegalInMultiThreadMode Field
The requested operation cannot be performed in multi-thread mode.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int IllegalInMultiThreadMode
Public Const IllegalInMultiThreadMode As Integer

Field Value

Type: Int32
Remarks
For instance, GetServerResponse call is ambiguous in multi-thread mode, since it's not possible to determine for which SMTP connection the last response must be returned if there are multiple SMTP connections being opened. If you encounter this error, use Smtp component events to keep track of SMTP sessions.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.IllegalRaiseEventsMode Field

ErrorCodesIllegalRaiseEventsMode Field
Wait method cannot be used if RaiseEventsViaMessageLoop is true.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int IllegalRaiseEventsMode
Public Const IllegalRaiseEventsMode As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapFolderNotSelected Field

ErrorCodesImapFolderNotSelected Field
This command requires a folder be selected on the IMAP4 server. Call SelectFolder(String) or ExamineFolder(String) first.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapFolderNotSelected
Public Const ImapFolderNotSelected As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapIdleNotSupported Field

ErrorCodesImapIdleNotSupported Field
The IMAP4 server does not support IDLE capability required to go into IDLE mode.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapIdleNotSupported
Public Const ImapIdleNotSupported As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapMessageIndexNotFound Field

ErrorCodesImapMessageIndexNotFound Field
The message with the specified index does not exist on the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapMessageIndexNotFound
Public Const ImapMessageIndexNotFound As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapNamespaceNotSupported Field

ErrorCodesImapNamespaceNotSupported Field
The IMAP4 server does not support NAMESPACE capability.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapNamespaceNotSupported
Public Const ImapNamespaceNotSupported As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapQuotaNotSupported Field

ErrorCodesImapQuotaNotSupported Field
The IMAP4 server does not support QUOTA capability required to obtain account and folder quotas.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapQuotaNotSupported
Public Const ImapQuotaNotSupported As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapResponseNotFound Field

ErrorCodesImapResponseNotFound Field
No required data found in the server response.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapResponseNotFound
Public Const ImapResponseNotFound As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapSortNotSupported Field

ErrorCodesImapSortNotSupported Field
The IMAP4 server does not support SORT capability required to perform sorted search.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapSortNotSupported
Public Const ImapSortNotSupported As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImapUidPlusNotSupported Field

ErrorCodesImapUidPlusNotSupported Field
The IMAP4 server does not support UIDPLUS capability required for the current operation to complete.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImapUidPlusNotSupported
Public Const ImapUidPlusNotSupported As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ImpersonationWin32Error Field

ErrorCodesImpersonationWin32Error Field
Impersonation-related WinAPI function returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ImpersonationWin32Error
Public Const ImpersonationWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InconsistentResponse Field

ErrorCodesInconsistentResponse Field
The response data received from the server do not match the data previously received from the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InconsistentResponse
Public Const InconsistentResponse As Integer

Field Value

Type: Int32
Remarks
For instance, if the server reports the mailbox contains x messages, but the following response contains the details on y messages (so the server contradicts to itself), this error occurs.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InternalError Field

ErrorCodesInternalError Field
MailBee internal error. Please contact Afterlogic support team if you encounter this error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InternalError
Public Const InternalError As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidBase64DataInResponse Field

ErrorCodesInvalidBase64DataInResponse Field
The server response is expected to contain Base64 encoded data but this data cannot be decoded from base64.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidBase64DataInResponse
Public Const InvalidBase64DataInResponse As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidBinaryResponse Field

ErrorCodesInvalidBinaryResponse Field
The response received from the DNS server cannot be parsed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidBinaryResponse
Public Const InvalidBinaryResponse As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidDataFormat Field

ErrorCodesInvalidDataFormat Field
The supplied data string or byte block has invalid format.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidDataFormat
Public Const InvalidDataFormat As Integer

Field Value

Type: Int32
Remarks
For instance, this error may occur if the application tries to load an Outlook .MSG file like if it was .EML MIME file (using MailMessage class instead of MsgConvert class).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidDataSyntax Field

ErrorCodesInvalidDataSyntax Field
The supplied data string (such as an e-mail address) has invalid syntax.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidDataSyntax
Public Const InvalidDataSyntax As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidDateFormat Field

ErrorCodesInvalidDateFormat Field
The supplied datetime string has invalid format.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidDateFormat
Public Const InvalidDateFormat As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidDomainInCache Field

ErrorCodesInvalidDomainInCache Field
It's known (from the DNS cache) that the requested domain name does not exist.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidDomainInCache
Public Const InvalidDomainInCache As Integer

Field Value

Type: Int32
Remarks
It does not make sense to make DNS MX query regarding the domain name since the previous attempt to do so produced negative response from the DNS server and this fact was recorded in the DNS cache. The developer can use Clear and Timeout members of DnsCache class to affect this behavior.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidImapEnvelope Field

ErrorCodesInvalidImapEnvelope Field
The envelope data is corrupted or incorrect. Some properties of Envelope object may contain invalid values.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidImapEnvelope
Public Const InvalidImapEnvelope As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidOperationException Field

ErrorCodesInvalidOperationException Field
InvalidOperationException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidOperationException
Public Const InvalidOperationException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidResponse Field

ErrorCodesInvalidResponse Field
The response received from the server cannot be parsed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidResponse
Public Const InvalidResponse As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.InvalidResponseItem Field

ErrorCodesInvalidResponseItem Field
A particular element of the response data cannot be parsed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int InvalidResponseItem
Public Const InvalidResponseItem As Integer

Field Value

Type: Int32
Remarks
For instance, if the server response should contain a number but this number cannot be parsed, this error occurs.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.IOException Field

ErrorCodesIOException Field
IOException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int IOException
Public Const IOException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.JobInBatchFailed Field

ErrorCodesJobInBatchFailed Field
One of the jobs in a batch failed and the component is configured to stop processing when this happens.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int JobInBatchFailed
Public Const JobInBatchFailed As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.LicenseError Field

ErrorCodesLicenseError Field
The license key is invalid or not specified.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int LicenseError
Public Const LicenseError As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.LoginWin32Error Field

ErrorCodesLoginWin32Error Field
Win32 function related to Integrated Windows Authentication returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int LoginWin32Error
Public Const LoginWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.MessageDataTooLarge Field

ErrorCodesMessageDataTooLarge Field
The message is too large.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int MessageDataTooLarge
Public Const MessageDataTooLarge As Integer

Field Value

Type: Int32
Remarks
This error occurs when the server supports SIZE extension, and the fact of exceeding the maximum allowed message size can be determined before actual submission of the message to the server.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NegativeResponse Field

ErrorCodesNegativeResponse Field
The server responded with the negative reply.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NegativeResponse
Public Const NegativeResponse As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoAllowedRecipients Field

ErrorCodesNoAllowedRecipients Field
The SMTP server refused the e-mail addresses of all the recipients of the mail message.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoAllowedRecipients
Public Const NoAllowedRecipients As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoCredentials Field

ErrorCodesNoCredentials Field
No account name and/or password was supplied for the login.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoCredentials
Public Const NoCredentials As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoDnsAttemptsLeft Field

ErrorCodesNoDnsAttemptsLeft Field
The DNS server is down, and no more retry attempts left.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoDnsAttemptsLeft
Public Const NoDnsAttemptsLeft As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoDnsServersAvailable Field

ErrorCodesNoDnsServersAvailable Field
At least one DNS server IP must be registered in the system in order to start the requested operation.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoDnsServersAvailable
Public Const NoDnsServersAvailable As Integer

Field Value

Type: Int32
Remarks
For instance, QuickSend(MailMessage) method needs to perform MX queries to DNS servers. If no DNS server is registered in the system, this method can't do its job. In this case, the developer can manually specify DNS or SMTP server and use Send method to send out mails.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoDnsServersSpecified Field

ErrorCodesNoDnsServersSpecified Field
At least one DNS server must be specified in order to start the requested operation.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoDnsServersSpecified
Public Const NoDnsServersSpecified As Integer

Field Value

Type: Int32
Remarks
For instance, DnsServers collection must contain at least one DNS server in order to make direct send operation possible.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoDomainsForMXLookup Field

ErrorCodesNoDomainsForMXLookup Field
The list of recipient domains is empty.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoDomainsForMXLookup
Public Const NoDomainsForMXLookup As Integer

Field Value

Type: Int32
Remarks
Please contact AfterLogic support team if you encounter this error.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoDomainsToSendFor Field

ErrorCodesNoDomainsToSendFor Field
The list of MX servers of recipient domains is empty.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoDomainsToSendFor
Public Const NoDomainsToSendFor As Integer

Field Value

Type: Int32
Remarks
Please contact AfterLogic support team if you encounter this error.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoIP4AddressesFound Field

ErrorCodesNoIP4AddressesFound Field
No IPv4 compatible address has been found for the specified host.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoIP4AddressesFound
Public Const NoIP4AddressesFound As Integer

Field Value

Type: Int32
Remarks
Usually, this error indicates the host is IPv6-only.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoMessageInImapResponse Field

ErrorCodesNoMessageInImapResponse Field
No required mail message data found in the server response.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoMessageInImapResponse
Public Const NoMessageInImapResponse As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoOperationToEnd Field

ErrorCodesNoOperationToEnd Field
Asynchonous method completion with EndXXX method is not possible, since no corresponding BeginXXX method has been called before.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoOperationToEnd
Public Const NoOperationToEnd As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoRecipients Field

ErrorCodesNoRecipients Field
No recipients are specified for the mail message.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoRecipients
Public Const NoRecipients As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoSender Field

ErrorCodesNoSender Field
No sender is specified for the mail message. No longer used.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoSender
Public Const NoSender As Integer

Field Value

Type: Int32
Remarks
Since MailBee.NET Objects v11.2, this error never happens as it's now allowed to send with empty MAIL FROM (no sender).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoSmtpOrDnsServersSpecified Field

ErrorCodesNoSmtpOrDnsServersSpecified Field
At least one DNS or SMTP relay server must be specified in order to send mail.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoSmtpOrDnsServersSpecified
Public Const NoSmtpOrDnsServersSpecified As Integer

Field Value

Type: Int32
Remarks
Either SmtpServers or DnsServers collection must contain at least one SMTP relay or DNS server in order to send mail.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoSmtpServersSpecified Field

ErrorCodesNoSmtpServersSpecified Field
At least one SMTP relay server must be specified in order to start the requested operation.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoSmtpServersSpecified
Public Const NoSmtpServersSpecified As Integer

Field Value

Type: Int32
Remarks
For instance, SmtpServers collection must contain at least one SMTP relay server in order to connect or send mail to an SMTP relay server.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NoSupportedLoginMethods Field

ErrorCodesNoSupportedLoginMethods Field
None of the requested authentication methods is supported by the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NoSupportedLoginMethods
Public Const NoSupportedLoginMethods As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NotConnected Field

ErrorCodesNotConnected Field
Not yet connected to the server. Call Connect first.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NotConnected
Public Const NotConnected As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NotHelloed Field

ErrorCodesNotHelloed Field
Not yet sent initial greeting to the SMTP server. Call Hello first.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NotHelloed
Public Const NotHelloed As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NotImpersonated Field

ErrorCodesNotImpersonated Field
Not impersonated yet. Call LogonAs(String, String, String) first.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NotImpersonated
Public Const NotImpersonated As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.NotLoggedIn Field

ErrorCodesNotLoggedIn Field
Not yet logged in the user account on the server. Call Login first.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int NotLoggedIn
Public Const NotLoggedIn As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ObjectReadOnly Field

ErrorCodesObjectReadOnly Field
The object (e.g. collection) is read-only for user code.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ObjectReadOnly
Public Const ObjectReadOnly As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.OK Field

ErrorCodesOK Field
No error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int OK
Public Const OK As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.OleDocBuildingError Field

ErrorCodesOleDocBuildingError Field
An OLE2 building error occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int OleDocBuildingError
Public Const OleDocBuildingError As Integer

Field Value

Type: Int32
Remarks
This error occurs when it's not possible to build an OLE2 document like Outlook .MSG file.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.OleDocParsingError Field

ErrorCodesOleDocParsingError Field
An OLE2 parsing error occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int OleDocParsingError
Public Const OleDocParsingError As Integer

Field Value

Type: Int32
Remarks
This error occurs when it's not possible to parse an OLE2 document like Outlook .MSG file.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.OutlookPstParsingError Field

ErrorCodesOutlookPstParsingError Field
Outlook .PST file parsing error occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int OutlookPstParsingError
Public Const OutlookPstParsingError As Integer

Field Value

Type: Int32
Remarks
This error occurs when it's not possible to parse data from Outlook .PST file. For instance, "Unrecognised PST File version: 36." error means that you're trying to open .OST file produced by Outlook 2013 or higher (that format is not supported).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.Pop3AuthCommandUnknown Field

ErrorCodesPop3AuthCommandUnknown Field
The POP3 server does not support optional AUTH command. SASL authentication will be disabled.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int Pop3AuthCommandUnknown
Public Const Pop3AuthCommandUnknown As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.Pop3CapaCommandUnknown Field

ErrorCodesPop3CapaCommandUnknown Field
The POP3 server does not support optional CAPA command. Certain POP3 extensions will be disabled.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int Pop3CapaCommandUnknown
Public Const Pop3CapaCommandUnknown As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ProxyAuthMethodsNotAccepted Field

ErrorCodesProxyAuthMethodsNotAccepted Field
None of the methods listed by the client to the proxy server are acceptable.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ProxyAuthMethodsNotAccepted
Public Const ProxyAuthMethodsNotAccepted As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ProxyConnectionDeclined Field

ErrorCodesProxyConnectionDeclined Field
The proxy server declined to act as a proxy gateway for the given client.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ProxyConnectionDeclined
Public Const ProxyConnectionDeclined As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ProxyGssApiAuthFailed Field

ErrorCodesProxyGssApiAuthFailed Field
Proxy GSSAPI authentication Failed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ProxyGssApiAuthFailed
Public Const ProxyGssApiAuthFailed As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ProxyUserPassAuthFailed Field

ErrorCodesProxyUserPassAuthFailed Field
Proxy Username/Password authentication failed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ProxyUserPassAuthFailed
Public Const ProxyUserPassAuthFailed As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.ResponseTimeout Field

ErrorCodesResponseTimeout Field
The operation was aborted because the total response time exceeded the limit set by the application.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int ResponseTimeout
Public Const ResponseTimeout As Integer

Field Value

Type: Int32
Remarks
This error may occur if the server returns data very slowly. This is different from regular timeout errors which occur when the server never responds during certain time interval. For instance, if the regular timeout is 30 seconds, this means the server may return 1 byte of data each 25 seconds and this will never cause MailBee to claim timeout (even if the overall operation takes very long).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SaslAnswerRejected Field

ErrorCodesSaslAnswerRejected Field
The server refused the authentication data sent by the client. Authentication failed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SaslAnswerRejected
Public Const SaslAnswerRejected As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SmimeWin32Error Field

ErrorCodesSmimeWin32Error Field
S/MIME-related Win32 function returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SmimeWin32Error
Public Const SmimeWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SocketDisposed Field

ErrorCodesSocketDisposed Field
The Socket object was unexpectedly closed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SocketDisposed
Public Const SocketDisposed As Integer

Field Value

Type: Int32
Remarks
This error may occur after the application closes the connection directly, not using Disconnect method of a mailer component. For example, calling mailer.GetSocket().Close() (mailer is an instance of Smtp, Pop3, or Imap class).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SocketException Field

ErrorCodesSocketException Field
SocketException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SocketException
Public Const SocketException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SocketTimeout Field

ErrorCodesSocketTimeout Field
The network operation has timed out.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SocketTimeout
Public Const SocketTimeout As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SslNegoAuthException Field

ErrorCodesSslNegoAuthException Field
SSL negotiation failed with AuthenticationException.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SslNegoAuthException
Public Const SslNegoAuthException As Integer

Field Value

Type: Int32
Remarks
For instance, the selected security protocol is not supported by the server. Consider selecting another protocol (e.g. [!:SecurityProtocol.Tls12] or [!:SecurityProtocol.TlsAuto]).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SslNegoException Field

ErrorCodesSslNegoException Field
SSL negotiation failed with Exception.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SslNegoException
Public Const SslNegoException As Integer

Field Value

Type: Int32
Remarks
This usually occurs with UWP apps only (the underlying code tends to throw exceptions of common Exception type.
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SslNegoIOException Field

ErrorCodesSslNegoIOException Field
SSL negotiation failed with IOException.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SslNegoIOException
Public Const SslNegoIOException As Integer

Field Value

Type: Int32
Remarks
For instance, the selected security protocol is not supported by the server. Consider selecting another protocol (for instance, [!:SecurityProtocol.Tls12] if the server does support automatic protocol selection).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SslNegoNotSupportedException Field

ErrorCodesSslNegoNotSupportedException Field
SSL negotiation failed with NotSupportedException.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SslNegoNotSupportedException
Public Const SslNegoNotSupportedException As Integer

Field Value

Type: Int32
Remarks
For instance, the selected security protocol is not supported by the current platform. Consider selecting another protocol (e.g. [!:SecurityProtocol.Tls12] or [!:SecurityProtocol.TlsAuto]).
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.SslWin32Error Field

ErrorCodesSslWin32Error Field
SSL-related Win32 function returned an error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int SslWin32Error
Public Const SslWin32Error As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.StartTlsNotAvailable Field

ErrorCodesStartTlsNotAvailable Field
The server does not advertize STARTTLS extension.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int StartTlsNotAvailable
Public Const StartTlsNotAvailable As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.StreamCannotRead Field

ErrorCodesStreamCannotRead Field
The supplied Stream object cannot be read.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int StreamCannotRead
Public Const StreamCannotRead As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.StreamCannotWrite Field

ErrorCodesStreamCannotWrite Field
The supplied Stream object cannot be written to.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int StreamCannotWrite
Public Const StreamCannotWrite As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefAttributeChecksumInvalid Field

ErrorCodesTnefAttributeChecksumInvalid Field
Invalid checksum on TNEF attribute.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefAttributeChecksumInvalid
Public Const TnefAttributeChecksumInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefAttributeLevelInvalid Field

ErrorCodesTnefAttributeLevelInvalid Field
Invalid TNEF attribute level.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefAttributeLevelInvalid
Public Const TnefAttributeLevelInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefCompressedRtfCrc32Failed Field

ErrorCodesTnefCompressedRtfCrc32Failed Field
Compressed-RTF CRC32 failed.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefCompressedRtfCrc32Failed
Public Const TnefCompressedRtfCrc32Failed As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefCompressedRtfDataSizeMismatch Field

ErrorCodesTnefCompressedRtfDataSizeMismatch Field
Compressed-RTF data size mismatch.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefCompressedRtfDataSizeMismatch
Public Const TnefCompressedRtfDataSizeMismatch As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefCompressedRtfHeaderInvalid Field

ErrorCodesTnefCompressedRtfHeaderInvalid Field
Invalid compressed-RTF header.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefCompressedRtfHeaderInvalid
Public Const TnefCompressedRtfHeaderInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefGuidInvalid Field

ErrorCodesTnefGuidInvalid Field
Invalid TNEF Guid.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefGuidInvalid
Public Const TnefGuidInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefLevelTypeInvalid Field

ErrorCodesTnefLevelTypeInvalid Field
Invalid TNEF level type.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefLevelTypeInvalid
Public Const TnefLevelTypeInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefMapiPropTypeInvalid Field

ErrorCodesTnefMapiPropTypeInvalid Field
Invalid MAPI property type of TNEF data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefMapiPropTypeInvalid
Public Const TnefMapiPropTypeInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefMapiTypeUnknown Field

ErrorCodesTnefMapiTypeUnknown Field
Unknown MAPI type of TNEF data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefMapiTypeUnknown
Public Const TnefMapiTypeUnknown As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefMapiValueInvalid Field

ErrorCodesTnefMapiValueInvalid Field
Invalid MAPI property value of TNEF data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefMapiValueInvalid
Public Const TnefMapiValueInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefSignatureInvalid Field

ErrorCodesTnefSignatureInvalid Field
The supplied data does not have a valid TNEF signature.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefSignatureInvalid
Public Const TnefSignatureInvalid As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefUnexpectedEndOfStream Field

ErrorCodesTnefUnexpectedEndOfStream Field
Unexpected end of TNEF stream.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefUnexpectedEndOfStream
Public Const TnefUnexpectedEndOfStream As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.TnefUnknownRtfCompressionType Field

ErrorCodesTnefUnknownRtfCompressionType Field
Unknown compression type.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int TnefUnknownRtfCompressionType
Public Const TnefUnknownRtfCompressionType As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.UnauthorizedAccessException Field

ErrorCodesUnauthorizedAccessException Field
UnauthorizedAccessException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int UnauthorizedAccessException
Public Const UnauthorizedAccessException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.Unknown Field

ErrorCodesUnknown Field
Unknown error.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int Unknown
Public Const Unknown As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.UnsupportedLoginMethod Field

ErrorCodesUnsupportedLoginMethod Field
The requested authentication method is not supported by the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int UnsupportedLoginMethod
Public Const UnsupportedLoginMethod As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.WebException Field

ErrorCodesWebException Field
WebException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int WebException
Public Const WebException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes.XmlException Field

ErrorCodesXmlException Field
XmlException occurred.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const int XmlException
Public Const XmlException As Integer

Field Value

Type: Int32
See Also

Reference

ErrorCodes Class
MailBee Namespace


ErrorCodes Methods

ErrorCodes Methods

The ErrorCodes type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ErrorCodes Class
MailBee Namespace


Global Class

Global Class
Provides properties specifying default values and parameter settings which apply to instances of all MailBee classes.
Inheritance Hierarchy
SystemObject
MailBeeGlobal

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Global
Public Class Global

The Global type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
AutodetectPortAndSslMode | Gets or sets whether MailBee should override SSL mode and/or port to use when it detects well-known mail server hostname (like gmail.com) or port number (like 995).
DefaultCulture | Gets or sets the default CultureInfo to be used for string comparisons and conversions.
DefaultEncoding | Gets or sets the default Encoding to be used for byte-to-string and string-to-byte conversions when no encoding is specified.
DefaultServerName | Gets or sets the default mail server name to be used when no server name specified.
DefaultTimeout | Gets or sets the default timeout value (in milliseconds) of all MailBee classes which allow the developer to set timeout value.
DnsMaxFailureCount | Gets or sets the maximum number of seriated failures of the DNS server required in order to consider the DNS server down.
DnsNextAttemptInterval | Gets or sets the amount of time (in milliseconds) the failed DNS server spends in quarantine.
DnsPort | Gets or sets the port on which to communicate with DNS servers.
DnsServers | Gets the list of DNS servers to use in addition to any DNS servers in the config file.
FipsMode | Gets or sets if MailBee must disable security algorithms which are not FIPS-compliant.
FixBadDates | Gets or sets if MailBee should attempt to fix bad datetime values instead of throwing an exception.
LicenseKey | Assigns the license key.
LocalSmtpMXServerName | Gets or sets the default SMTP MX server name to be used to send mail in direct send mode to the recipients whose e-mail address contains no domain part.
MaxMultiLineDataLength | Gets or sets the maximum length (in bytes) of the multi-line data (request to a server or response from a server) which will be inserted into the log without truncation.
Pipelining | Gets or sets whether pipelining (joining commands in batches) must be enabled by default.
PreferIPv4Hosts | Gets or sets whether MailBee should try to connect to IPv4 endpoints before IPv6 endpoints when connecting to mail servers.
PreserveMimePartOrder | Gets or sets whether MailBee should put plain-text and HTML part before any other text parts.
PrivateDataCover | Gets or sets the string to be used instead of the actual password data in the log when HidePasswords is true.
SafeMode | Gets or sets whether safe mode (prefer compatibility instead of performance) must be ENABLED by default.
TcpBufSize | Gets or sets the default size (in bytes) of TCP buffer.
UnwrappedLineLengthLimit | Gets or sets the minimum length of a line which needs wrapping.
Version | Gets the version of the MailBee assembly.
Top
Remarks

The most important property in this class is LicenseKey which unlocks MailBee.NET Objects.

Changes of the property values of this class affect all MailBee classes in the current application domain. For instance, if DnsPort is set to 42, all subsequent DNS MX lookup queries will be initiated on port 42. Or, if DefaultTimeout is set to 500, all subsequent connections will use 0.5 seconds as a timeout value (however, any connections which are already open will still use their current timeout settings).

Note Note
If you're Visual Basic developer, you need to use fully qualified name when accessing properties of this class. For instance, use MailBee.Global.AutodetectPortAndSslMode, not Global.AutodetectPortAndSslMode. This is because Global is a keyword in VB.
See Also

Reference

MailBee Namespace


Global Methods

Global Methods

The Global type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Global Class
MailBee Namespace


Global Properties

Global Properties

The Global type exposes the following members.

Properties
Name | Description
AutodetectPortAndSslMode | Gets or sets whether MailBee should override SSL mode and/or port to use when it detects well-known mail server hostname (like gmail.com) or port number (like 995).
DefaultCulture | Gets or sets the default CultureInfo to be used for string comparisons and conversions.
DefaultEncoding | Gets or sets the default Encoding to be used for byte-to-string and string-to-byte conversions when no encoding is specified.
DefaultServerName | Gets or sets the default mail server name to be used when no server name specified.
DefaultTimeout | Gets or sets the default timeout value (in milliseconds) of all MailBee classes which allow the developer to set timeout value.
DnsMaxFailureCount | Gets or sets the maximum number of seriated failures of the DNS server required in order to consider the DNS server down.
DnsNextAttemptInterval | Gets or sets the amount of time (in milliseconds) the failed DNS server spends in quarantine.
DnsPort | Gets or sets the port on which to communicate with DNS servers.
DnsServers | Gets the list of DNS servers to use in addition to any DNS servers in the config file.
FipsMode | Gets or sets if MailBee must disable security algorithms which are not FIPS-compliant.
FixBadDates | Gets or sets if MailBee should attempt to fix bad datetime values instead of throwing an exception.
LicenseKey | Assigns the license key.
LocalSmtpMXServerName | Gets or sets the default SMTP MX server name to be used to send mail in direct send mode to the recipients whose e-mail address contains no domain part.
MaxMultiLineDataLength | Gets or sets the maximum length (in bytes) of the multi-line data (request to a server or response from a server) which will be inserted into the log without truncation.
Pipelining | Gets or sets whether pipelining (joining commands in batches) must be enabled by default.
PreferIPv4Hosts | Gets or sets whether MailBee should try to connect to IPv4 endpoints before IPv6 endpoints when connecting to mail servers.
PreserveMimePartOrder | Gets or sets whether MailBee should put plain-text and HTML part before any other text parts.
PrivateDataCover | Gets or sets the string to be used instead of the actual password data in the log when HidePasswords is true.
SafeMode | Gets or sets whether safe mode (prefer compatibility instead of performance) must be ENABLED by default.
TcpBufSize | Gets or sets the default size (in bytes) of TCP buffer.
UnwrappedLineLengthLimit | Gets or sets the minimum length of a line which needs wrapping.
Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

Global Class
MailBee Namespace


Global.AutodetectPortAndSslMode Property

GlobalAutodetectPortAndSslMode Property
Gets or sets whether MailBee should override SSL mode and/or port to use when it detects well-known mail server hostname (like gmail.com) or port number (like 995).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool AutodetectPortAndSslMode { get; set; }
Public Shared Property AutodetectPortAndSslMode As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will override SSL mode and/or port to use when connecting to the mail server if it detects well-known mail server hostname or port number. If false, MailBee will always use the values specified by the application. The default value is true.
Remarks
This property makes it easier for the programmer to implement the logic of connecting to mail servers which require SSL connections. Currently, when it's true, SslMode of the corresponding Pop3, Smtp or Imap object has the default value Manual and the developer calls Connect or BeginConnect method, the following checks are made:
  • If the hostname is "pop.gmail.com", use OnConnect mode and port 995.
  • If the hostname is "imap.gmail.com", use OnConnect mode and port 993.
  • If the hostname is "smtp.gmail.com", use UseStartTlsIfSupported mode if the application specifies port 25 or 587, or OnConnect if the port specified is 465.
  • If the hostname is "pop3.live.com", use OnConnect mode and port 995.
  • If the hostname is "smtp.live.com", use UseStartTlsIfSupported mode if the application specifies port 25 or 587.
  • If the hostname is "pop-mail.outlook.com" or "pop3-mail.outlook.com", use OnConnect mode and port 995.
  • If the hostname is "imap-mail.outlook.com", use OnConnect mode and port 993.
  • If the hostname is "smtp-mail.outlook.com", use UseStartTlsIfSupported mode and port 587.
  • If the hostname is "imap.mail.yahoo.com", use OnConnect mode and port 993.
  • If the hostname is "pop.mail.yahoo.com", use OnConnect mode and port 995.
  • If the hostname is "smtp.mail.yahoo.com", use OnConnect mode and port 465.
  • If the hostname ends with ".office365.com" or ".outlook.com" (but not "pop-mail.outlook.com", "pop3-mail.outlook.com", "imap-mail.outlook.com", "smtp-mail.outlook.com"), use UseStartTlsIfSupported mode and regular port (applies to SMTP, IMAP, POP3).
  • If the hostname is not well-known, use UseStartTlsIfSupported mode if the application specifies port 587 for SMTP connection, or use OnConnect mode if the port is 465 for SMTP, 995 for POP3 or 993 for IMAP.
If you want to manually specify port and SSL mode, set this property value to false. For example, this can be useful if the mail server you're connecting to runs a regular (not SSL) POP3 service on the dedicated SSL POP3 port 995 and you want to use Manual mode.
Note Note
SSL mode and port overriding will not occur if the application itself changes SslMode from its default value Manual.

Note that in Visual Basic you need to use the fully qualified name when accessing this property. Use MailBee.Global.AutodetectPortAndSslMode, not Global.AutodetectPortAndSslMode. This is because Global is a keyword in VB.

See Also

Reference

Global Class
MailBee Namespace


Global.DefaultCulture Property

GlobalDefaultCulture Property
Gets or sets the default CultureInfo to be used for string comparisons and conversions.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static CultureInfo DefaultCulture { get; set; }
Public Shared Property DefaultCulture As CultureInfo
    Get
    Set

Property Value

Type: CultureInfo
A reference to the CultureInfo object to be used for string comparisons and conversions. The default value is InvariantCulture.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Global Class
MailBee Namespace


Global.DefaultEncoding Property

GlobalDefaultEncoding Property
Gets or sets the default Encoding to be used for byte-to-string and string-to-byte conversions when no encoding is specified.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static Encoding DefaultEncoding { get; set; }
Public Shared Property DefaultEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the Encoding object to be used for byte-to-string and string-to-byte conversions when no encoding is specified. The default value is Default.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Global Class
MailBee Namespace


Global.DefaultServerName Property

GlobalDefaultServerName Property
Gets or sets the default mail server name to be used when no server name specified.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string DefaultServerName { get; set; }
Public Shared Property DefaultServerName As String
    Get
    Set

Property Value

Type: String
The string containing the default mail server name to be used when no server name specified. The default value is "localhost".
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Global Class
MailBee Namespace


Global.DefaultTimeout Property

GlobalDefaultTimeout Property
Gets or sets the default timeout value (in milliseconds) of all MailBee classes which allow the developer to set timeout value.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int DefaultTimeout { get; set; }
Public Shared Property DefaultTimeout As Integer
    Get
    Set

Property Value

Type: Int32
An integer value which will be used as an initial value of Timeout property during creating instances of any MailBee class which implements Timeout property. The default value is 20000 (20 seconds).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
If set to zero, the default timeout setting will be "wait indefinitely".
Note Note
DefaultTimeout field has no effect on UDP timeout default value (UdpTimeout property).
See Also

Reference

Global Class
MailBee Namespace


Global.DnsMaxFailureCount Property

GlobalDnsMaxFailureCount Property
Gets or sets the maximum number of seriated failures of the DNS server required in order to consider the DNS server down.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int DnsMaxFailureCount { get; set; }
Public Shared Property DnsMaxFailureCount As Integer
    Get
    Set

Property Value

Type: Int32
The number of seriated failures of the DNS server which needs to be achieved in order to consider this server down. The default value is 3.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is less than 1.
Remarks

When making DNS MX lookup queries, it's normal that the DNS server does not respond in appropriate time frame sometimes. In this case, the query is sent second time. If the second (or n-th, if UdpRetryCount is n) attempt fails too, the DNS server is put aside (set in quarantine) and another DNS server is tried (however, if no more servers available, an error occurs). The amount of time the DNS server spends in quarantine is set by DnsNextAttemptInterval field. Once this time is over, the DNS server is returned back to the working servers set, and can be used again. If the DNS server again did not responded to two (or n) queries one by one, it's set in quarantine again. When the number of settings in quarantine is going to reach DnsMaxFailureCount, the server is considered completely down, and will not be tried any longer (or at least until the application explicitly calls Reset method).

If, however, the DNS server having non-zero number of failures does respond to any query, the failure counter is reset (i.e. only "one by one" failures are counted). Thus, temporary DNS failures are discarded while permanent or long-term downs are recognized correctly.

See Also

Reference

Global Class
MailBee Namespace


Global.DnsNextAttemptInterval Property

GlobalDnsNextAttemptInterval Property
Gets or sets the amount of time (in milliseconds) the failed DNS server spends in quarantine.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int DnsNextAttemptInterval { get; set; }
Public Shared Property DnsNextAttemptInterval As Integer
    Get
    Set

Property Value

Type: Int32
The length of the period (in milliseconds) the failed DNS server spends in quarantine. The default value is 1000 (1 second).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
If the DNS server didn't responded UdpRetryCount running, it's set in quarantine for DnsNextAttemptInterval milliseconds. During this interval, the server is not used (other servers used if any, or an error occurs if all the servers are in quarantine). If the number of quarantines reaches DnsMaxFailureCount, the server is disabled instead of being set in quarantine (see DnsMaxFailureCount field for details).
See Also

Reference

Global Class
MailBee Namespace


Global.DnsPort Property

GlobalDnsPort Property
Gets or sets the port on which to communicate with DNS servers.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int DnsPort { get; set; }
Public Shared Property DnsPort As Integer
    Get
    Set

Property Value

Type: Int32
The integer value containing the port number to connect to DNS servers on. The default value is 53 (Domain Name Server port).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value does not denote a valid port number.
Remarks
In some rare cases, the developer may need to set it to 42 (Host Name Server port).
See Also

Reference

Global Class
MailBee Namespace


Global.DnsServers Property

GlobalDnsServers Property
Gets the list of DNS servers to use in addition to any DNS servers in the config file.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static DnsServerCollection DnsServers { get; }
Public Shared ReadOnly Property DnsServers As DnsServerCollection
    Get

Property Value

Type: DnsServerCollection
A collection of DNS servers which will be added to the entries found in the config file. The default value is an empty collection.
Remarks

This property affects how Autodetect method and Autodetect(DnsAutodetectOptions) method with ConfigFiles flag set work.

When this collection is non-empty and MailBee is asked to get the DNS servers from the config file, MailBee will append entries from this collection to the entries found in the config file. This is useful for .NET Core, UWP, Xamarin where app.config is not available or you need to set the servers in runtime and it's not possible to auto-detect them. So, even if you don't have any app.config at all, you can mimic having some entries there by populating DnsServers collection.

See Also

Reference

Global Class
MailBee Namespace


Global.FipsMode Property

GlobalFipsMode Property
Gets or sets if MailBee must disable security algorithms which are not FIPS-compliant.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool FipsMode { get; set; }
Public Shared Property FipsMode As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MD5 dependent authentication methods will be disabled. If false, all authentication methods will be enabled.
Remarks

This property should only be set if the target machines where MailBee is being used must conform to a FIPS 140-2 standard. Such machines have HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy\Enabled set to 1.

By default, MailBee does not use weak algorithms like MD5 and RC4 (even if FipsMode is false) and uses stronger methods like SHA1 instead (this concerns S/MIME, SSL, digests of Message-ID hashes, etc). However, there are things which can only be implemented via MD5. They include Apop, SaslCramMD5, SaslDigestMD5 authentication methods. When FipsMode is enabled, MailBee will never use these methods even if they are supported by the mail server.

FipsMode also affects how SHA1 and SHA256 algorithms are used with DomainKeys. In FIPS mode, MailBee will pick FIPS-compliant implementations of these algorithms instead of their managed code counterparts (managed code versions are faster but not FIPS-compliant). If FipsMode is NOT enabled and the current system is FIPS-compliant, MailBee will try a non-FIPS method first. It will fail with an exception, MailBee will catch that exception and fall back to a FIPS method. Enabling FipsMode avoids penalty of trying the method which will fail anyway.

SSL and S/MIME functions of MailBee are by default immune to FIPS restrictions and use FIPS-compliant methods.

Note Note
If the current system if FIPS-enabled and you didn't set FipsMode to true, you may get InvalidOperationException exceptions and related errors (mostly, with MD5-based authentication mechanisms). This is because .NET Framework will block MailBee's attempts to create instances of FIPS-noncompliant classes.
See Also

Reference

Global Class
MailBee Namespace


Global.FixBadDates Property

GlobalFixBadDates Property
Gets or sets if MailBee should attempt to fix bad datetime values instead of throwing an exception.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool FixBadDates { get; set; }
Public Shared Property FixBadDates As Boolean
    Get
    Set

Property Value

Type: Boolean
If true and the string date in the message being parsed contains time with invalid values of hours, minutes or seconds, Date property will return a valid datetime which is closest to the source invalid value. If false (the default value), MailBeeDateParsingException will be thrown in this case or Date property will return MinValue (depending on MailBee.Mime.MailMessage.ThrowExceptions value).
Remarks

For instance, the message has Date: Fri, 30 May 2014 09:51:79 GMT in its headers. 79 is incorrect value for seconds. By default, MailBee will not parse such date. You can, however, enable FixBadDates and MailBee will return the datetime which corresponds to 30 May 2014 09:51:59 GMT value.

This lets the application ignore small errors in Date values which are often the case with messages created by some low quality mail programs or spam generators.

MailMessage.SetDateFromString method, Envelope.Date (and all other properties dealing with MIME Date format) are also affected by this setting.

Note Note
MailBee can fix only time part in wrong dates. Wrong days, months or years cannot be tolerated because the rounding difference will be too significant for getting satisfactory results.
See Also

Reference

Global Class
MailBee Namespace


Global.LicenseKey Property

GlobalLicenseKey Property
Assigns the license key.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string LicenseKey { get; set; }
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks

You can unlock MailBee.NET Objects by setting this property to the valid permanent or trial license key or by adding MailBee.Global.LicenseKey key in app.config, web.config, or machine.config file. The 3rd method is to pass the license key as a parameter when calling a constructor which creates an instance of a component.

This property is static (Shared in Visual Basic). If not set in the config file, this property must be set before using any static methods creating any instances of Global class.

Examples
Setting this property and creating instances of all licensed classes.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee.AntiSpam;
using MailBee.ImapMail;
using MailBee.Outlook;
using MailBee.Pdf;
using MailBee.Pop3Mail;
using MailBee.Security;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)
MailBee.Global.LicenseKey = "Permanent or trial license key here";
BayesFilter filter = new BayesFilter();
Imap imp = new Imap();
MsgConvert conv_msg = new MsgConvert();
PstReader reader = new PstReader(@"C:\OutlookMessageBase\Outlook.pst");
HtmlToPdf conv_pdf = new HtmlToPdf();
Pop3 pop = new Pop3();
Smime sm = new Smime();
Smtp mailer = new Smtp();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee.AntiSpam
Imports MailBee.ImapMail
Imports MailBee.Outlook
Imports MailBee.Pdf
Imports MailBee.Pop3Mail
Imports MailBee.Security
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)
MailBee.Global.LicenseKey = "Permanent or trial license key here"
Dim filter As New BayesFilter
Dim imp As New Imap
Dim conv_msg As New MsgConvert
Dim reader As New PstReader("C:\OutlookMessageBase\Outlook.pst")
Dim conv_pdf As New HtmlToPdf
Dim pop As New Pop3
Dim sm As New Smime
Dim mailer = New Smtp
Examples
Setting the license key in the config file and creating instances of all licensed classes.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee.AntiSpam;
using MailBee.ImapMail;
using MailBee.Outlook;
using MailBee.Pdf;
using MailBee.Pop3Mail;
using MailBee.Security;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)
BayesFilter filter = new BayesFilter();
Imap imp = new Imap();
MsgConvert conv_msg = new MsgConvert();
PstReader reader = new PstReader(@"C:\OutlookMessageBase\Outlook.pst");
HtmlToPdf conv_pdf = new HtmlToPdf();
Pop3 pop = new Pop3();
Smime sm = new Smime();
Smtp mailer = new Smtp();

// XML config file (app.config, web.config, or machine.config):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MailBee.Global.LicenseKey" value="Permanent or trial license key here"/>
</appSettings>
</configuration>

// In .NET 2.0, it can be <applicationSettings> instead of <appSettings>.
Imports MailBee.AntiSpam
Imports MailBee.ImapMail
Imports MailBee.Outlook
Imports MailBee.Pdf
Imports MailBee.Pop3Mail
Imports MailBee.Security
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)
Dim filter As New BayesFilter
Dim imp As New Imap
Dim conv_msg As New MsgConvert
Dim reader As New PstReader("C:\OutlookMessageBase\Outlook.pst")
Dim conv_pdf As New HtmlToPdf
Dim pop As New Pop3
Dim sm As New Smime
Dim mailer = New Smtp

' XML config file (app.config, web.config, or machine.config):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MailBee.Global.LicenseKey" value="Permanent or trial license key here"/>
</appSettings>
</configuration>

' In .NET 2.0, it can be <applicationSettings> instead of <appSettings>.
See Also

Reference

Global Class
MailBee Namespace


Global.LocalSmtpMXServerName Property

GlobalLocalSmtpMXServerName Property
Gets or sets the default SMTP MX server name to be used to send mail in direct send mode to the recipients whose e-mail address contains no domain part.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string LocalSmtpMXServerName { get; set; }
Public Shared Property LocalSmtpMXServerName As String
    Get
    Set

Property Value

Type: String
The name of SMTP server to relay mail in direct send mode when it's impossible to determine recipient's own SMTP MX server because domain is missing in e-mail address, or a null reference (Nothing in Visual Basic) to use local machine name as SMTP server name.
Remarks

When this property is a null reference (default value), the local machine name will be used as the name of SMTP MX server for sending mail to e-mail addresses like jdoe (as opposed to jdoe@domain) in direct send mode.

When sending to a relay SMTP server, all the recipients are submitted to the relay server, and LocalSmtpMXServerName value is not used.

Note Note
If LocalSmtpMXServerName is set to an empty string (Empty) rather than to a null reference, MailBee will attempt to perform MX lookup query for an empty domain name on direct send attempt, which would result in an error.
See Also

Reference

Global Class
MailBee Namespace


Global.MaxMultiLineDataLength Property

GlobalMaxMultiLineDataLength Property
Gets or sets the maximum length (in bytes) of the multi-line data (request to a server or response from a server) which will be inserted into the log without truncation.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int MaxMultiLineDataLength { get; set; }
Public Shared Property MaxMultiLineDataLength As Integer
    Get
    Set

Property Value

Type: Int32
An integer value containing the maximum length (in bytes) of the multi-line data (request to a server or response from a server) which will be inserted into the log without truncation. The default value is 128.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
This property allows the developer to limit the maximum length of large textual data (such as client requests and server responses) to be inserted in the log. This parameter has no effect if logging is not used.
Note Note
POP3 requests and SMTP responses are always printed into the log completely. This is because POP3 requests and SMTP responses are small, and all the information in this data is very important and should not be truncated.
See Also

Reference

Global Class
MailBee Namespace


Global.Pipelining Property

GlobalPipelining Property
Gets or sets whether pipelining (joining commands in batches) must be enabled by default.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool Pipelining { get; set; }
Public Shared Property Pipelining As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the pipelining will be enabled by default; otherwise, disabled. The default value is true.
Remarks
If this property value is true and pipelining was not explicitly disabled and the mail server supports pipelining, it will be used. Using pipelining greatly increases performance of communication with the mail server.
Note Note
If SafeMode is true, Pipelining value will be set to false and the pipelining will be disabled.
The developer, however, may still connect to the mail server with pipelining enabled using Connect method overload which explicitly specifies whether pipelining should be used or not. For instance, for Pop3 class, such overload is Connect(String, Int32, Boolean).
See Also

Reference

Global Class
MailBee Namespace


Global.PreferIPv4Hosts Property

GlobalPreferIPv4Hosts Property
Gets or sets whether MailBee should try to connect to IPv4 endpoints before IPv6 endpoints when connecting to mail servers.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool PreferIPv4Hosts { get; set; }
Public Shared Property PreferIPv4Hosts As Boolean
    Get
    Set

Property Value

Type: Boolean
If true and a mail server's host name is resolved in multiple IP addresses, MailBee will try IPv4 IP addresses first. If false, MailBee will try IPv4 and IPv6 addresses in the same order they are returned by the OS. The defaut value is true.
See Also

Reference

Global Class
MailBee Namespace


Global.PreserveMimePartOrder Property

GlobalPreserveMimePartOrder Property
Gets or sets whether MailBee should put plain-text and HTML part before any other text parts.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool PreserveMimePartOrder { get; set; }
Public Shared Property PreserveMimePartOrder As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will not re-arrange MIME parts when building the message from the existing message. If false, MailBee will put plain-text and HTML parts first. The default value is true.
Remarks
This is special use property which is only imporant when you're re-sending existing messages. It has no sense for parsing messages or sending new messages. Some mail clients require well-defined order of text parts (usually, when there are more body types than just plain-text and HTML, such as text/watch-htmli>).
See Also

Reference

Global Class
MailBee Namespace


Global.PrivateDataCover Property

GlobalPrivateDataCover Property
Gets or sets the string to be used instead of the actual password data in the log when HidePasswords is true.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string PrivateDataCover { get; set; }
Public Shared Property PrivateDataCover As String
    Get
    Set

Property Value

Type: String
The string to replace the actual password data in the log file or memory log. The default value is "********".
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Global Class
MailBee Namespace


Global.SafeMode Property

GlobalSafeMode Property
Gets or sets whether safe mode (prefer compatibility instead of performance) must be ENABLED by default.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool SafeMode { get; set; }
Public Shared Property SafeMode As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, many performance extensions (including Pipelining) will be DISABLED by default; otherwise, they will be enabled (unless they have not been explicitly disabled via their corresponding options). The default value is false (safe mode is off and the extensions are enabled).
Remarks

The purpose of this property is to troubleshoot various issues with incorrect implementations of mail protocols on some servers. When SafeMode is enabled, MailBee downgrades its capabilities to the level which still provides all the features but with reduced performance.

Another effect of SafeMode enabled is changing the order in which authentication methods are tried for availibility. By default, MailBee attempts to use secure methods and downgrades to non-secure ones only if secure methods are not available. In SafeMode, this behavior is reversed. However, if the list of desired methods is limited to secure methods only (for instance, Login(String, String, AuthenticationMethods) was called with authMethods parameter set to Apop), MailBee will NOT attempt to use non-secure methods even in safe mode.

Setting SafeMode to true changes the defaults as follows:

  • Pipelining is disabled (Pipelining will return false)
  • PreferSimpleMethods is enabled
  • All ESMTP extensions except AUTH (SMTP authentication) are disabled (SmtpOptions is 7)

Note Note
SafeMode property specifies defaults only for newly created connection settings objects. Thus, it must be set BEFORE creating instances of MailBee classes which are containers of the connection settings (i.e. SmtpServer). The property value does not have any effect on SmtpServer objects already created.

However, even if certain connection settings object was created AFTER SafeMode property had already been set, its effect can be overridden using such object's properties or method parameters which explicitly control the corresponding options. For instance, the developer may manually change SmtpOptions value after it was set during construction of the object.

Note that in Visual Basic you need to use the fully qualified name when accessing this property. Use MailBee.Global.SafeMode, not Global.SafeMode. This is because Global is a keyword in VB.

See Also

Reference

Global Class
MailBee Namespace


Global.TcpBufSize Property

GlobalTcpBufSize Property
Gets or sets the default size (in bytes) of TCP buffer.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int TcpBufSize { get; set; }
Public Shared Property TcpBufSize As Integer
    Get
    Set

Property Value

Type: Int32
The default size (in bytes) of TCP buffer. The default value is 65536.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is less than 1.
Remarks

The developer may consider to reduce this value to make MailBee raise DateReceived, DateSent, and similar events more often.

Increasing this property value may improve performance because MailBee will send and receive data in larger chunks.

See Also

Reference

Global Class
MailBee Namespace


Global.UnwrappedLineLengthLimit Property

GlobalUnwrappedLineLengthLimit Property
Gets or sets the minimum length of a line which needs wrapping.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int UnwrappedLineLengthLimit { get; set; }
Public Shared Property UnwrappedLineLengthLimit As Integer
    Get
    Set

Property Value

Type: Int32
The maximum length of unwrapped line of text. The default value is 76.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is less than 76 or larger than 255.
Remarks

This is advanced property needed only when you're re-sending (forwarding) existing messages.

MIME requires body lines be wrapped if they exceed 76 chars. Normally it's not an issue as MailBee automatically wraps all the lines when building the message and this does not cause any artifacts (quoted-printable encoding takes care of this). Sometimes, however, if you have an existing message with no quoted-printable or base64 encoding and with lengthy lines, you may need to increase this value if you want to keep its formatting (avoid adding extra line breaks) after re-sending.

Note Note
Having lines with more than 76 chars is MIME standards violation. When making new messages, you should avoid chaning the default value of this property unless you have a very good reason for this. Again, by default MailBee utilizes quoted-printable encoding to transparently wrap lines without any extra line breaks. You should use this property only if the mail reader of the recipient cannot deal with quoted-printable (or base64).
See Also

Reference

Global Class
MailBee Namespace


Global.Version Property

GlobalVersion Property
Gets the version of the MailBee assembly.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string Version { get; }
Public Shared ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

Global Class
MailBee Namespace


LogEntry Class

LogEntry Class
Represents an entry to be added into the log file or memory log buffer.
Inheritance Hierarchy
SystemObject
MailBeeLogEntry

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class LogEntry
Public Class LogEntry

The LogEntry type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns formatted log string. (Overrides ObjectToString.)
Top
Properties
 | Name | Description
Public property | AddThisEntry | Gets or sets whether this log entry must be added into the log.
Public property | ContextInfo | Gets the string containing fully-qualified name of the current context.
Public property | MessageComment | Gets or sets the string containing any additional information about the message text or data.
Public property | MessageText | Gets or sets the string containing the message text or data.
Public property | MessageType | Gets the type of the log entry.
Public property | Time | Gets the date and time when this log entry was created.
Top
Remarks
The instance of this class is passed as NewEntry property value of LogNewEntry event which can be raised by Smtp, Pop3, and Imap components.
Note Note
The developer can set AddThisEntry property value to false to cancel adding a particular entry into the log.
See Also

Reference

MailBee Namespace


LogEntry Methods

LogEntry Methods

The LogEntry type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns formatted log string. (Overrides ObjectToString.)
Top
See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.ToString Method

LogEntryToString Method
Returns formatted log string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
A formatted log string, like "[18:28:34.22] [SEND] [SEND-00.SMTP-00........] MAIL FROM:<user@domain.com>\r\n".
See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry Properties

LogEntry Properties

The LogEntry type exposes the following members.

Properties
 | Name | Description
Public property | AddThisEntry | Gets or sets whether this log entry must be added into the log.
Public property | ContextInfo | Gets the string containing fully-qualified name of the current context.
Public property | MessageComment | Gets or sets the string containing any additional information about the message text or data.
Public property | MessageText | Gets or sets the string containing the message text or data.
Public property | MessageType | Gets the type of the log entry.
Public property | Time | Gets the date and time when this log entry was created.
Top
See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.AddThisEntry Property

LogEntryAddThisEntry Property
Gets or sets whether this log entry must be added into the log.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AddThisEntry { get; set; }
Public Property AddThisEntry As Boolean
    Get
    Set

Property Value

Type: Boolean
A boolean value specifying whether this log entry must be added into the log. The default value is true.
Remarks
The developer may set it to false to force MailBee ignore this log entry and do not put it into the log.
See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.ContextInfo Property

LogEntryContextInfo Property
Gets the string containing fully-qualified name of the current context.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContextInfo { get; }
Public ReadOnly Property ContextInfo As String
    Get

Property Value

Type: String
The string containing dot-separated names of all MailBee contexts which participate in the current operation.
Remarks

This property is useful when using the Smtp component. Unlike Pop3 and Imap components, Smtp component can operate in multiple contexts

When Pop3 component is used, the context is always POP3.

However, when Smtp component is used, the context may be somewhat like SEND-00.SMTP-04, which indicates the component is sending a mail message using multiple threads, and the current log entry corresponds to thread #4 (starting from zero). Another example is SEND-00.SMTP-00.POP3 which means the component currently operates in send mail mode, the connection to SMTP server on thread #0 is in progress, and POP-before-SMTP authentication is currently performed as a part of this connection procedure.

ContextInfo value is especially useful when Smtp component operates in multi-thread mode (MaxThreadCount is not 1). In this case, many log entries are simultaneously added into the log by multiple threads. In this case, ContextInfo allows the person who's viewing the log to group the log entries by their ContextInfo values.

See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.MessageComment Property

LogEntryMessageComment Property
Gets or sets the string containing any additional information about the message text or data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MessageComment { get; set; }
Public Property MessageComment As String
    Get
    Set

Property Value

Type: String
The string containing any additional information about the message text or data, or an empty string if no additional information is available.
Remarks

The comment is usually added if MessageText contains incomplete information. For instance, if large block of data has been received from the network so only the part of this data has been placed into MessageText, MessageComment will return the string specifying the entire length of the received data.

In the log file or memory log, the comment (if any) is enclosed in [].

In the following example, the message comment is marked bold:

[21:13:32.92] [RECV] +OK 117 messages\r\n [Total 1074 bytes received.]

See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.MessageText Property

LogEntryMessageText Property
Gets or sets the string containing the message text or data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MessageText { get; set; }
Public Property MessageText As String
    Get
    Set

Property Value

Type: String
The string containing the texual or binary data representing the information this log entry is about.
Remarks

This property value contains either data received from or sent to the network (when MessageType is Send or Recv) or informational/error/warning messages from MailBee.

In the following example, the message text is marked bold:

[18:28:34.22] [SEND] [SEND-00.SMTP-00........] MAIL FROM:<user@domain.com>\r\n

See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.MessageType Property

LogEntryMessageType Property
Gets the type of the log entry.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public LogMessageType MessageType { get; }
Public ReadOnly Property MessageType As LogMessageType
    Get

Property Value

Type: LogMessageType
A LogMessageType value specifying the type of the log entry (such as user-defined log message, informational message, etc).
Remarks
Since user-defined log entries (User), which are produced when the developer explicitly adds an entry to the log using WriteLine(String) method, do not cause LogNewEntry events to occur, the LogMessageType property never returns User.
See Also

Reference

LogEntry Class
MailBee Namespace


LogEntry.Time Property

LogEntryTime Property
Gets the date and time when this log entry was created.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime Time { get; }
Public ReadOnly Property Time As DateTime
    Get

Property Value

Type: DateTime
A DateTime value specifying the date and time of the moment when the log entry was created.
See Also

Reference

LogEntry Class
MailBee Namespace


LogFormatOptions Enumeration

LogFormatOptions Enumeration
Provides flags which can be used to change formatting of log messages produced by MailBee.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum LogFormatOptions
<FlagsAttribute>
Public Enumeration LogFormatOptions
Members
Member name | Value | Description
None | 0 | Use default formatting.
AddDate | 1 | Include the current date in the timestamp.
AddContextInfo | 2 | Include the information about the current thread ID and the current context (such as DNSQ (DNS Query), SMTP, POP3, SEND). Useful in multi-thread mode (when log messages, produced by different threads, overlap).
BinaryAsText | 4 | Disable base64 encoding of binary data (usually, in DNS MX lookup queries).
Examples
This sample demonstrates the effect of different LogFormatOptions flags.
Note Note
The actual values can be different in your case.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // LogNewEntry event handler.
    private static void OnLogNewEntry(object sender, LogNewEntryEventArgs e)
    {
        // For readability, reduce the number of log entries displayed.
        if (e.NewEntry.MessageType != LogMessageType.Recv)
        {
            e.NewEntry.AddThisEntry = false;
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        mailer.SmtpServers.Add("smtp.domain.com");

        // Enable logging the SMTP session into memory.
        mailer.Log.Enabled = true;
        mailer.Log.MemoryLog = true;

        // Subscribe to the LogNewEntry event.
        mailer.LogNewEntry += new LogNewEntryEventHandler(OnLogNewEntry);

        mailer.Log.Clear();
        mailer.Connect();
        Console.WriteLine("Format is None");
        Console.WriteLine(mailer.Log.GetMemoryLog());

        mailer.Log.Clear();
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Hello();
        Console.WriteLine("Format is AddContextInfo");
        Console.WriteLine(mailer.Log.GetMemoryLog());

        mailer.Log.Clear();
        mailer.Log.Format = LogFormatOptions.AddDate;
        mailer.Noop();
        Console.WriteLine("Format is AddDate");
        Console.WriteLine(mailer.Log.GetMemoryLog());

        mailer.Log.Clear();
        mailer.Log.Format = LogFormatOptions.AddContextInfo | LogFormatOptions.AddDate;
        mailer.Disconnect();
        Console.WriteLine("Format is AddContextInfo | AddDate");
        Console.WriteLine(mailer.Log.GetMemoryLog());
    }
}

// The output (the actual content will be different for your case).
Format is None
[18:55:15.26] [RECV] 220 smtp.domain.com: please say hello\r\n

Format is AddContextInfo
[18:55:15.30] [RECV] [0020] [SMTP-00................] 250-smtp.domain.com: EHLO NOTEBOOK1 accepted\r\n250

Format is AddDate
[11/08/2005 18:55:15.31] [RECV] 250 OK\r\n

Format is AddContextInfo | AddDate
[11/08/2005 18:55:15.32] [RECV] [000A] [SMTP-00................] 221 smtp.domain.com: see you later\r\n
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' LogNewEntry event handler.
    Private Shared Sub OnLogNewEntry(ByVal sender As Object, ByVal e As LogNewEntryEventArgs)
        ' For readability, reduce the number of log entries displayed
        If e.NewEntry.MessageType <> LogMessageType.Recv Then
            e.NewEntry.AddThisEntry = False
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        mailer.SmtpServers.Add("smtp.domain.com")

        ' Enable logging the SMTP session into memory.
        mailer.Log.Enabled = True
        mailer.Log.MemoryLog = True

        ' Subscribe to the LogNewEntry event.
        AddHandler mailer.LogNewEntry, AddressOf OnLogNewEntry

        mailer.Log.Clear()
        mailer.Connect()
        Console.WriteLine("Format is None")
        Console.WriteLine(mailer.Log.GetMemoryLog())

        mailer.Log.Clear()
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Hello()
        Console.WriteLine("Format is AddContextInfo")
        Console.WriteLine(mailer.Log.GetMemoryLog())

        mailer.Log.Clear()
        mailer.Log.Format = LogFormatOptions.AddDate
        mailer.Noop()
        Console.WriteLine("Format is AddDate")
        Console.WriteLine(mailer.Log.GetMemoryLog())

        mailer.Log.Clear()
        mailer.Log.Format = LogFormatOptions.AddContextInfo Or LogFormatOptions.AddDate
        mailer.Disconnect()
        Console.WriteLine("Format is AddContextInfo Or AddDate")
        Console.WriteLine(mailer.Log.GetMemoryLog())
    End Sub
End Class

' The output (the actual content will be different for your case).
Format is None
[18:55:15.26] [RECV] 220 smtp.domain.com: please say hello\r\n

Format is AddContextInfo
[18:55:15.30] [RECV] [0020] [SMTP-00................] 250-smtp.domain.com: EHLO NOTEBOOK1 accepted\r\n250

Format is AddDate
[11/08/2005 18:55:15.31] [RECV] 250 OK\r\n

Format is AddContextInfo | AddDate
[11/08/2005 18:55:15.32] [RECV] [000A] [SMTP-00................] 221 smtp.domain.com: see you later\r\n
See Also

Reference

MailBee Namespace


Logger Class

Logger Class
Provides logging facilities for MailBee components such as Smtp, Pop3, and Imap.
Inheritance Hierarchy
SystemObject
MailBeeLogger

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Logger
Public Class Logger

The Logger type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Clears the log contents if logging is enabled.
Public method | ClearAsync | async/await version of Clear.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMemoryLog | Returns the string containing the memory log contents.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | WriteLine | Adds a new log entry containing user-defined message into the log.
Public method | WriteLineAsync | async/await version of WriteLine(String).
Top
Properties
 | Name | Description
Public property | DateTimeFormatFull | Gets or sets the format of full datetime string.
Public property | DateTimeFormatTimeOnly | Gets or sets the format of time-only string.
Public property | DisableOnException | Gets or sets whether the logging should be automatically disabled instead of throwing exception when logging error occurs.
Public property | Enabled | Gets or sets whether the logging into a file or memory buffer is enabled.
Public property | FileEncoding | Gets or sets Encoding to be used when writing into the log file.
Public property | Filename | Gets or sets the log file name.
Public property | Format | Gets or sets flags which specify formatting of log entries placed into the log.
Public property | HidePasswords | Gets or sets whether the actual password data may appear in the log or not.
Public property | KeepLogFileOpen | Gets or sets whether the log file must be kept open during MailBee session.
Public property | LogDnsQueryBody | Gets or sets whether DNS MX lookup query binary data must be added into the log.
Public property | MaxSize | Gets or sets the maximum allowed length (in characters) of the file or memory log.
Public property | MemoryLog | Gets or sets whether the logging must be performed into a log file or into a memory buffer.
Public property | OldFilename | Gets or sets the name of a backup file the log must be renamed into when its size exceeds the maximum allowed limit.
Public property | SyncRoot | Gets or sets the object to be used for synchronized access to the log file.
Top
Remarks

The logging is the first tool to use for troubleshooting. If you encounter any problems with Smtp, Pop3 or Imap component, please enable the logging first, and try again.

The log provides a lot of useful and detailed information on how MailBee communicates with mail or DNS servers. The logs keeps track of all occurred network connection and protocol errors as well.

Logger class also supports logging into memory buffer instead of a file (useful for those ASP.NET applications which have no permissions to write to disk).

To prevent unlimited growth of the log file/memory buffer, the maximum size of the log can be restricted to certain value (see MaxSize property).

The developer has control of adding log messages. Each time the log entry is to be added into the log, MailBee components raise LogNewEntry event (see Smtp.LogNewEntry, Pop3.LogNewEntry, and Imap.LogNewEntry). Also, the developer can explicitly put new entries into the log using WriteLine(String) method.

Examples
This sample enables logging POP3 session into C:\Temp\pop3_log.txt file. The maximum size of the log file is restricted to 4 Kbytes. If the log file is going to exceed this size, it's renamed into C:\Temp\pop3_log-bak.txt, and new C:\Temp\pop3_log.txt log is started.
Note Note
If C:\Temp\pop3_log.txt gets full again, it's again renamed to C:\Temp\pop3_log-bak.txt (old C:\Temp\pop3_log-bak.txt contents will be lost). Thus, the log will always reflect the latest activity, however, older data may be lost.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();

// Set logging parameters.
pop.Log.Enabled = true;
pop.Log.Filename = @"C:\Temp\pop3_log.txt";
pop.Log.MaxSize = 4096;
pop.Log.OldFilename = @"C:\Temp\pop3_log-bak.txt";

// Download all message headers to produce some log messages.
pop.Connect("mail.domain.com");
pop.Login("user@domain.com", "password");
MailMessageCollection msgs = pop.DownloadMessageHeaders();
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3

' Set logging parameters.
pop.Log.Enabled = True
pop.Log.Filename = "C:\Temp\pop3_log.txt"
pop.Log.MaxSize = 4096
pop.Log.OldFilename = "C:\Temp\pop3_log-bak.txt"

' Download all message headers to produce some log messages.
pop.Connect("mail.domain.com")
pop.Login("user@domain.com", "password")

Dim msgs As MailMessageCollection
msgs = pop.DownloadMessageHeaders()
pop.Disconnect()
See Also

Reference

MailBee Namespace


Logger Methods

Logger Methods

The Logger type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Clears the log contents if logging is enabled.
Public method | ClearAsync | async/await version of Clear.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMemoryLog | Returns the string containing the memory log contents.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | WriteLine | Adds a new log entry containing user-defined message into the log.
Public method | WriteLineAsync | async/await version of WriteLine(String).
Top
See Also

Reference

Logger Class
MailBee Namespace


Logger.Clear Method

LoggerClear Method
Clears the log contents if logging is enabled.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear()
Public Sub Clear
Remarks
If memory logging is used (MemoryLog is true), the memory buffer length is set to 0. If file logging is used (MemoryLog is false), the log file denoted by Filename property value is cleared.
Note Note
In UWP apps, use async version of this method.
See Also

Reference

Logger Class
MailBee Namespace


Logger.ClearAsync Method

LoggerClearAsync Method
async/await version of Clear.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task ClearAsync()
Public Function ClearAsync As Task

Return Value

Type: Task
A task that represents the asynchronous operation.
See Also

Reference

Logger Class
MailBee Namespace


Logger.GetMemoryLog Method

LoggerGetMemoryLog Method
Returns the string containing the memory log contents.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetMemoryLog()
Public Function GetMemoryLog As String

Return Value

Type: String
The return value is the string containing the memory log contents if memory logging is enabled; otherwise, the return value is an empty string.
See Also

Reference

Logger Class
MailBee Namespace


Logger.WriteLine Method

LoggerWriteLine Method
Adds a new log entry containing user-defined message into the log.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void WriteLine(
    string messageText
)
Public Sub WriteLine (
    messageText As String
)

Parameters

messageText
Type: SystemString
The string to be added in the log as a part of the log entry.
Remarks

The developer can use this method to add custom messages in the log. These messages will be formatted to the same rules as any other messages placed into the log. However, MailBee components (such as Smtp, Pop3, and Imap) do not raise LogNewEntry event when the log entry is added using this method. This allows the developer to call this method even inside LogNewEntry event handlers without getting endless recursion in the code.

Entries added with WriteLine(String) method are marked as [USER] in the log (as compared to [INFO], [SEND], or [RECV] entries produced by MailBee itself).

Note Note
In UWP apps, use async version of this method.
Examples
This sample adds user-defined message into the file log.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();

// Set logging parameters.
pop.Log.Enabled = true;
pop.Log.Filename = @"C:\Temp\pop3_log.txt";
pop.Log.Clear();

// Print Hello.
pop.Log.WriteLine("Hello");

// After running this code, C:\Temp\pop3_log.txt file should look like below.
[00:05:34.79] [USER] Hello
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3

' Set logging parameters.
pop.Log.Enabled = True
pop.Log.Filename = "C:\Temp\pop3_log.txt"
pop.Log.Clear()

' Print Hello.
pop.Log.WriteLine("Hello")

' After running this code, C:\Temp\pop3_log.txt file should look like below.
[00:05:34.79] [USER] Hello
See Also

Reference

Logger Class
MailBee Namespace


Logger.WriteLineAsync Method

LoggerWriteLineAsync Method
async/await version of WriteLine(String).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task WriteLineAsync(
    string messageText
)
Public Function WriteLineAsync (
    messageText As String
) As Task

Parameters

messageText
Type: SystemString
The string to be added in the log as a part of the log entry.

Return Value

Type: Task
A task that represents the asynchronous operation.
See Also

Reference

Logger Class
MailBee Namespace


Logger Properties

Logger Properties

The Logger type exposes the following members.

Properties
 | Name | Description
Public property | DateTimeFormatFull | Gets or sets the format of full datetime string.
Public property | DateTimeFormatTimeOnly | Gets or sets the format of time-only string.
Public property | DisableOnException | Gets or sets whether the logging should be automatically disabled instead of throwing exception when logging error occurs.
Public property | Enabled | Gets or sets whether the logging into a file or memory buffer is enabled.
Public property | FileEncoding | Gets or sets Encoding to be used when writing into the log file.
Public property | Filename | Gets or sets the log file name.
Public property | Format | Gets or sets flags which specify formatting of log entries placed into the log.
Public property | HidePasswords | Gets or sets whether the actual password data may appear in the log or not.
Public property | KeepLogFileOpen | Gets or sets whether the log file must be kept open during MailBee session.
Public property | LogDnsQueryBody | Gets or sets whether DNS MX lookup query binary data must be added into the log.
Public property | MaxSize | Gets or sets the maximum allowed length (in characters) of the file or memory log.
Public property | MemoryLog | Gets or sets whether the logging must be performed into a log file or into a memory buffer.
Public property | OldFilename | Gets or sets the name of a backup file the log must be renamed into when its size exceeds the maximum allowed limit.
Public property | SyncRoot | Gets or sets the object to be used for synchronized access to the log file.
Top
See Also

Reference

Logger Class
MailBee Namespace


Logger.DateTimeFormatFull Property

LoggerDateTimeFormatFull Property
Gets or sets the format of full datetime string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DateTimeFormatFull { get; set; }
Public Property DateTimeFormatFull As String
    Get
    Set

Property Value

Type: String
The default value is "MM\/dd\/yyyy HH:mm:ss.ff".
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
Full datetime is used when Format value includes AddDate flag.
See Also

Reference

Logger Class
MailBee Namespace


Logger.DateTimeFormatTimeOnly Property

LoggerDateTimeFormatTimeOnly Property
Gets or sets the format of time-only string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DateTimeFormatTimeOnly { get; set; }
Public Property DateTimeFormatTimeOnly As String
    Get
    Set

Property Value

Type: String
The default value is "HH:mm:ss.ff".
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
Time-only datetime is used when Format value does not include AddDate flag.
See Also

Reference

Logger Class
MailBee Namespace


Logger.DisableOnException Property

LoggerDisableOnException Property
Gets or sets whether the logging should be automatically disabled instead of throwing exception when logging error occurs.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DisableOnException { get; set; }
Public Property DisableOnException As Boolean
    Get
    Set

Property Value

Type: Boolean
true if logging should be silently disabled when any logging error occurs; false if any logging error should cause an exception to be thrown. The default value is false.
Remarks
Since logging exists primarily for debug purposes, it's possible to tell MailBee to ignore errors which occur in logging itself. When DisableOnException is true, the developer can still determine if logging error occurred by examining Enabled property value. If it's now false, the logging error occurred and the logging was disabled.
See Also

Reference

Logger Class
MailBee Namespace


Logger.Enabled Property

LoggerEnabled Property
Gets or sets whether the logging into a file or memory buffer is enabled.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Enabled { get; set; }
Public Property Enabled As Boolean
    Get
    Set

Property Value

Type: Boolean
true if logging into a file or memory buffer is enabled; otherwise, false. The default value is false.
Remarks
Use logging only when it's needed. Logging is expensive operation, it might considerably degrade performance in some cases.
See Also

Reference

Logger Class
MailBee Namespace


Logger.FileEncoding Property

LoggerFileEncoding Property
Gets or sets Encoding to be used when writing into the log file.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding FileEncoding { get; set; }
Public Property FileEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the Encoding object specifying which character encoding to use when writing data into the log file. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
If log strings contain international characters which are replaced with ? characters in the log file, consider setting this property to the appropriate encoding (such as UTF8).
Note Note
This property is ignored when memory log is used (because no character-to-byte conversion needs to be performed for memory log).
See Also

Reference

Logger Class
MailBee Namespace


Logger.Filename Property

LoggerFilename Property
Gets or sets the log file name.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; set; }
Public Property Filename As String
    Get
    Set

Property Value

Type: String
The full path and file name of the log file. The default value is log.txt.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is an empty string or a null reference (Nothing in Visual Basic).
See Also

Reference

Logger Class
MailBee Namespace


Logger.Format Property

LoggerFormat Property
Gets or sets flags which specify formatting of log entries placed into the log.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public LogFormatOptions Format { get; set; }
Public Property Format As LogFormatOptions
    Get
    Set

Property Value

Type: LogFormatOptions
A LogFormatOptions value containing bitwise combination of flags specifying formatting of log entries placed into the log. The default value is None.
See Also

Reference

Logger Class
MailBee Namespace


Logger.HidePasswords Property

LoggerHidePasswords Property
Gets or sets whether the actual password data may appear in the log or not.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool HidePasswords { get; set; }
Public Property HidePasswords As Boolean
    Get
    Set

Property Value

Type: Boolean
true if passwords must be replaced with "********"-like patterns; false if password data must be preserved. The default value is true.
Remarks

Only unencrypted passwords get hidden. These include passwords used with regular POP3 or POP-before-SMTP authentications, SASL LOGIN, and SASL PLAIN authentication methods. Secure authentication methods (such as APOP or SASL NTLM) do not transmit passwords over the network, so the password data never appear in the log anyway.

The pattern to replace passwords is taken from PrivateDataCover value.

Caution note Caution
Setting this property to false may expose security problems. Anybody who has access to the log file might be able to see the actual password data which was trasmitted by the component to the mail server.
See Also

Reference

Logger Class
MailBee Namespace


Logger.KeepLogFileOpen Property

LoggerKeepLogFileOpen Property
Gets or sets whether the log file must be kept open during MailBee session.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool KeepLogFileOpen { get; set; }
Public Property KeepLogFileOpen As Boolean
    Get
    Set

Property Value

Type: Boolean
true if the component (such as Smtp, Pop3 or Imap) will keep the file open during the lifetime of the instance of the component); false if the component re-opens the log file and then closes it on each writing into the log. The default value is false.
Remarks
Keeping the log file open increases performance, although it's less reliable (operating system may cache log data so they might not be placed into the log if some kind of critical hardware or operating system error occurs). Also, the log contents won't be available for other applications while the log is still open.
Note Note
The developer can close the opened log (to make sure all the data is actually saved) just by setting KeepLogFileOpen to false. Then, KeepLogFileOpen can be set back to true if desired.
See Also

Reference

Logger Class
MailBee Namespace


Logger.LogDnsQueryBody Property

LoggerLogDnsQueryBody Property
Gets or sets whether DNS MX lookup query binary data must be added into the log.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LogDnsQueryBody { get; set; }
Public Property LogDnsQueryBody As Boolean
    Get
    Set

Property Value

Type: Boolean
true if log entries containing DNS MX lookup query data are added into the log; otherwise, false. The default value is false.
Remarks
The developer may set this property to true for debug purposes (for instance, to keep track of DNS queries sent by Smtp component in direct send mode.
See Also

Reference

Logger Class
MailBee Namespace


Logger.MaxSize Property

LoggerMaxSize Property
Gets or sets the maximum allowed length (in characters) of the file or memory log.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxSize { get; set; }
Public Property MaxSize As Integer
    Get
    Set

Property Value

Type: Int32
If value is a positive integer, it specifies the maximum length (in characters) of the log; if 0 or negative, the log size is unlimited. The default value is 0.
Remarks

This property can be set to prevent unlimited growth of the log file. When MaxSize is set to certain positive integer value, the log size will never exceed this value (unless it's not too small so that even one log entry would not fit).

If the memory log is used and the log size is going to exceed MaxSize value, the oldest half of the log is removed (the removal occurs on the entry boundaries so that individual entries are not splitted).

If the file log is used and the log size is going to exceed MaxSize value, the log file is renamed into OldFilename name and then cleared (or just cleared if OldFilename property is not set).

The developer may also call Clear method to clear the log.

Note Note
The log size limitation is a character count, not byte count. When using logging into a file, some characters can be converted into multi-byte sequences (especially, if UTF8 encoding is used), so that the log file size in bytes may get larger than MaxSize value.
See Also

Reference

Logger Class
MailBee Namespace


Logger.MemoryLog Property

LoggerMemoryLog Property
Gets or sets whether the logging must be performed into a log file or into a memory buffer.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MemoryLog { get; set; }
Public Property MemoryLog As Boolean
    Get
    Set

Property Value

Type: Boolean
true if logging is performed into the memory buffer; false if logging is performed into the file. The default value is false.
Remarks
To enable logging (either into memory or into a file), the logging itself must be enabled as well (Enabled property value must be set to true).
See Also

Reference

Logger Class
MailBee Namespace


Logger.OldFilename Property

LoggerOldFilename Property
Gets or sets the name of a backup file the log must be renamed into when its size exceeds the maximum allowed limit.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OldFilename { get; set; }
Public Property OldFilename As String
    Get
    Set

Property Value

Type: String
The full path and file name of a backup file the log must be renamed into when its size exceeds the limit set by MaxSize property value, or a null reference (Nothing in Visual Basic) to indicate no backup must be created. The default value is a null reference (the backup file won't be created).
Remarks
This property makes sense only when using logging into a file is enabled and MaxSize property value is non-zero (i.e. log size quota is on).
See Also

Reference

Logger Class
MailBee Namespace


Logger.SyncRoot Property

LoggerSyncRoot Property
Gets or sets the object to be used for synchronized access to the log file.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object SyncRoot { get; set; }
Public Property SyncRoot As Object
    Get
    Set

Property Value

Type: Object
A reference to the object to be used for synchronized access to the log file.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
The developer may need to set this value if the application is multi-threaded and there are multiple instances of MailBee components which attempt to write to the same log file. In this case, SyncRoot should be set to the same object reference for all such instances of MailBee components.
See Also

Reference

Logger Class
MailBee Namespace


LogMessageType Enumeration

LogMessageType Enumeration
Specifies the type of the log entry.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum LogMessageType
Public Enumeration LogMessageType
Members
Member name | Value | Description
Info | 0 | The log entry is an informational or error message.
Recv | 1 | The log entry contains data received from the network.
Send | 2 | The log entry contains data sent to the network.
User | 3 | This log entry is a result of WriteLine(String) method called by the application. MailBee itself never calls this method.
See Also

Reference

MailBee Namespace


OAuth Class

OAuth Class
This class provides methods for OAuth 1.0 authentication process.
Inheritance Hierarchy
SystemObject
MailBeeOAuth

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class OAuth
Public Class OAuth

The OAuth type exposes the following members.

Constructors
 | Name | Description
Public method | OAuth | Initializes a new instance of OAuth object with a consumer key pair.
Top
Methods
 | Name | Description
 | AccessToken(String, String) | Fetches Request Access from the specified URI
 | AccessToken(String, String, StringDictionary) | Fetches Request Access from the specified URI passing extra parameters in that URI.
 | AuthorizeToken(String) | Fetches Request Authorize from the specified URI (URL).
 | AuthorizeToken(String, StringDictionary) | Fetches Request Authorize from the specified URI passing extra parameters in that URI.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | GetXOAuthKey(String) | Fetches XOAuth key from the specified URI.
 | GetXOAuthKey(String, StringDictionary) | Fetches XOAuth key from the specified URI passing extra parameters in that URI.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | RequestToken(String) | Fetches Request Token from the specified URI.
 | RequestToken(String, StringDictionary) | Fetches Request Token from the specified URI passing extra parameters in that URI.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Fields
Name | Description
OAuthCallbackKey | The parameter name for setting callback URI.
Top
Properties
 | Name | Description
Public property | EnableOpenIDHybrid | Enables or disables OpenID + OAuth mode.
Public property | Token | Gets token key from OAuth provider.
Public property | TokenSecret | Gets token secret key from OAuth provider.
Top
Remarks
OAuth 1.0 is now considered deprecated. Use OAuth2 whenever possible. OAuth 2.0 in Windows and ASP.NET MVC apps guide provides lots of samples and detailed explanations on various aspects of OAuth 2.0 usage with Microsoft and Google providers.
Examples

Examples section contains several samples of using 2-legged and 3-legged OAuth with GMail IMAP and SMTP.

The first sample authenticates client in Gmail IMAP via 2-legged OAuth.

C#
VB
Copy
using System;
using System.Collections.Specialized;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        string consumerKey = "";
        string consumerSecret = "";
        string userEmail = "e-mail@gmail.com";

        OAuth myOAuth = new OAuth(consumerKey, consumerSecret);

        StringDictionary parameters = new StringDictionary();
        parameters.Add("xoauth_requestor_id", userEmail);

        // Get XOAuth key for IMAP.
        string imapXOAuthKey = myOAuth.GetXOAuthKey(
            string.Format("https://mail.google.com/mail/b/{0}/imap/", userEmail));

        // Last: Login to Gmail IMAP server using XOAuth.
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.gmail.com", 993);
        imp.Login(null, imapXOAuthKey, AuthenticationMethods.SaslOAuth, AuthenticationOptions.None, null);
        imp.SelectFolder("INBOX");

        // Processing of INBOX emails here.
        //...
        imp.Disconnect();
    }
}
Imports System
Imports System.Collections.Specialized
Imports MailBee
Imports MailBee.ImapMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim consumerKey As String = ""
        Dim consumerSecret As String = ""
        Dim userEmail As String = "e-mail@gmail.com"

        Dim myOAuth As OAuth = New OAuth(consumerKey, consumerSecret)

        Dim parameters As StringDictionary = New StringDictionary
        parameters.Add("xoauth_requestor_id", userEmail)

        ' Get XOAuth key for IMAP.
        Dim imapXOAuthKey As String = myOAuth.GetXOAuthKey( _
            String.Format("https://mail.google.com/mail/b/{0}/imap/", userEmail))

        ' Last: Login to Gmail IMAP server using XOAuth.
        Dim imp As Imap = New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.gmail.com", 993)
        imp.Login(Nothing, imapXOAuthKey, AuthenticationMethods.SaslOAuth, AuthenticationOptions.None, Nothing)
        imp.SelectFolder("INBOX")

        ' Processing of INBOX emails here.
        '...
        imp.Disconnect()
    End Sub
End Class
Examples
This sample authenticates client in Gmail IMAP via 3-legged OAuth with "anonymous" consumer key pairs. User may get registered his/her site for an e-mail account and specify keys from Google "Registration for Web Applications" page.
C#
VB
Copy
using System;
using System.Collections.Specialized;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Console.Write("Please enter your email: ");
        string userEmail = Console.ReadLine().Trim();

        OAuth myOAuth = new OAuth("anonymous", "anonymous");

        StringDictionary parameters = new StringDictionary();
        parameters.Add("scope", "https://mail.google.com/");
        parameters.Add(OAuth.OAuthCallbackKey, "oob");

        // First: Fetch Request Token
        myOAuth.RequestToken("https://www.google.com/accounts/OAuthGetRequestToken", parameters);

        // Second: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start(
            myOAuth.AuthorizeToken("https://www.google.com/accounts/OAuthAuthorizeToken"));

        Console.Write("Please enter the key: ");
        string key = Console.ReadLine().Trim();

        // Third: Fetch Access Token
        myOAuth.AccessToken("https://www.google.com/accounts/OAuthGetAccessToken", key);

        // Get XOAuth key for IMAP.
        string imapXOAuthKey = myOAuth.GetXOAuthKey(
            string.Format("https://mail.google.com/mail/b/{0}/imap/", userEmail));

        // Last: Login to Gmail IMAP server using XOAuth.
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.gmail.com", 993);
        imp.Login(null, imapXOAuthKey, AuthenticationMethods.SaslOAuth, AuthenticationOptions.None, null);
        imp.SelectFolder("INBOX");

        // Processing of INBOX emails here.
        //...
        imp.Disconnect();
    }
}
Imports System
Imports System.Collections.Specialized
Imports MailBee
Imports MailBee.ImapMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Console.Write("Please enter your email: ")
        Dim userEmail As String = Console.ReadLine().Trim()

        Dim myOAuth As OAuth = New OAuth("anonymous", "anonymous")

        Dim parameters As StringDictionary = New StringDictionary
        parameters.Add("scope", "https://mail.google.com/")
        parameters.Add(OAuth.OAuthCallbackKey, "oob")

        ' First: Fetch Request Token
        myOAuth.RequestToken("https://www.google.com/accounts/OAuthGetRequestToken", parameters)

        ' Second: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start( _
            myOAuth.AuthorizeToken("https://www.google.com/accounts/OAuthAuthorizeToken"))

        Console.Write("Please enter the key: ")
        Dim key As String = Console.ReadLine().Trim()

        ' Third: Fetch Access Token
        myOAuth.AccessToken("https://www.google.com/accounts/OAuthGetAccessToken", key)

        ' Get XOAuth key for IMAP.
        Dim imapXOAuthKey As String = myOAuth.GetXOAuthKey( _
            String.Format("https://mail.google.com/mail/b/{0}/imap/", userEmail))

        ' Last: Login to Gmail IMAP server using XOAuth.
        Dim imp As Imap = New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.gmail.com", 993)
        imp.Login(Nothing, imapXOAuthKey, AuthenticationMethods.SaslOAuth, AuthenticationOptions.None, Nothing)
        imp.SelectFolder("INBOX")

        ' Processing of INBOX emails here.
        '...
        imp.Disconnect()
    End Sub
End Class
Examples
This sample authenticates client in Gmail SMTP via 3-legged OAuth with "anonymous" consumer key pairs and sends e-mail message.
C#
VB
Copy
using System;
using System.Collections.Specialized;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Console.Write("Please enter your email: ");
        string userEmail = Console.ReadLine().Trim();

        OAuth myOAuth = new OAuth("anonymous", "anonymous");

        StringDictionary parameters = new StringDictionary();
        parameters.Add("scope", "https://mail.google.com/");
        parameters.Add(OAuth.OAuthCallbackKey, "oob");

        // First: Fetch Request Token
        myOAuth.RequestToken("https://www.google.com/accounts/OAuthGetRequestToken", parameters);

        // Second: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start(
            myOAuth.AuthorizeToken("https://www.google.com/accounts/OAuthAuthorizeToken"));

        Console.Write("Please enter the key: ");
        string key = Console.ReadLine().Trim();

        // Third: Fetch Access Token
        myOAuth.AccessToken("https://www.google.com/accounts/OAuthGetAccessToken", key);

        // Get XOAuth key for IMAP.
        string smtpXOAuthKey = myOAuth.GetXOAuthKey(
            string.Format("https://mail.google.com/mail/b/{0}/smtp/", userEmail));

        // Last: Login to Gmail SMTP server using XOAuth.

        // Connect to the server, login and send e-mail.
        SmtpServer server = new SmtpServer("smtp.gmail.com", 465, 0);
        server.AuthMethods = AuthenticationMethods.SaslOAuth;
        server.AccountName = null;
        server.Password = smtpXOAuthKey;

        Smtp mailer = new Smtp();

        mailer.From.AsString = userEmail;
        mailer.To.Add("e-mail@host.com");
        mailer.Subject = "My subject";
        mailer.BodyPlainText = "Text body";

        mailer.SmtpServers.Add(server);
        mailer.Send();
    }
}
Imports System
Imports System.Collections.Specialized
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Console.Write("Please enter your email: ")
        Dim userEmail As String = Console.ReadLine().Trim()

        Dim myOAuth As OAuth = New OAuth("anonymous", "anonymous")

        Dim parameters As StringDictionary = New StringDictionary
        parameters.Add("scope", "https://mail.google.com/")
        parameters.Add(OAuth.OAuthCallbackKey, "oob")

        ' First: Fetch Request Token
        myOAuth.RequestToken("https://www.google.com/accounts/OAuthGetRequestToken", parameters)

        ' Second: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start( _
            myOAuth.AuthorizeToken("https://www.google.com/accounts/OAuthAuthorizeToken"))

        Console.Write("Please enter the key: ")
        Dim key As String = Console.ReadLine().Trim()

        ' Third: Fetch Access Token
        myOAuth.AccessToken("https://www.google.com/accounts/OAuthGetAccessToken", key)

        ' Get XOAuth key for IMAP.
        Dim smtpXOAuthKey As String = myOAuth.GetXOAuthKey( _
            String.Format("https://mail.google.com/mail/b/{0}/smtp/", userEmail))

        ' Last: Login to Gmail SMTP server using XOAuth.

        ' Connect to the server, login and send e-mail.
        Dim server As SmtpServer = New SmtpServer("smtp.gmail.com", 465, 0)
        server.AuthMethods = AuthenticationMethods.SaslOAuth
        server.AccountName = Nothing
        server.Password = smtpXOAuthKey

        Dim mailer As Smtp = New Smtp

        mailer.From.AsString = userEmail
        mailer.To.Add("e-mail@host.com")
        mailer.Subject = "My subject"
        mailer.BodyPlainText = "Text body"

        mailer.SmtpServers.Add(server)
        mailer.Send()
    End Sub
End Class
Examples
This sample authenticates client in Yahoo OAuth with keys, received after application registration in Yahoo. See Yahoo! OAuth Quick Start Guide for additional information.
C#
VB
Copy
using System;
using System.Collections.Specialized;
using MailBee;

class Sample
{
    static void Main(string[] args)
    {
        string consumerKey = "";
        string consumerSecret = "";

        Console.Write("Please enter your email: ");
        string userEmail = Console.ReadLine().Trim();

        OAuth myOAuth = new OAuth(consumerKey, consumerSecret);

        StringDictionary parameters = new StringDictionary();
        parameters.Add(OAuth.OAuthCallbackKey, "oob");

        // First: Fetch Request Token
        myOAuth.RequestToken("https://api.login.yahoo.com/oauth/v2/get_request_token", parameters);

        // Second: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start(
            myOAuth.AuthorizeToken("https://api.login.yahoo.com/oauth/v2/request_auth"));

        Console.Write("Please enter the key: ");
        string key = Console.ReadLine().Trim();

        // Third: Fetch Access Token
        myOAuth.AccessToken("https://api.login.yahoo.com/oauth/v2/get_token", key);

        Console.WriteLine("Token: " + myOAuth.Token);
        Console.WriteLine("Token Secret: " + myOAuth.TokenSecret);
        Console.ReadLine();
    }
}
Imports System.Collections.Specialized
Imports MailBee

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim consumerKey As String = ""
        Dim consumerSecret As String = ""

        Console.Write("Please enter your email: ")
        Dim userEmail As String = Console.ReadLine().Trim()

        Dim myOAuth As OAuth = New OAuth(consumerKey, consumerSecret)

        Dim parameters As StringDictionary = New StringDictionary
        parameters.Add(OAuth.OAuthCallbackKey, "oob")

        ' First: Fetch Request Token
        myOAuth.RequestToken("https://api.login.yahoo.com/oauth/v2/get_request_token", parameters)

        ' Second: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start( _
         myOAuth.AuthorizeToken("https://api.login.yahoo.com/oauth/v2/request_auth"))

        Console.Write("Please enter the key: ")
        Dim key As String = Console.ReadLine().Trim()

        ' Third: Fetch Access Token
        myOAuth.AccessToken("https://api.login.yahoo.com/oauth/v2/get_token", key)

        Console.WriteLine("Token: " + myOAuth.Token)
        Console.WriteLine("Token Secret: " + myOAuth.TokenSecret)
        Console.ReadLine()
    End Sub
End Class
See Also

Reference

MailBee Namespace


OAuth Constructor

OAuth Constructor
Initializes a new instance of OAuth object with a consumer key pair.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public OAuth(
    string consumerKey,
    string consumerSecret
)
Public Sub New (
    consumerKey As String,
    consumerSecret As String
)

Parameters

consumerKey
Type: SystemString
A string value with a consumer public key.
consumerSecret
Type: SystemString
A string value with a consumer secret key.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | consumerKey or consumerSecret is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
For GMail 3-legged IMAP/SMTP OAuth you can use "anonymous", "anonymous" key pair or get a registered site for an e-mail account and specify the keys from Google "Registration for Web Applications" page. For GMail 2-legged OAuth you should register and get key pair from Google.
See Also

Reference

OAuth Class
MailBee Namespace


OAuth Fields

OAuth Fields

The OAuth type exposes the following members.

Fields
Name | Description
OAuthCallbackKey | The parameter name for setting callback URI.
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.OAuthCallbackKey Field

OAuthOAuthCallbackKey Field
The parameter name for setting callback URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string OAuthCallbackKey
Public Const OAuthCallbackKey As String

Field Value

Type: String
See Also

Reference

OAuth Class
MailBee Namespace


OAuth Methods

OAuth Methods

The OAuth type exposes the following members.

Methods
 | Name | Description
 | AccessToken(String, String) | Fetches Request Access from the specified URI
 | AccessToken(String, String, StringDictionary) | Fetches Request Access from the specified URI passing extra parameters in that URI.
 | AuthorizeToken(String) | Fetches Request Authorize from the specified URI (URL).
 | AuthorizeToken(String, StringDictionary) | Fetches Request Authorize from the specified URI passing extra parameters in that URI.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | GetXOAuthKey(String) | Fetches XOAuth key from the specified URI.
 | GetXOAuthKey(String, StringDictionary) | Fetches XOAuth key from the specified URI passing extra parameters in that URI.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | RequestToken(String) | Fetches Request Token from the specified URI.
 | RequestToken(String, StringDictionary) | Fetches Request Token from the specified URI passing extra parameters in that URI.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.AccessToken Method

OAuthAccessToken Method
Fetches Access Token from the specified URI.
Overload List
Name | Description
AccessToken(String, String) | Fetches Request Access from the specified URI
AccessToken(String, String, StringDictionary) | Fetches Request Access from the specified URI passing extra parameters in that URI.
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.AccessToken Method (String, String)

OAuthAccessToken Method (String, String)
Fetches Request Access from the specified URI

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AccessToken(
    string uri,
    string key
)
Public Sub AccessToken (
    uri As String,
    key As String
)

Parameters

uri
Type: SystemString
A URI for sending HTTP request.
key
Type: SystemString
A string with the verification code from the end user's browser authentication process.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri or key is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeDataParsingException | A URI has incorrect format.
MailBeeStreamException | A stream error occurred.
MailBeeWebException | HTTP connection error occurred.
MailBeeInvalidStateException | AuthorizeToken(String) should be called first.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
AccessToken Overload
MailBee Namespace


OAuth.AccessToken Method (String, String, StringDictionary)

OAuthAccessToken Method (String, String, StringDictionary)
Fetches Request Access from the specified URI passing extra parameters in that URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AccessToken(
    string uri,
    string key,
    StringDictionary parameters
)
Public Sub AccessToken (
    uri As String,
    key As String,
    parameters As StringDictionary
)

Parameters

uri
Type: SystemString
An URI for sending HTTP request.
key
Type: SystemString
A string with the verification code from the end user's browser authentication process.
parameters
Type: System.Collections.SpecializedStringDictionary
A StringDictionary object with the parameters list.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri or key is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeDataParsingException | A URI has incorrect format.
MailBeeStreamException | A stream error occurred.
MailBeeWebException | HTTP connection error occurred.
MailBeeInvalidStateException | AuthorizeToken(String) should be called first.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
AccessToken Overload
MailBee Namespace


OAuth.AuthorizeToken Method

OAuthAuthorizeToken Method
Fetches Authorize Token from the specified URI.
Overload List
Name | Description
AuthorizeToken(String) | Fetches Request Authorize from the specified URI (URL).
AuthorizeToken(String, StringDictionary) | Fetches Request Authorize from the specified URI passing extra parameters in that URI.
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.AuthorizeToken Method (String)

OAuthAuthorizeToken Method (String)
Fetches Request Authorize from the specified URI (URL).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AuthorizeToken(
    string uri
)
Public Function AuthorizeToken (
    uri As String
) As String

Parameters

uri
Type: SystemString
A URI for producing HTTP request string.

Return Value

Type: String
A string with the URI for authentication process in the end user's browser.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeInvalidStateException | RequestToken(String) should be called first.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
AuthorizeToken Overload
MailBee Namespace


OAuth.AuthorizeToken Method (String, StringDictionary)

OAuthAuthorizeToken Method (String, StringDictionary)
Fetches Request Authorize from the specified URI passing extra parameters in that URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AuthorizeToken(
    string uri,
    StringDictionary parameters
)
Public Function AuthorizeToken (
    uri As String,
    parameters As StringDictionary
) As String

Parameters

uri
Type: SystemString
A URI for producing HTTP request string.
parameters
Type: System.Collections.SpecializedStringDictionary
A StringDictionary object with the parameters list.

Return Value

Type: String
A string with URI for authentication process in client browser.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeInvalidStateException | RequestToken(String) should be called first.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
AuthorizeToken Overload
MailBee Namespace


OAuth.GetXOAuthKey Method

OAuthGetXOAuthKey Method
Fetches XOAuth Key from the specified URI for IMAP/SMTP authentication.
Overload List
Name | Description
GetXOAuthKey(String) | Fetches XOAuth key from the specified URI.
GetXOAuthKey(String, StringDictionary) | Fetches XOAuth key from the specified URI passing extra parameters in that URI.
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.GetXOAuthKey Method (String)

OAuthGetXOAuthKey Method (String)
Fetches XOAuth key from the specified URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetXOAuthKey(
    string uri
)
Public Function GetXOAuthKey (
    uri As String
) As String

Parameters

uri
Type: SystemString
An URI for producing XOAuth key string.

Return Value

Type: String
A string with URI for XOAuth authentication process for IMAP/SMTP.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
GetXOAuthKey Overload
MailBee Namespace


OAuth.GetXOAuthKey Method (String, StringDictionary)

OAuthGetXOAuthKey Method (String, StringDictionary)
Fetches XOAuth key from the specified URI passing extra parameters in that URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetXOAuthKey(
    string uri,
    StringDictionary parameters
)
Public Function GetXOAuthKey (
    uri As String,
    parameters As StringDictionary
) As String

Parameters

uri
Type: SystemString
A URI for producing XOAuth key string.
parameters
Type: System.Collections.SpecializedStringDictionary
A StringDictionary object with parameters list.

Return Value

Type: String
A string with the URI for XOAuth authentication process for IMAP/SMTP.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
The return value of this method is what you then supply as a password when calling Login method of IMAP or SMTP component. Moreover, this value can be used not only with MailBee, you can pass it as OAuth key to any implementation of XOAUTH authentication.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
GetXOAuthKey Overload
MailBee Namespace


OAuth.RequestToken Method

OAuthRequestToken Method
Fetches Request Token from the specified URI.
Overload List
Name | Description
RequestToken(String) | Fetches Request Token from the specified URI.
RequestToken(String, StringDictionary) | Fetches Request Token from the specified URI passing extra parameters in that URI.
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.RequestToken Method (String)

OAuthRequestToken Method (String)
Fetches Request Token from the specified URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RequestToken(
    string uri
)
Public Sub RequestToken (
    uri As String
)

Parameters

uri
Type: SystemString
An URI (URL) for sending HTTP request.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeDataParsingException | An URI has incorrect format.
MailBeeStreamException | A stream error occurred.
MailBeeWebException | HTTP connection error occurred.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
RequestToken Overload
MailBee Namespace


OAuth.RequestToken Method (String, StringDictionary)

OAuthRequestToken Method (String, StringDictionary)
Fetches Request Token from the specified URI passing extra parameters in that URI.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RequestToken(
    string uri,
    StringDictionary parameters
)
Public Sub RequestToken (
    uri As String,
    parameters As StringDictionary
)

Parameters

uri
Type: SystemString
An URI for sending HTTP request.
parameters
Type: System.Collections.SpecializedStringDictionary
A StringDictionary object with the parameters list.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeDataParsingException | An URI has incorrect format.
MailBeeStreamException | A stream error occurred.
MailBeeWebException | HTTP connection error occurred.
Examples
See OAuth topic for the example.
See Also

Reference

OAuth Class
RequestToken Overload
MailBee Namespace


OAuth Properties

OAuth Properties

The OAuth type exposes the following members.

Properties
 | Name | Description
Public property | EnableOpenIDHybrid | Enables or disables OpenID + OAuth mode.
Public property | Token | Gets token key from OAuth provider.
Public property | TokenSecret | Gets token secret key from OAuth provider.
Top
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.EnableOpenIDHybrid Property

OAuthEnableOpenIDHybrid Property
Enables or disables OpenID + OAuth mode.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EnableOpenIDHybrid { get; set; }
Public Property EnableOpenIDHybrid As Boolean
    Get
    Set

Property Value

Type: Boolean
The default value is false which means that OpenID + OAuth mode is disabled.
Remarks
This mode should be enabled for using with OpenID class.
See Also

Reference

OAuth Class
MailBee Namespace
MailBeeOpenID


OAuth.Token Property

OAuthToken Property
Gets token key from OAuth provider.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Token { get; }
Public ReadOnly Property Token As String
    Get

Property Value

Type: String
A string with token key.
See Also

Reference

OAuth Class
MailBee Namespace


OAuth.TokenSecret Property

OAuthTokenSecret Property
Gets token secret key from OAuth provider.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TokenSecret { get; }
Public ReadOnly Property TokenSecret As String
    Get

Property Value

Type: String
A string with token secret key.
See Also

Reference

OAuth Class
MailBee Namespace


OAuth2 Class

OAuth2 Class
This class provides methods for OAuth 2.0 authentication process.
Inheritance Hierarchy
SystemObject
MailBeeOAuth2

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class OAuth2
Public Class OAuth2

The OAuth2 type exposes the following members.

Constructors
 | Name | Description
Public method | OAuth2 | Initializes a new instance of OAuth2 object with a client key pair.
Top
Methods
 | Name | Description
 | AuthorizeToken | Fetches Request Authorize from the specified URI (URL).
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | GetXOAuthKey | Fetches XOAuth key for the specified e-mail address.
 | GetXOAuthKeyStatic | The version of GetXOAuthKey(String, String) which does not require you to create an instance of OAuth2 class.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Fields
Name | Description
ClientIdKey | The name of Client-ID-Key parameter.
RedirectUriKey | The name of Redirect-Uri-Key parameter.
ResponseTypeKey | The name of Response-Type-Key parameter.
Scope | The name of Scope parameter.
Top
Remarks

OAuth enables websites or applications to access users' mailboxes and profile data without requiring users to disclose their credentials to these web sites or applications. It means that a 3d party application doesn't need to get the username and the password to access data via API from the restricted application.

For instance, your application can ask the user to authorize its attempt to access data in their Gmail or Outlook.com mailbox. MailBee provides your application with the URL on Google or Microsoft web site which should be opened in the browser. The page asks the user if they confirm that your application is trusted to access their mailbox. If the user confirms that, Google or Microsoft returns the authorization key. The application then use this key to get an access token from Google or Microsoft server, and then you can then use it with OAuth 2.0 method when logging in Gmail or Microsoft account of the user. The same will work for any OAuth 2.0 capable provider which supports XOAUTH2 extension in their IMAP or SMTP service.

The methods of this class help you complete OAuth 2.0 authorization process and get OAuth keys which can be used for authentication on IMAP/SMTP servers that support XOAUTH2 extension. You can also use this class to get OAuth 2.0 keys for other purposes with any software capable of OAuth 2.0 authentication because the produced keys are not specific to MailBee.

Note Note
You can refer to OAuth 2.0 in Windows and ASP.NET MVC apps topic for detailed tutorials on using OAuth 2.0 with Outlook.com, Live.com, Hotmail.com, Gmail (including Google Apps specific case, Service Accounts). The tutorials cover many related aspects such as refresh tokens, passing OAuth authorization code from OAuth providers' web sites to the application, IIS configuration, etc.
Examples

This sample authenticates client in Gmail IMAP via OAuth 2.0 using DotNetOpenAuth library (.NET 3.5+). User should get registered their application as described here: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth and specify the keys received from Google in the application code (clientID and clientSecret variables) along with their e-mail address. The keys can be generated in Google Developers Console at https://console.developers.google.com, where you select your project and then "APIs & auth" / "Credentials".

Another and better way of doing OAuth 2.0 with Google is using Google API Auth Client library described in OAuth 2.0 for Google Regular Accounts (installed applications) tutorial. Note that Google API requires .NET 4.0 or higher. You can find the example at GetXOAuthKeyStatic(String, String) topic.

C#
VB
Copy
using System;
using System.Collections.Specialized;
using MailBee;
using MailBee.ImapMail;
using DotNetOpenAuth.OAuth2;

class Sample
{
    static string GetAccessToken(string clientID, string clientSecret, string key)
    {
        UserAgentClient consumer;
        IAuthorizationState grantedAccess;

        // Second: Fetch Access Token
        StringDictionary parameters2 = new StringDictionary();
        parameters2.Add(OAuth2.RedirectUriKey, "urn:ietf:wg:oauth:2.0:oob");

        string uri = "https://accounts.google.com/o/oauth2/token";

        AuthorizationServerDescription server = new AuthorizationServerDescription();
        server.TokenEndpoint = new Uri(uri);
        server.ProtocolVersion = ProtocolVersion.V20;

        consumer = new UserAgentClient(server, clientID, clientSecret);

        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);

        IAuthorizationState authorizationState = new AuthorizationState(null);

        if (parameters2.ContainsKey(OAuth2.RedirectUriKey))
        {
            authorizationState.Callback = new Uri(parameters2[OAuth2.RedirectUriKey]);
        }

        // Build a generic URL containing the auth code.
        // This is done here as we cannot modify the DotNetOpenAuth library
        // and the underlying method only allows parsing an URL as a method
        // of retrieving the AuthorizationState.
        string url = "http://example.com/?code=" + key;

        try
        {
            grantedAccess = consumer.ProcessUserAuthorization(new Uri(url), authorizationState);
        }
        catch (DotNetOpenAuth.Messaging.ProtocolException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }

        return grantedAccess.AccessToken;
    }

    static void Main(string[] args)
    {
        string clientID = "somewhat like 628470012345.apps.googleusercontent.com";
        string clientSecret = "somewhat like 8IbRSofadFQ7ThjClxp8GBa2";
        string userEmail = "john.doe@gmail.com";

        OAuth2 myOAuth2 = new OAuth2(clientID, clientSecret);

        StringDictionary parameters1 = new StringDictionary();
        parameters1.Add(OAuth2.Scope, "https://mail.google.com/");
        parameters1.Add(OAuth2.RedirectUriKey, "urn:ietf:wg:oauth:2.0:oob");
        parameters1.Add(OAuth2.ResponseTypeKey, "code");

        // First: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start(
            myOAuth2.AuthorizeToken("https://accounts.google.com/o/oauth2/auth", parameters1));

        Console.Write("Please enter the Authorization key from Google: ");
        string key = Console.ReadLine().Trim();

        // Second: Fetch Access Token
        string accessToken = GetAccessToken(clientID, clientSecret, key);
        if (accessToken == null)
        {
            return;
        }

        // Get XOAuth key for IMAP.
        string imapXOAuthKey = myOAuth2.GetXOAuthKey(userEmail, accessToken);

        Imap imp = new Imap();

        // In the log, you can find the actual search queries sent to the server.
        imp.Log.Filename = "C:\\Temp\\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        imp.Connect("imap.gmail.com", 993);
        imp.Login(null, imapXOAuthKey, AuthenticationMethods.SaslOAuth2, AuthenticationOptions.None, null);
        imp.SelectFolder("INBOX");

        Console.WriteLine(imp.MessageCount.ToString() + " message(s) in INBOX");

        imp.Disconnect();
    }
}
Imports System.Collections.Specialized
Imports MailBee
Imports MailBee.ImapMail
Imports DotNetOpenAuth.OAuth2

Class Sample
    Shared Function GetAccessToken(clientID As String, clientSecret As String, key As String) As String
        Dim consumer As UserAgentClient
        Dim grantedAccess As IAuthorizationState

        ' Second: Fetch Access Token
        Dim parameters2 As New StringDictionary()
        parameters2.Add(OAuth2.RedirectUriKey, "urn:ietf:wg:oauth:2.0:oob")

        Dim uri As String = "https://accounts.google.com/o/oauth2/token"

        Dim server As New AuthorizationServerDescription
        With server
            .TokenEndpoint = New Uri(uri)
            .ProtocolVersion = ProtocolVersion.V20
        End With

        consumer = New UserAgentClient(server, clientID, clientSecret)

        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret)

        Dim authorizationState As IAuthorizationState = New AuthorizationState(Nothing)

        If parameters2.ContainsKey(OAuth2.RedirectUriKey) Then
            authorizationState.Callback = New Uri(parameters2(OAuth2.RedirectUriKey))
        End If

        ' Build a generic URL containing the auth code.
        ' This is done here as we cannot modify the DotNetOpenAuth library
        ' and the underlying method only allows parsing an URL as a method
        ' of retrieving the AuthorizationState.
        Dim url As String = "http://example.com/?code=" & key

        Try
            grantedAccess = consumer.ProcessUserAuthorization(New Uri(url), authorizationState)
        Catch e As DotNetOpenAuth.Messaging.ProtocolException
            Console.WriteLine(e.Message)
            Return Nothing
        End Try

        Return grantedAccess.AccessToken
    End Function

    Shared Sub Main()
        Dim clientID As String = "somewhat like 628470012345.apps.googleusercontent.com"
        Dim clientSecret As String = "somewhat like 8IbRSofadFQ7ThjClxp8GBa2"
        Dim userEmail As String = "john.doe@gmail.com"

        Dim myOAuth2 As New OAuth2(clientID, clientSecret)

        Dim parameters1 As New StringDictionary()
        parameters1.Add(OAuth2.Scope, "https://mail.google.com/")
        parameters1.Add(OAuth2.RedirectUriKey, "urn:ietf:wg:oauth:2.0:oob")
        parameters1.Add(OAuth2.ResponseTypeKey, "code")

        ' First: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start(myOAuth2.AuthorizeToken("https://accounts.google.com/o/oauth2/auth", parameters1))

        Console.Write("Please enter the Authorization key from Google: ")
        Dim key As String = Console.ReadLine().Trim()

        ' Second: Fetch Access Token
        Dim accessToken As String = GetAccessToken(clientID, clientSecret, key)
        If accessToken Is Nothing Then
            Return
        End If

        ' Get XOAuth key for IMAP.
        Dim imapXOAuthKey As String = myOAuth2.GetXOAuthKey(userEmail, accessToken)

        Dim imp As New Imap()

        ' In the log, you can find the actual search queries sent to the server.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        imp.Connect("imap.gmail.com", 993)
        imp.Login(Nothing, imapXOAuthKey, AuthenticationMethods.SaslOAuth2, AuthenticationOptions.None, Nothing)
        imp.SelectFolder("INBOX")

        Console.WriteLine(imp.MessageCount.ToString() & " message(s) in INBOX")

        imp.Disconnect()
    End Sub
End Class
See Also

Reference

MailBee Namespace


OAuth2 Constructor

OAuth2 Constructor
Initializes a new instance of OAuth2 object with a client key pair.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public OAuth2(
    string clientId,
    string clientSecret
)
Public Sub New (
    clientId As String,
    clientSecret As String
)

Parameters

clientId
Type: SystemString
A string value with a client public Id.
clientSecret
Type: SystemString
A string value with a client secret key.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | clientId or clientSecret is a null reference (Nothing in Visual Basic) or an empty string.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2 Fields

OAuth2 Fields

The OAuth2 type exposes the following members.

Fields
Name | Description
ClientIdKey | The name of Client-ID-Key parameter.
RedirectUriKey | The name of Redirect-Uri-Key parameter.
ResponseTypeKey | The name of Response-Type-Key parameter.
Scope | The name of Scope parameter.
Top
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.ClientIdKey Field

OAuth2ClientIdKey Field
The name of Client-ID-Key parameter.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string ClientIdKey
Public Const ClientIdKey As String

Field Value

Type: String
"client_id" string.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.RedirectUriKey Field

OAuth2RedirectUriKey Field
The name of Redirect-Uri-Key parameter.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string RedirectUriKey
Public Const RedirectUriKey As String

Field Value

Type: String
"redirect_uri" string.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.ResponseTypeKey Field

OAuth2ResponseTypeKey Field
The name of Response-Type-Key parameter.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string ResponseTypeKey
Public Const ResponseTypeKey As String

Field Value

Type: String
"response_type" string.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.Scope Field

OAuth2Scope Field
The name of Scope parameter.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string Scope
Public Const Scope As String

Field Value

Type: String
"scope" string.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2 Methods

OAuth2 Methods

The OAuth2 type exposes the following members.

Methods
 | Name | Description
 | AuthorizeToken | Fetches Request Authorize from the specified URI (URL).
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | GetXOAuthKey | Fetches XOAuth key for the specified e-mail address.
 | GetXOAuthKeyStatic | The version of GetXOAuthKey(String, String) which does not require you to create an instance of OAuth2 class.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.AuthorizeToken Method

OAuth2AuthorizeToken Method
Fetches Request Authorize from the specified URI (URL).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AuthorizeToken(
    string uri,
    StringDictionary parameters
)
Public Function AuthorizeToken (
    uri As String,
    parameters As StringDictionary
) As String

Parameters

uri
Type: SystemString
An URI for sending HTTP request.
parameters
Type: System.Collections.SpecializedStringDictionary
A StringDictionary object with the parameters' list.

Return Value

Type: String
A string with the URI for authentication process in the end user's browser.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uri is a null reference (Nothing in Visual Basic) or an empty string. parameters is a null reference (Nothing in Visual Basic) or an empty string.
Examples
See OAuth2 topic for the example.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.GetXOAuthKey Method

OAuth2GetXOAuthKey Method
Fetches XOAuth key for the specified e-mail address.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetXOAuthKey(
    string email,
    string accessToken
)
Public Function GetXOAuthKey (
    email As String,
    accessToken As String
) As String

Parameters

email
Type: SystemString
E-mail address, like user@domain.com.
accessToken
Type: SystemString
Access token (GetAccessToken method in the code example creates it).

Return Value

Type: String
A string with URI for XOAuth authentication process for IMAP/SMTP.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email or accessToken is a null reference (Nothing in Visual Basic) or an empty string.
Examples
See OAuth2 topic for the example.
See Also

Reference

OAuth2 Class
MailBee Namespace


OAuth2.GetXOAuthKeyStatic Method

OAuth2GetXOAuthKeyStatic Method
The version of GetXOAuthKey(String, String) which does not require you to create an instance of OAuth2 class.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetXOAuthKeyStatic(
    string email,
    string accessToken
)
Public Shared Function GetXOAuthKeyStatic (
    email As String,
    accessToken As String
) As String

Parameters

email
Type: SystemString
E-mail address, like user@domain.com.
accessToken
Type: SystemString
Access token.

Return Value

Type: String
A string with URI for XOAUTH2 authentication process for IMAP/SMTP.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email or accessToken is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
When using Google API Auth Client library, the only required method of OAuth2 class is GetXOAuthKeyStatic(String, String), you don't need to use other methods of this class. For that purpose, this static (Shared in Visual Basic) version exists.
Examples

Two samples in this topic. You can find more samples and explanations in OAuth 2.0 in Windows and ASP.NET MVC apps guide.

The first sample performs OAUTH2 authentication using Google Service accounts (common method for Google Apps). You'll need to reference Google API Auth Client library (with NuGet). Note that at least .NET 4.0 is required for this library.

C#
VB
Copy
using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using MailBee;
using MailBee.ImapMail;

public class Program
{
    public static void Main(string[] args)
    {
        String serviceAccountEmail = "88...-...7j@developer.gserviceaccount.com";
        string userEmail = "user@some-googleapps-domain.com";

        var certificate = new X509Certificate2(@"C:\Temp\a...0-privatekey.p12",
            "secret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            User = userEmail,
            Scopes = new[] { "https://mail.google.com/" }
        }.FromCertificate(certificate));

        if (credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
        {
            string imapXOAuthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

            Imap imp = new Imap();

            // Logging is not necessary but useful for debugging.
            imp.Log.Enabled = true;
            imp.Log.Filename = @"C:\Temp\log.txt";
            imp.Log.Clear();

            imp.Connect("imap.gmail.com");
            imp.Login(userEmail, imapXOAuthKey, AuthenticationMethods.SaslOAuth2,
                AuthenticationOptions.None, null);
            imp.SelectFolder("Inbox");
            imp.Disconnect();
        }
    }
}
Imports System.Security.Cryptography.X509Certificates
Imports Google.Apis.Auth.OAuth2
Imports MailBee
Imports MailBee.ImapMail

Public Class Program
    Public Shared Sub Main(args As String())
        Dim serviceAccountEmail As String = "88...-...7j@developer.gserviceaccount.com"
        Dim userEmail As String = "user@some-googleapps-domain.com"

        Dim certificate = New X509Certificate2("C:\Temp\a...0-privatekey.p12", _
            "secret", X509KeyStorageFlags.Exportable)

        Dim credential As New ServiceAccountCredential(
            New ServiceAccountCredential.Initializer(serviceAccountEmail) With { _
            .User = userEmail, _
            .Scopes = New String() {"https://mail.google.com/"} _
        }.FromCertificate(certificate))

        If credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result Then
            Dim imapXOAuthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

            Dim imp As New Imap()

            ' Logging is not necessary but useful for debugging.
            imp.Log.Enabled = True
            imp.Log.Filename = "C:\Temp\log.txt"
            imp.Log.Clear()

            imp.Connect("imap.gmail.com")
            imp.Login(userEmail, imapXOAuthKey, AuthenticationMethods.SaslOAuth2, _
                AuthenticationOptions.None, Nothing)
            imp.SelectFolder("Inbox")
            imp.Disconnect()
        End If
    End Sub
End Class
The second sample connects to a regular Google account. In its IMAP part, it's similar to the sample in OAuth2 topic but uses Google API Auth Client library instead of DotNetOpenAuth.dll. The key advantage is that no user input is required (copy-paste from the browser to the console). Also, it shows OAuth2 usage with SMTP, not just IMAP.
C#
VB
Copy
using System;
using Google.Apis.Auth.OAuth2;
using MailBee;
using MailBee.ImapMail;
using MailBee.SmtpMail;

public class Program
{
    public static void Main(string[] args)
    {
        string userEmail = "john.doe@gmail.com";

        UserCredential credential;
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets
            {
                ClientId = "somewhat like 628470012345.apps.googleusercontent.com",
                ClientSecret = "somewhat like 8IbRSofadFQ7ThjClxp8GBa2"
            },
            new[] { "https://mail.google.com/" },
            "user",
            System.Threading.CancellationToken.None).Result;

        string xoauthKey = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken);

        bool useImap = true; // Set to false to use SMTP instead of IMAP.

        if (useImap)
        {
            Imap imp = new Imap();

            // Logging is not necessary but useful for debugging.
            imp.Log.Enabled = true;
            imp.Log.Filename = @"C:\Temp\log.txt";
            imp.Log.Clear();

            imp.Connect("imap.gmail.com");
            imp.Login(userEmail, xoauthKey, AuthenticationMethods.SaslOAuth2,
                AuthenticationOptions.None, null);
            imp.SelectFolder("Inbox");
            imp.Disconnect();
            Console.WriteLine("SUCCEEDED");
        }
        else
        {
            Smtp mailer = new Smtp();
            mailer.SmtpServers.Add("smtp.gmail.com", userEmail, xoauthKey, AuthenticationMethods.SaslOAuth2);

            // Logging is not necessary but useful for debugging.
            mailer.Log.Enabled = true;
            mailer.Log.Filename = @"C:\Temp\log.txt";
            mailer.Log.Clear();

            mailer.From.Email = userEmail;
            mailer.To.Add(userEmail);
            mailer.Subject = "empty email to myself";

            mailer.Send();
        }
    }
}
Imports System.Security.Cryptography.X509Certificates
Imports Google.Apis.Auth.OAuth2
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail

Public Class Program
    Public Shared Sub Main(args As String())
        Dim userEmail As String = "john.doe@gmail.com"

        Dim credential As UserCredential
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With { _
                .ClientId = "somewhat like 628470012345.apps.googleusercontent.com", _
                .ClientSecret = "somewhat like 8IbRSofadFQ7ThjClxp8GBa2" _
            }, New String() {"https://mail.google.com/"}, "user", _
            System.Threading.CancellationToken.None).Result

        Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

        Dim useImap As Boolean = True ' Set to false to use SMTP instead of IMAP.
        If useImap Then
            Dim imp As New Imap()

            ' Logging is not necessary but useful for debugging.
            imp.Log.Enabled = True
            imp.Log.Filename = "C:\Temp\log.txt"
            imp.Log.Clear()

            imp.Connect("imap.gmail.com")
            imp.Login(userEmail, xoauthKey, AuthenticationMethods.SaslOAuth2, _
                AuthenticationOptions.None, Nothing)
            imp.SelectFolder("Inbox")
            imp.Disconnect()
            Console.WriteLine("SUCCEEDED")
        Else
            Dim mailer As New Smtp()
            mailer.SmtpServers.Add("smtp.gmail.com", userEmail, xoauthKey, _
                AuthenticationMethods.SaslOAuth2)

            ' Logging is not necessary but useful for debugging.
            mailer.Log.Enabled = True
            mailer.Log.Filename = "C:\Temp\log.txt"
            mailer.Log.Clear()

            mailer.From.Email = userEmail
            mailer.To.Add(userEmail)
            mailer.Subject = "empty email to myself"

            mailer.Send()
        End If
    End Sub
End Class
See Also

Reference

OAuth2 Class
MailBee Namespace


OpenID Class

OpenID Class

Note: This API is now obsolete.

This class provides methods for OpenID authentication process. It can be used with OAuth class for hybrid OpenID + OAuth authentication.
Inheritance Hierarchy
SystemObject
MailBeeOpenID

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This class is now obsolete as OpenID technology itself.")]
public class OpenID
<ObsoleteAttribute("This class is now obsolete as OpenID technology itself.")>
Public Class OpenID

The OpenID type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetOpenIDServer | Gets OpenID server URI from OpenID URI string.
 | GetParamsForGoogleOpenIdWithOAuth | Creates a collection with OpenID request parameters for Google OpenID + OAuth.
 | GetParamsForYahooOpenIdWithOAuth | Creates a collection with OpenID requests for Yahoo OpenID + OAuth.
 | GetRedirectURL | Gets the URL on an OpenID server where your web application should redirect the user's browser to.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Remarks

OpenID + OAuth hybrid method makes it possible to access certain data (like e-mails) in the user account without requiring the user to enter their e-mail address and password, provided that the user is already logged into their account by other means.

For instance, if the user is logged in their Gmail account on that computer and the user accesses your web application, it can get access to the e-mails in that account if the user permits this. The user just needs to click a button (confirmation from Google to grant access to the user's data to your web application), it's not required to enter the login or password. Also, your application does not get access to your account's password, only to your account's data.

To make requests for approval, your application must be registered on the web site of a service provider. E.g. if you want to let users grant you with the access to their Gmail mailboxes, you'll need to register your application with Google, or with Yahoo in order to access Yahoo Mail accounts. In return, the service provider assigns you a consumer key and consumer secret you'll need to pass to the service each time you make a request for a user's data.

See "Federated Login for Google Account Users" on Google web site for additional information on how to register your site in Google.

Note Note
This class provides helper classes which support OpenID + OAuth implementations of Google and Yahoo. You can, however, add any other implementation which sets OpenID/OAuth parameters as required by your service provider. For that, create and populate parameters object in the samples below not using GetParamsForGoogleOpenIdWithOAuth or GetParamsForYahooOpenIdWithOAuth methods. Or, you can use these methods and then adjust the resulting object in case if the implementation you're working with is very close to Google or Yahoo (for instance, simply requires adding an extra parameter).
Examples

This topic contains samples for both Google (Gmail) and Yahoo below.

The first web sample authenticates client in Gmail IMAP via OpenID + OAuth authentication. It has two pages: "Default.aspx" and "WebForm1.aspx". User opens "Default.aspx" and is get redirected to OpenID server page on Google web site (where the user can grant access to their data to your application). Then, Google redirects the user's browser to "WebForm1.aspx" which actually accesses the user's e-mail account via IMAP.

"http://[yourhost]/hybrid/WebForm1.aspx" designates the URL of "WebForm1.aspx" page (so that Google would know where it should redirect the user after passing the authorization stage).

If user sets "Remember this approval" checkbox on Google authentication page, next time Google will not ask to allow site request for getting Gmail access rights and will get access by default. GMail XOAuth key also may be stored by application for logging in GMail without authentication process.

C#
VB
Copy
// Default.aspx.cs

// To use the code below, import the following namespaces at the top of your code.
using MailBee;

// The actual code (put it into a method of your class).

// Get OpenID server name.
string openIdSrv = OpenID.GetOpenIDServer("https://www.google.com/accounts/o8/id");

StringDictionary parameters = OpenID.GetParamsForGoogleOpenIdWithOAuth();

parameters["openid.return_to"] = "http://[yourhost]/hybrid/WebForm1.aspx";
parameters["openid.realm"] = "http://[yourhost]/hybrid/";
parameters["openid.oauth.consumer"] = "[consumer_key]";

Response.Redirect(OpenID.GetRedirectURL(openIdSrv, parameters));

// WebForm1.aspx.cs

// To use the code below, import the following namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).

// Input consumerKey/consumerSecret from Google here.
string consumerKey = "";
string consumerSecret = "";

OAuth myOAuth = new OAuth(consumerKey, consumerSecret);

// Enables OpenID + OAuth extension.
myOAuth.EnableOpenIDHybrid = true;

// Request OAuth access key from
myOAuth.AccessToken("https://www.google.com/accounts/OAuthGetAccessToken",
    Request.QueryString["openid.ext2.request_token"]);

Response.Write("<b>Access Token:</b> " + myOAuth.Token + "<br/>");
Response.Write("<b>Access Token Secret:</b> " + myOAuth.TokenSecret + "<br/><br/>");

string imapXOAuthKey = myOAuth.GetXOAuthKey(
    string.Format("https://mail.google.com/mail/b/{0}/imap/", Request.QueryString["openid.ext1.value.email"]));

Response.Write("<b>GMail XOAuth key:</b> " + imapXOAuthKey + "<br/><br/>");

// Last: Login to Gmail IMAP server using XOAuth.
Imap imp = new Imap();

// Connect to the server, login and select inbox.
imp.Connect("imap.gmail.com", 993);
imp.Login(null, imapXOAuthKey, AuthenticationMethods.SaslOAuth, AuthenticationOptions.None, null);
imp.SelectFolder("INBOX");

Response.Write("<b>Gmail connected successfully via OpenID+XOAuth</b>");

// Processing of INBOX emails here.
//...
imp.Disconnect();
' Default.aspx.vb

' To use the code below, import the following namespaces at the top of your code.
Imports MailBee

' The actual code (put it into a method of your class).

' Get OpenID server name.
Dim openIdSrv As String = OpenID.GetOpenIDServer("https://www.google.com/accounts/o8/id")

Dim parameters As StringDictionary = OpenID.GetParamsForGoogleOpenIdWithOAuth()

parameters("openid.return_to") = "http://[yourhost]/hybrid/WebForm1.aspx"
parameters("openid.realm") = "http://[yourhost]/hybrid/"
parameters("openid.oauth.consumer") = "[consumer_key]"

Response.Redirect(OpenID.GetRedirectURL(openIdSrv, parameters))

' WebForm1.aspx.vb

' To use the code below, import the following namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).

' Input consumerKey/consumerSecret from Google here.
Dim consumerKey As String = ""
Dim consumerSecret As String = ""

Dim myOAuth As OAuth = New OAuth(consumerKey, consumerSecret)

' Enables OpenID + OAuth extension.
myOAuth.EnableOpenIDHybrid = True

' Request OAuth access key from
myOAuth.AccessToken("https://www.google.com/accounts/OAuthGetAccessToken", _
 Request.QueryString("openid.ext2.request_token"))

Response.Write("<b>Access Token:</b> " + myOAuth.Token + "<br/>")
Response.Write("<b>Access Token Secret:</b> " + myOAuth.TokenSecret + "<br/><br/>")

Dim imapXOAuthKey As String = myOAuth.GetXOAuthKey( _
 String.Format("https://mail.google.com/mail/b/{0}/imap/", Request.QueryString("openid.ext1.value.email")))

Response.Write("<b>GMail XOAuth key:</b> " + imapXOAuthKey + "<br/><br/>")

' Last: Login to Gmail IMAP server using XOAuth.
Dim imp As Imap = New Imap

' Connect to the server, login and select inbox.
imp.Connect("imap.gmail.com", 993)
imp.Login(Nothing, imapXOAuthKey, AuthenticationMethods.SaslOAuth, AuthenticationOptions.None, Nothing)
imp.SelectFolder("INBOX")

Response.Write("<b>Gmail connected successfully via OpenID+XOAuth</b>")

' Processing of INBOX emails here.
'...
imp.Disconnect()
Examples

This web sample authenticates the client in Yahoo via OpenID + OAuth authentication. It works in much the same way as Google/Gmail version but it does not include the last step of connecting via IMAP (currently, Yahoo only supports HTTP access for OpenID + OAuth, such as for accessing Yahoo web services, although this may change in the future).

See "Yahoo! OAuth Quick Start Guide" on Yahoo web site for additional information on how to register your site in Yahoo.

C#
VB
Copy
// Default.aspx.cs

// To use the code below, import the following namespaces at the top of your code.
using MailBee;

string openIdSrv = "https://open.login.yahooapis.com/openid/op/auth";

StringDictionary parameters = OpenID.GetParamsForYahooOpenIdWithOAuth();

parameters["openid.return_to"] = "http://[yourhost]/hybrid/WebForm1.aspx";
parameters["openid.realm"] = "http://[yourhost]/hybrid/";
parameters["openid.oauth.consumer"] = "[consumer_key]";

Response.Redirect(OpenID.GetRedirectURL(openIdSrv, parameters));

// WebForm1.aspx.cs

// To use the code below, import the following namespaces at the top of your code.
using MailBee;

// Input consumerKey/consumerSecret from Yahoo here.
string consumerKey = "";
string consumerSecret = "";

OAuth myOAuth = new OAuth(consumerKey, consumerSecret);

// Enables OpenID + OAuth extension.
myOAuth.EnableOpenIDHybrid = true;

myOAuth.AccessToken("https://api.login.yahoo.com/oauth/v2/get_token",
    Request.QueryString["openid.oauth.request_token"]);

Response.Write("<b>Access Token:</b> " + myOAuth.Token + "<br/>");
Response.Write("<b>Access Token Secret:</b> " + myOAuth.TokenSecret);
' Default.aspx.vb

' To use the code below, import the following namespaces at the top of your code.
Imports MailBee

' The actual code (put it into a method of your class).
Dim openIdSrv As String = "https://open.login.yahooapis.com/openid/op/auth"

Dim parameters As StringDictionary = OpenID.GetParamsForYahooOpenIdWithOAuth()

parameters("openid.return_to") = "http://[yourhost]/hybrid/WebForm1.aspx"
parameters("openid.realm") = "http://[yourhost]/hybrid/"
parameters("openid.oauth.consumer") = "[consumer_key]"

Response.Redirect(OpenID.GetRedirectURL(openIdSrv, parameters))

' WebForm1.aspx.vb

' To use the code below, import the following namespaces at the top of your code.
Imports MailBee

' The actual code (put it into a method of your class).

' Input consumerKey/consumerSecret from Yahoo here.
Dim consumerKey As String = ""
Dim consumerSecret As String = ""

Dim myOAuth As OAuth = New OAuth(consumerKey, consumerSecret)

' Enables OpenID + OAuth extension.
myOAuth.EnableOpenIDHybrid = True

myOAuth.AccessToken("https://api.login.yahoo.com/oauth/v2/get_token", _
 Request.QueryString("openid.oauth.request_token"))

Response.Write("<b>Access Token:</b> " + myOAuth.Token + "<br/>")
Response.Write("<b>Access Token Secret:</b> " + myOAuth.TokenSecret)
See Also

Reference

MailBee Namespace


OpenID Methods

OpenID Methods

The OpenID type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetOpenIDServer | Gets OpenID server URI from OpenID URI string.
 | GetParamsForGoogleOpenIdWithOAuth | Creates a collection with OpenID request parameters for Google OpenID + OAuth.
 | GetParamsForYahooOpenIdWithOAuth | Creates a collection with OpenID requests for Yahoo OpenID + OAuth.
 | GetRedirectURL | Gets the URL on an OpenID server where your web application should redirect the user's browser to.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

OpenID Class
MailBee Namespace


OpenID.GetOpenIDServer Method

OpenIDGetOpenIDServer Method
Gets OpenID server URI from OpenID URI string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetOpenIDServer(
    string openIdKeyUri
)
Public Shared Function GetOpenIDServer (
    openIdKeyUri As String
) As String

Parameters

openIdKeyUri
Type: SystemString
A string with OpenID link.

Return Value

Type: String
A string with OpenID server URI.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | openIdKeyUri is invalid or a null reference (Nothing in Visual Basic).
See Also

Reference

OpenID Class
MailBee Namespace


OpenID.GetParamsForGoogleOpenIdWithOAuth Method

OpenIDGetParamsForGoogleOpenIdWithOAuth Method
Creates a collection with OpenID request parameters for Google OpenID + OAuth.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static StringDictionary GetParamsForGoogleOpenIdWithOAuth()
Public Shared Function GetParamsForGoogleOpenIdWithOAuth As StringDictionary

Return Value

Type: StringDictionary
A StringDictionary object filled with the parameters specific for Google's implementation of OpenID + OAuth.
Remarks

A StringDictionary object contains the following parameters:

openid.ns | http://specs.openid.net/auth/2.0
openid.claimed_id | http://specs.openid.net/auth/2.0/identifier_select
openid.identity | http://specs.openid.net/auth/2.0/identifier_select
openid.mode | checkid_setup
openid.ns.ui | http://specs.openid.net/extensions/ui/1.0
openid.ns.ext1 | http://openid.net/srv/ax/1.0
openid.ext1.mode | fetch_request
openid.ext1.type.email | http://schema.openid.net/contact/email
openid.ext1.type.first | http://schema.openid.net/namePerson/first
openid.ext1.type.last | http://schema.openid.net/namePerson/last
openid.ext1.type.country | http://schema.openid.net/contact/country/home
openid.ext1.type.lang | http://axschema.org/pref/language
openid.ext1.required | email,first,last
openid.ns.oauth | http://specs.openid.net/extensions/oauth/1.0
openid.oauth.scope | https://mail.google.com/

An OpenID request parameter list depends on a particular target server implementation (Yahoo, Google, etc). You can change the default parameters or create and fill your own collection.

See Also

Reference

OpenID Class
MailBee Namespace


OpenID.GetParamsForYahooOpenIdWithOAuth Method

OpenIDGetParamsForYahooOpenIdWithOAuth Method
Creates a collection with OpenID requests for Yahoo OpenID + OAuth.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static StringDictionary GetParamsForYahooOpenIdWithOAuth()
Public Shared Function GetParamsForYahooOpenIdWithOAuth As StringDictionary

Return Value

Type: StringDictionary
A StringDictionary object filled with the parameters specific for Yahoo's implementation of OpenID + OAuth.
Remarks

The returned StringDictionary object contains the following parameters:

openid.ns | http://specs.openid.net/auth/2.0
openid.claimed_id | http://specs.openid.net/auth/2.0/identifier_select
openid.identity | http://specs.openid.net/auth/2.0/identifier_select
openid.mode | checkid_setup
openid.ns.oauth | http://specs.openid.net/extensions/oauth/1.0
Note Note
At the moment of writing, Yahoo does not yet support OpenID + OAuth for IMAP or SMTP (only for HTTP).

An OpenID request parameter list depends on a particular target server implementation (Yahoo, Google, etc). You can change the default parameters or create and fill your own collection.

See Also

Reference

OpenID Class
MailBee Namespace


OpenID.GetRedirectURL Method

OpenIDGetRedirectURL Method
Gets the URL on an OpenID server where your web application should redirect the user's browser to.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetRedirectURL(
    string openIdServerUrl,
    StringDictionary parameters
)
Public Shared Function GetRedirectURL (
    openIdServerUrl As String,
    parameters As StringDictionary
) As String

Parameters

openIdServerUrl
Type: SystemString
A string with OpenID server URL.
parameters
Type: System.Collections.SpecializedStringDictionary
A StringDictionary with the OpenID request parameters.

Return Value

Type: String
A string containing the URL of the authorization page on the OpenID server.
Remarks
You'll redirect the user to this page on the OpenID server where the user will be able to grant permissions to your web application.
See Also

Reference

OpenID Class
MailBee Namespace


Resources Class

Resources Class
Provides localization and text customization framework for MailBee library.
Inheritance Hierarchy
SystemObject
MailBeeResources

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Resources
Public Class Resources

The Resources type exposes the following members.

Constructors
 | Name | Description
Public method | Resources | Initializes a new instance of the Resources class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ErrorDesc_0ComponentNotLicensed | Gets "{0} component not licensed." string.
Public property | ErrorDesc_AbortedByLocalHost | Gets "Socket connection has been aborted by local machine." string.
Public property | ErrorDesc_AbortedByServer | Gets "Socket connection was aborted by remote host." string.
Public property | ErrorDesc_AbortedByUser | Gets "Processing is aborted by user." string.
Public property | ErrorDesc_AlreadyConnected | Gets "Already connected to the server." string.
Public property | ErrorDesc_AlreadyLoggedIn | Gets "Already logged in." string.
Public property | ErrorDesc_AlreadySsl | Gets "TLS/SSL connection already established." string.
Public property | ErrorDesc_ArgumentEmpty | Gets "Empty or null argument value is not allowed." string.
Public property | ErrorDesc_ArgumentInvalid | Gets "Argument value is invalid." string.
Public property | ErrorDesc_ArgumentNull | Gets "Null argument value is not allowed." string.
Public property | ErrorDesc_ArgumentOutOfRange | Gets "Argument value is out of range." string.
Public property | ErrorDesc_BadCredentials | Gets "Wrong account name and/or password." string.
Public property | ErrorDesc_BadDnsResponseHeader | Gets "The header of DNS query response is incorrect." string.
Public property | ErrorDesc_BadMessageData | Gets "The mail message data has been rejected by the server." string.
Public property | ErrorDesc_BadRecipient | Gets "The server rejected the given recipient." string.
Public property | ErrorDesc_BadSender | Gets "The server rejected the specified sender email address." string.
Public property | ErrorDesc_BdatRejected | Gets "BDAT command has been rejected by the server." string.
Public property | ErrorDesc_BdatTimeout | Gets ErrorDesc_SocketTimeout + " This could happen because the SMTP server does not support CHUNKING properly. Set ExtendedSmtpOptions.NoChunking flag to fix this." string.
Public property | ErrorDesc_Busy | Gets "There is already an operation in progress." string.
Public property | ErrorDesc_CertificateDataInvalid | Gets "Certificate data is invalid, of unknown format, or the supplied password is incorrect." string.
Public property | ErrorDesc_CertificateStoreWin32Error | Gets "Win32 function related to certificate store API returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_CertificateValidationError | Gets "Certificate validation failed: the certificate is invalid or expired." string.
Public property | ErrorDesc_CertificateWin32Error | Gets "Certificate-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_ConnectionRefused | Gets "Socket connection has been refused by remote host." string.
Public property | ErrorDesc_ConnectionReset | Gets "An existing connection was forcibly closed by the remote host." string.
Public property | ErrorDesc_Conversion8bitTo7Bit | Gets "The message data will be converted to 7bit format because the given server cannot transmit 8bit data. Some data will be lost." string.
Public property | ErrorDesc_CryptographicException | Gets "CryptographicException occurred." string.
Public property | ErrorDesc_CryptoPrivateKeyInvalid | Gets "Invalid cryptographic private key format." string.
Public property | ErrorDesc_CryptoProviderWin32Error | Gets "Win32 function related to a crypto provider API returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_DataNotAllowed | Gets "The server rejected DATA command." string.
Public property | ErrorDesc_DeadDomain0SmtpMXesInCache | Gets "DNS cache states all SMTP MXes for the domain \"{0}\" are not available or broken." string.
Public property | ErrorDesc_DnsFailureReply | Gets "DNS server replied with Server Failure status." string.
Public property | ErrorDesc_DnsFormatErrorReply | Gets "DNS server replied with Format Error status." string.
Public property | ErrorDesc_DnsInvalidQName | Gets "The length of the item name being queried to DNS server exceeds allowed limit." string.
Public property | ErrorDesc_DnsNameErrorReply | Gets "DNS server replied queried host name was unknown." string.
Public property | ErrorDesc_DnsNotSupportedReply | Gets "DNS server replied with Not Implemented status" string.
Public property | ErrorDesc_DnsQueryMismatch | Gets "The response from DNS server does not correspond to the given query." string.
Public property | ErrorDesc_DnsQueryRefusedReply | Gets "DNS server refused the query. You should try another DNS server." string.
Public property | ErrorDesc_DnsRecursionRequired | Gets "DNS server must support recursion in order to execute the query." string.
Public property | ErrorDesc_DnsUnknownReply | Gets "DNS server replied with unknown status." string.
Public property | ErrorDesc_EhloNotSupported | Gets "EHLO command is not supported by the server." string.
Public property | ErrorDesc_EmptyHostNameForDnsQuery | Gets "Cannot make DNS query for empty host name." string.
Public property | ErrorDesc_EmptyResponseLine | Gets "Status line of the server response contains no status code." string.
Public property | ErrorDesc_EncodingError | Gets "Error occurred during string encoding conversion." string.
Public property | ErrorDesc_EwsFolderAlreadyExists | Gets "Exchange folder already exists." string.
Public property | ErrorDesc_EwsFolderNotFound | Gets "Exchange folder not found." string.
Public property | ErrorDesc_EwsLocalException | Gets "Client-side Exchange error occurred." string.
Public property | ErrorDesc_EwsRemoteException | Gets "Server-side Exchange error occurred." string.
Public property | ErrorDesc_ExternalError | Gets "User code has thrown an exception." string.
Public property | ErrorDesc_FileNotFoundException | Gets "IOException occurred." string.
Public property | ErrorDesc_HostDown | Gets "Remote host is down." string.
Public property | ErrorDesc_HostNotFound | Gets "Remote host not found." string.
Public property | ErrorDesc_HostUnreachable | Gets "Remote host is unreachable." string.
Public property | ErrorDesc_IllegalContext | Gets "This operation is not allowed in the current context." string.
Public property | ErrorDesc_IllegalInCurrentState | Gets "An attempt to call a method of an object in the inappropriate state." string.
Public property | ErrorDesc_IllegalInMultiThreadMode | Gets "This operation is allowed in single-thread mode only." string.
Public property | ErrorDesc_IllegalRaiseEventsMode | Gets "Wait is not allowed unless RaiseEventsViaMessageLoop=false." string.
Public property | ErrorDesc_ImapFolderNotSelected | Gets "A folder must be selected on the server. Call SelectFolder or ExamineFolder first." string.
Public property | ErrorDesc_ImapIdleNotSupported | Gets "The IMAP4 server does not support IDLE capability required to go into IDLE mode." string.
Public property | ErrorDesc_ImapMessageIndexNotFound | Gets "The message with the specified index does not exist on the server." string.
Public property | ErrorDesc_ImapNamespaceNotSupported | Gets "The IMAP4 server does not support NAMESPACE capability." string.
Public property | ErrorDesc_ImapQuotaNotSupported | Gets "The IMAP4 server does not support QUOTA capability required to obtain account and folder quotas." string.
Public property | ErrorDesc_ImapResponseNotFound | Gets "No required data found in the server response." string.
Public property | ErrorDesc_ImapSortNotSupported | Gets "The IMAP4 server does not support SORT capability required to perform sorted search." string.
Public property | ErrorDesc_ImapUidPlusNotSupported | Gets "The IMAP4 server does not support UIDPLUS capability required for the current operation to complete." string.
Public property | ErrorDesc_ImpersonationWin32Error | Gets "Impersonation-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_InconsistentResponse | Gets "The response received from the server refers to non-existent data." string.
Public property | ErrorDesc_InternalError | Gets "Internal error occurred." string.
Public property | ErrorDesc_InvalidBase64DataInResponse | Gets "Base64 data received from the server cannot be decoded." string.
Public property | ErrorDesc_InvalidBinaryResponse | Gets "The binary response received from the server cannot be parsed." string.
Public property | ErrorDesc_InvalidDataFormat | Gets "Supplied data has invalid format." string.
Public property | ErrorDesc_InvalidDataSyntax | Gets "Supplied string has invalid syntax." string.
Public property | ErrorDesc_InvalidDateFormat | Gets "Supplied string date format is invalid." string.
Public property | ErrorDesc_InvalidDomain0InCache | Gets "DNS cache states the domain \"{0}\" does not exist." string.
Public property | ErrorDesc_InvalidImapEnvelope | Gets The envelope data is corrupted or incorrect. Envelope.IsValid will be false." string.
Public property | ErrorDesc_InvalidOperationException | Gets "InvalidOperationException occurred." string.
Public property | ErrorDesc_InvalidResponse | Gets "The response received from the server could not be parsed." string.
Public property | ErrorDesc_InvalidResponseItem | Gets "The particular item of the response data cannot be parsed." string.
Public property | ErrorDesc_IOException | Gets "IOException occurred." string.
Public property | ErrorDesc_JobInBatchFailed | Gets "At least one job failed in the batch. Further processing is stopped. Enable/see log file for more information." string.
Public property | ErrorDesc_LoginWin32Error | Gets "The server has rejected authentication data sent by the client." string.
Public property | ErrorDesc_MessageDataTooLarge | Gets "The length of message data exceeds maximum allowed limit for the given server." string.
Public property | ErrorDesc_NegativeResponse | Gets "The server has responded with negative reply." string.
Public property | ErrorDesc_NoAllowedRecipients | Gets "The server rejected all the recipients of the mail message." string.
Public property | ErrorDesc_NoCredentials | Gets "No credentials have been supplied for login." string.
Public property | ErrorDesc_NoDnsAttemptsLeft | Gets "DNS server has failed too many times and is now considered down." string.
Public property | ErrorDesc_NoDnsServersAvailable | Gets "At least one DNS server must be registered in the system in order to perform direct send." string.
Public property | ErrorDesc_NoDnsServersSpecified | Gets "At least one DNS server must be specified in order to perform direct send or MX query." string.
Public property | ErrorDesc_NoDomainsForMXLookup | Gets "At least one recipient domain must be specified in order to perform MX lookup." string.
Public property | ErrorDesc_NoDomainsToSendFor | Gets "At least one recipient domain must be specified in order to send mail to domains MXes." string.
Public property | ErrorDesc_NoIP4AddressesFound | Gets "No IPv4-compatible end point found." string.
Public property | ErrorDesc_NoMessageInImapResponse | Gets "No required mail message data found in the server response." string.
Public property | ErrorDesc_NoOperationToEnd | Gets "There is no such operation in progress." string.
Public property | ErrorDesc_NoRecipients | Gets "At least one recipient must be specified." string.
Public property | ErrorDesc_NoSender | Gets "No sender specified for the mail message." string.
Public property | ErrorDesc_NoSmtpOrDnsServersSpecified | Gets "At least one DNS or SMTP server must be specified in order to send mail." string.
Public property | ErrorDesc_NoSmtpServersSpecified | Gets "At least one SMTP server must be specified in order to send to relay server." string.
Public property | ErrorDesc_NoSupportedLoginMethods | Gets "None of the specified authentication methods is supported by the server." string.
Public property | ErrorDesc_NotConnected | Gets "Not yet connected to the server. Call Connect first." string.
Public property | ErrorDesc_NotHelloed | Gets "SMTP Hello (HELO or EHLO) has not yet been sent. Call Hello first." string.
Public property | ErrorDesc_NotImpersonated | Gets "Not impersonated yet. Call LogonAs first." string.
Public property | ErrorDesc_NotLoggedIn | Gets "Not yet logged in. Call Login first." string.
Public property | ErrorDesc_ObjectReadOnly | Gets "An attempt to modify the object state has been made while IsReadOnly is set to true." string.
Public property | ErrorDesc_OK | Gets "No error." string.
Public property | ErrorDesc_OleDocAttemptToReplaceExistingBlockAllocationTable | Gets "Attempt to replace existing OLE2 BlockAllocationTable." string.
Public property | ErrorDesc_OleDocBatCountExceedsLimit | Gets "OLE2 BAT count exceeds limit, yet XBAT index indicates no valid entries." string.
Public property | ErrorDesc_OleDocBlock0AlreadyRemoved | Gets "OLE2 Block[{0}] already removed." string.
Public property | ErrorDesc_OleDocBuildingError | Gets "An OLE2 building error occurred." string.
Public property | ErrorDesc_OleDocCannotOpenInternalDocumentStorage | Gets "Cannot open internal OLE2 document storage." string.
Public property | ErrorDesc_OleDocCannotRemoveBlock0OutOfRange1 | Gets "Cannot remove OLE2 block[{0}] out of range[0 - {1}]." string.
Public property | ErrorDesc_OleDocCannotReturnEmptyData | Gets "Cannot return empty OLE2 data." string.
Public property | ErrorDesc_OleDocCouldNotFindAllBlocks | Gets "Could not find all OLE2 blocks." string.
Public property | ErrorDesc_OleDocDuplicateName0 | Gets "Duplicate OLE2 name {0}." string.
Public property | ErrorDesc_OleDocEntry0IsNotDocumentEntry | Gets "OLE2 entry '{0}' is not a DocumentEntry." string.
Public property | ErrorDesc_OleDocIllegalBlockCount0 | Gets "Illegal OLE2 block count; minimum count is 1, got {0} instead." string.
Public property | ErrorDesc_OleDocImproperlyInitializedList | Gets "Improperly initialized list: no OLE2 block allocation table provided." string.
Public property | ErrorDesc_OleDocIndex0IsUnused | Gets "OLE2 index {0} is unused." string.
Public property | ErrorDesc_OleDocInvalidHeaderSignatureRead0Expected1 | Gets "Invalid OLE2 header signature (Outlook MSG message must be a binary file with a valid OLE2 signature). Read {0}, expected {1}." string.
Public property | ErrorDesc_OleDocParsingError | Gets "An OLE2 parsing error occurred." string.
Public property | ErrorDesc_OleDocTriedToWriteTooMuchData | Gets "Tried to write too much OLE2 data." string.
Public property | ErrorDesc_OleDocUnableToReadEntireHeader0ReadExpected1 | Gets "Unable to read the entire OLE2 header: {0} byte(s) read; expected {1} bytes." string.
Public property | ErrorDesc_OleDocXmlNotOle2Format | Gets "The supplied data appears to be in the Office 2007+ XML. MailBee.NET only supports OLE2 document format." string.
Public property | ErrorDesc_OutlookPstAttachmentIsEmpty | Gets "PST attachment is empty." string.
Public property | ErrorDesc_OutlookPstAttemptingToGetNonBinaryData | Gets "Attempting to get non-binary data where they are not expected in PST." string.
Public property | ErrorDesc_OutlookPstBadSignature0 | Gets "Unable to process PST descriptor node, bad signature: {0}" string.
Public property | ErrorDesc_OutlookPstCantGetChildFoldersForFolder01ChildCount23 | Gets "Can't get child folders for folder {0}({1}) child count: {2} - {3}." string.
Public property | ErrorDesc_OutlookPstExpectingLocalDescriptorNodeRef | Gets "Local PST descriptor node ref was expected but not found." string.
Public property | ErrorDesc_OutlookPstExternalReferenceButNoLocalDescriptorItems | Gets "External reference but no localDescriptorItems where they are expected in PST." string.
Public property | ErrorDesc_OutlookPstInvalidDescriptorsOffsetPassed | Gets "Unable to create PST descriptor, invalid descriptor offset." string.
Public property | ErrorDesc_OutlookPstInvalidFileHeader0 | Gets "Invalid PST file header: {0}, expected: !BDN." string.
Public property | ErrorDesc_OutlookPstInvalidInternalBlockSize | Gets "Invalid PST internal block size." string.
Public property | ErrorDesc_OutlookPstIOExceptionReadingSubNode0 | Gets "IOException reading PST subNode: 0x{0:X8}." string.
Public property | ErrorDesc_OutlookPstMissingAttachmentDescriptorItemFor0 | Gets "Missing attachment descriptor item for: {0}." string.
Public property | ErrorDesc_OutlookPstMultipleValueArraysInSubdescriptorsUnsupported | Gets "Multiple value array in PST subdescriptor encountered." string.
Public property | ErrorDesc_OutlookPstOnlyUnencryptedFilesSupported | Gets "Only unencrypted and compressable PST files are supported at this time." string.
Public property | ErrorDesc_OutlookPstParsingError | Gets "Outlook .PST file parsing error occurred." string.
Public property | ErrorDesc_OutlookPstUnableToCreate7cTable | Gets "Unable to create PSTTable7C, table is not 7c." string.
Public property | ErrorDesc_OutlookPstUnableToCreateBcTable | Gets "Unable to create PSTTableBC, table is not bc." string.
Public property | ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0Only1InThisEmail | Gets "Unable to fetch PST attachment #{0}, only {1} attachment(s) found in this e-mail message." string.
Public property | ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0UnableToReadAttachmentDetailsTable | Gets "Unable to fetch PST attachment #{0}, unable to read attachment details table." string.
Public property | ErrorDesc_OutlookPstUnableToFetchRecipientNumber0 | Gets "Unable to fetch PST recipient #{0}." string.
Public property | ErrorDesc_OutlookPstUnableToFind0 | Gets "Unable to find {0} in PST data." string.
Public property | ErrorDesc_OutlookPstUnableToFindNode0 | Gets "Unable to find PST node: {0}." string.
Public property | ErrorDesc_OutlookPstUnableToParseTable0 | Gets "Unable to parse PST table, can't find BTHHEADER header information: {0}." string.
Public property | ErrorDesc_OutlookPstUnableToParseTableBadType | Gets "Unable to parse PST table, bad table type." string.
Public property | ErrorDesc_OutlookPstUnableToParseTableBadType0 | Gets "Unable to parse PST table, bad table type. Unknown identifier: 0x{0}." string.
Public property | ErrorDesc_OutlookPstUnableToProcessArray | Gets "Unable to process PST array, not an array." string.
Public property | ErrorDesc_OutlookPstUnableToProcessXBlock | Gets "Unable to process PST XBlock, incorrect identifier." string.
Public property | ErrorDesc_OutlookPstUnableToReadDescriptorNode | Gets "Unable to read PST descriptor node, not a descriptor." string.
Public property | ErrorDesc_OutlookPstUnableToReadDescriptorNodeIsNotADescriptor | Gets "Unable to read descriptor node, is not a descriptor." string.
Public property | ErrorDesc_OutlookPstUnableToReadSignature | Gets "Unable to read PST Signature." string.
Public property | ErrorDesc_OutlookPstUnableToSeekPastEndOfItemSize0SeekingTo1 | Gets "Unable to seek past end of PST item. size = {0}, seeking to: {1}." string.
Public property | ErrorDesc_OutlookPstUnknownChildType01 | Gets "Unknown PST child type: {0} - {1}." string.
Public property | ErrorDesc_OutlookPstUnrecognisedPstFileVersion0 | Gets "Unrecognised PST File version: {0}." string.
Public property | ErrorDesc_Pop3AuthCommandUnknown | Gets "The server does not support AUTH command. SASL authentication will not be available." string.
Public property | ErrorDesc_Pop3CapaCommandUnknown | Gets "The server does not support CAPA command. POP3 pipelining will not be available." string.
Public property | ErrorDesc_ProxyAuthMethodsNotAccepted | Gets "None of the methods listed by the client to the proxy server are acceptable." string.
Public property | ErrorDesc_ProxyConnectionDeclined | Gets "The proxy server declined to act as a proxy gateway for the given client." string.
Public property | ErrorDesc_ProxyGssApiAuthFailed | Gets "Proxy GSSAPI authentication failed." string.
Public property | ErrorDesc_ProxyUserPassAuthFailed | Gets "Proxy Username/Password authentication failed." string.
Public property | ErrorDesc_ResponseTimeout | Gets "Establishing connection with the server has been aborted as it was too slow." string.
Public property | ErrorDesc_SaslAnswerRejected | Gets "The server has rejected authentication data sent by the client." string.
Public property | ErrorDesc_SmimeWin32Error | Gets "S/MIME-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_SocketDisposed | Gets "The socket object used by MailBee was unexpectedly closed." string.
Public property | ErrorDesc_SocketException | Gets "SocketException occurred." string.
Public property | ErrorDesc_SocketTimeout | Gets "Socket connection has timed out." string.
Public property | ErrorDesc_SslNegoAuthException | Gets "AuthenticationException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.
Public property | ErrorDesc_SslNegoException | Gets "Exception occurred during SSL negotiation." string.
Public property | ErrorDesc_SslNegoIOException | Gets "IOException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.
Public property | ErrorDesc_SslNegoNotSupportedException | Gets "NotSupportedException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.
Public property | ErrorDesc_SslWin32Error | Gets "SSL-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_StartTlsNotAvailable | Gets "The server does not support STARTTLS (STLS for POP3) command." string.
Public property | ErrorDesc_StreamCannotRead | Gets "The specified stream is closed or write-only or doesn't support seeking (random access)." string.
Public property | ErrorDesc_StreamCannotWrite | Gets "The specified stream is closed or read-only or doesn't support seeking (random access)." string.
Public property | ErrorDesc_SyncIONotSupported | Gets "Sync I/O not supported by this platform. Use async I/O instead." string.
Public property | ErrorDesc_TnefAttributeChecksumInvalid | Gets "Invalid checksum of TNEF attribute." string.
Public property | ErrorDesc_TnefAttributeLevelInvalid0 | Gets "Invalid TNEF attribute level: {0}." string.
Public property | ErrorDesc_TnefCompressedRtfCrc32Failed | Gets "TNEF compressed-RTF CRC32 failed." string.
Public property | ErrorDesc_TnefCompressedRtfDataSizeMismatch | Gets "TNEF compressed-RTF data size mismatch." string.
Public property | ErrorDesc_TnefCompressedRtfHeaderInvalid | Gets "Invalid TNEF compressed-RTF header." string.
Public property | ErrorDesc_TnefGuidInvalid0 | Gets "Invalid TNEF Guid: {0}." string.
Public property | ErrorDesc_TnefLevelTypeInvalid0 | Gets "Invalid TNEF level type: {0}." string.
Public property | ErrorDesc_TnefMapiMultivalueIsNotAllowedInSingleMapiValue | Gets "Multivalue is not allowed in single MapiValue." string.
Public property | ErrorDesc_TnefMapiPropTypeInvalid0 | Gets "Invalid MapiProp type: {0}." string.
Public property | ErrorDesc_TnefMapiTypeUnknown0 | Gets "Unknown TNEF MAPI type: {0}." string.
Public property | ErrorDesc_TnefSignature0Invalid | Gets "Invalid TNEF signature 0x{0} (not a valid TNEF stream)." string.
Public property | ErrorDesc_TnefUnexpectedEndOfStream | Gets "Unexpected end of TNEF stream." string.
Public property | ErrorDesc_TnefUnknownRtfCompressionType0 | Gets "TNEF Unknown RTF compression type (magic number {0})." string.
Public property | ErrorDesc_UnauthorizedAccessException | Gets "IOException occurred." string.
Public property | ErrorDesc_Unknown | Gets "Unknown error." string.
Public property | ErrorDesc_UnsupportedLoginMethod | Gets "The specified authentication method is not supported by the server." string.
Public property | ErrorDesc_WebException | Gets "IOException occurred." string.
Public property | ErrorDesc_XmlException | Gets "IOException occurred." string.
Public property | ErrorDescSuffix_DnsResponseCode0HostName1Base64EncodedData2 | Gets " DnsResponseCode: {0}, HostName DNS server was queried about: \"{1}\", Base64 encoded response data: {2} (trailing zero bytes truncated)." string.
Public property | ErrorDescSuffix_ImapInvalidEnvelopeMessageNumber0 | Gets " The invalid envelope message number is: {0}." string.
Public property | ErrorDescSuffix_ImapNonExistentMessageNumber0 | Gets " Non-existent message number is: {0}." string.
Public property | ErrorDescSuffix_ImapNonExistentUid0 | Gets " Non-existent UID is: {0}." string.
Public property | ErrorDescSuffix_InnerException0 | Gets " InnerException message follows: {0}" string.
Public property | ErrorDescSuffix_ResponseString0 | Gets " The server responded: {0}." string.
Public property | ErrorDescSuffix_ServerResponded0 | Gets " The server responded: {0}." string.
Public property | ErrorDescSuffix_Win32ErrorCode0Desc1 | Gets " The Win32 error code is: {0}. The Win32 description is: {1}." string.
 | Instance | Gets or sets the object of either Resources class or any derived class, which defines string resources used by MailBee.
Public property | LicenseKeyComVersion | Gets "LicenseKey is for MailBee COM/ActiveX version rather than MailBee.NET version." string.
Public property | LicenseKeyInvalid | Gets "LicenseKey is invalid. See documentation on MailBee.Global.LicenseKey property of the component for more information." string.
Public property | LicenseKeyIsWriteOnlyWarning | Gets "Warning: LicenseKey property is write-only." string.
Public property | LicenseKeyOlderVersion | Gets "LicenseKey is for an older version of MailBee.NET components." string.
Public property | LicenseKeyTrialExpired | Gets "Trial LicenseKey is expired." string.
Public property | Log_0BytesReceived | Gets "Total {0} bytes received." string.
Public property | Log_0BytesSent | Gets "Data chunk of {0} bytes sent." string.
Public property | Log_AbortRequested | Gets "User code called Abort." string.
Public property | Log_AssemblyVersion0 | Gets "Assembly version: {0}." string.
Public property | Log_Base64Banner | Gets "Binary data is Base64-encoded" string.
Public property | Log_ConnectedToServerAtHost0OnPort1 | Gets "Connected to mail service at host \"{0}\" on port {1} and ready." string.
Public property | Log_DisconnectedFromHost0 | Gets "Disconnected from host \"{0}\"." string.
Public property | Log_Dns0RecordsFoundForHost1 | Gets "{0} DNS record(s) found for host \"{1}\"." string.
Public property | Log_DnsCreatingQueryAboutHost0 | Gets "Creating DNS query about host \"{0}\"." string.
Public property | Log_DnsParsingReceivedResponse | Gets "Parsing a response that was received from DNS server." string.
Public property | Log_DnsQueryDone | Gets "DNS query done." string.
Public property | Log_DnsRecordOfATypeHasIP0 | Gets "DNS record of A type. IP={0}." string.
Public property | Log_DnsRecordOfCNameTypeIsAliasFor0 | Gets "DNS record of CNAME type. Alias for \"{0}\"." string.
Public property | Log_DnsRecordOfMXTypeHasSmtpHost0OfPreference1 | Gets DNS record of MX type. SmtpHost=\"{0}\", Preference={1}." string.
Public property | Log_DnsRecordOfPtrTypeDenotesDomain0 | Gets "DNS record of PTR type. Denotes domain \"{0}\"." string.
Public property | Log_DnsRecordOfTxtTypeHas0Strings | Gets "DNS record of TXT type. Has {0} strings." string.
Public property | Log_DnsRecordOfUnknownType | Gets "DNS record of unknown type detected." string.
Public property | Log_DnsRecursionIsNotSupported | Gets "Recursion is not supported by DNS server." string.
Public property | Log_DnsRecursionIsSupported | Gets "Recursion is supported by DNS server." string.
Public property | Log_DnsRecursionStatusUnknown | Gets "Recursion status is unknown for the given DNS server." string.
Public property | Log_DnsSendingQueryToEndPoint0 | Gets "Sending query to DNS server at \"{0}\"." string.
Public property | Log_Error0 | Gets "Error: {0}" string.
Public property | Log_Ews0AttachmentsReturned | Gets "{0} attachments returned." string.
Public property | Log_EwsAttachmentNotFound | Gets "Attachment not found." string.
Public property | Log_EwsDownloadFolderByFullNameRecursivelyFoundNothing | Gets "Finding folder by full name recursively found nothing" string.
Public property | Log_EwsFolderFullName0AlreadyExists | Gets "Folder full name \"{0}\" already exists." string.
Public property | Log_EwsFolderFullName0MatchedToId1 | Gets "Folder full name \"{0}\" matched to folder ID {1}" string.
Public property | Log_EwsFolderFullName0NotFound | Gets "Folder full name \"{0}\" not found." string.
Public property | Log_EwsOperationDone | Gets "Operation done." string.
Public property | Log_EwsOperationDone0ItemsReturned | Gets "Operation done, {0} item(s) returned." string.
Public property | Log_EwsOperationDone0MessagesDeleted | Gets "Operation done, {0} messages deleted." string.
Public property | Log_EwsWillAddAttachmentAndUpdateItem | Gets "Will add attachment and update item." string.
Public property | Log_EwsWillBindFolderId0 | Gets "Will bind folder ID {0}." string.
Public property | Log_EwsWillBindItemId0 | Gets "Will bind item ID {0}." string.
Public property | Log_EwsWillCheckFolderExistsByFullName0 | Gets "Will check folder existance by full name \"{0}\"." string.
Public property | Log_EwsWillCheckFolderExistsByShortName0InParentFolderId1 | Gets "Will check folder existance by short name \"{0}\" in parent folder ID {1}." string.
Public property | Log_EwsWillCopyItemToFolderId0 | Gets "Will copy item to folder ID {0}." string.
Public property | Log_EwsWillCreateFolder0 | Gets "Will create folder \"{0}\"." string.
Public property | Log_EwsWillCreateFolder0InId1 | Gets "Will create folder \"{0}\" in folder ID {1}." string.
Public property | Log_EwsWillDelete0AttachmentsAndUpdateItem | Gets "Will delete {0} attachment(s) and update item." string.
Public property | Log_EwsWillDeleteAllAttachmentsAndUpdateItem | Gets "Will delete all attachments and update item." string.
Public property | Log_EwsWillDeleteFolderUsingMethod0 | Gets "Will delete folder using method {0}." string.
Public property | Log_EwsWillDeleteItemsUsingMethod0 | Gets "Will delete items using method {0}." string.
Public property | Log_EwsWillDeleteItemUsingMethod0 | Gets "Will delete item using method {0}." string.
Public property | Log_EwsWillDownloadFolderByFullName0InContainingFolderId1 | Gets "Will find and download folder by full name \"{0}\" in containing folder ID {1}." string.
Public property | Log_EwsWillDownloadFolderByFullName0Recursively | Gets "Will find and download folder by full name \"{0}\" recursively." string.
Public property | Log_EwsWillDownloadFolderByShortName0InParentFolderId1 | Gets "Will find and download folder by short name \"{0}\" in parent folder ID {1}." string.
Public property | Log_EwsWillEmptyFolderUsingMethod0 | Gets "Will empty folder using method {0}." string.
Public property | Log_EwsWillFindFolderIdByShortName0InParentFolderId1 | Gets "Will find FolderId by short name \"{0}\" in parent folder ID {1}." string.
Public property | Log_EwsWillFindFolders | Gets "Will find folders." string.
Public property | Log_EwsWillFindItemsInFolderId0 | Gets "Will find items in folder ID {0}." string.
Public property | Log_EwsWillGet0Attachments | Gets "Will get {0} attachment(s)." string.
Public property | Log_EwsWillLoadPropertiesForItems | Gets "Will load properties for items." string.
Public property | Log_EwsWillMoveFolderToId0 | Gets "Will move folder to folder ID {0}." string.
Public property | Log_EwsWillMoveItemToFolderId0 | Gets "Will move item to folder ID {0}." string.
Public property | Log_EwsWillRenameFolderTo0 | Gets "Will rename folder to \"{0}\"." string.
Public property | Log_EwsWillRenameOrMoveFolderWithOldFullName0ToNewFullName1 | Gets "Will rename or move folder with old full name \"{0}\" to new full name \"{1}\"." string.
Public property | Log_EwsWillResolveName0 | Gets "Will resolve name \"{0}\"." string.
Public property | Log_EwsWillSendEmail | Gets "Will send email." string.
Public property | Log_EwsWillSendEmailAndSaveCopy | Gets "Will send email and save copy." string.
Public property | Log_EwsWillSendEmailAndSaveCopyInFolderId0 | Gets "Will send email and save copy in folder ID {0}." string.
Public property | Log_EwsWillUpdateItemId0 | Gets "Will update item ID {0}." string.
Public property | Log_EwsWillUpload0BytesMessageIntoFolderId1 | Gets "Will upload {0} bytes message into folder ID {1}." string.
Public property | Log_Host0ResolvedToIP1 | Gets "Host \"{0}\" resolved to IP address(es) {1}." string.
Public property | Log_ImapCloseFolder | Gets "Close folder." string.
Public property | Log_ImapCopyMessagesDone | Gets "Messages copied." string.
Public property | Log_ImapDownloadEnvelopesDone | Gets "Envelopes downloaded" string.
Public property | Log_ImapDownloadFoldersDone | Gets "Folder list downloaded." string.
Public property | Log_ImapExpunge | Gets "Expunge all deleted messages from the folder." string.
Public property | Log_ImapExpunge0 | Gets "Expunge messages with UIDs \"{0}\" from the folder." string.
Public property | Log_ImapFolderQuota0 | Gets "Obtain quota limits and usage for folder \"{0}\"." string.
Public property | Log_ImapFolderStatus0 | Gets "Get statistics for folder \"{0}\"." string.
Public property | Log_ImapGetCapabilitiesViaCapability | Gets "Get the list of IMAP4 capabilities via CAPABILITY command." string.
Public property | Log_ImapGettingQuotaFromList | Gets "Processing a single quota from quota list." string.
Public property | Log_ImapIdleDone | Gets "Idle done." string.
Public property | Log_ImapLiteralOfLength0 | Gets "Literal of length {0}." string.
Public property | Log_ImapManageFolder0 | Gets "Manage folder \"{0}\"." string.
Public property | Log_ImapMatchingQuotaFound | Gets "Matching quota found." string.
Public property | Log_ImapMoveMessagesDone | Gets "Messages moved." string.
Public property | Log_ImapNamespace | Gets "Get namespaces for the account." string.
Public property | Log_ImapPreauthenticatedUser | Gets "Preauthenticated user" string.
Public property | Log_ImapRenameFolder0To1 | Gets "Rename folder \"{0}\" to \"{1}\"." string.
Public property | Log_ImapSearchDone | Gets "Search done." string.
Public property | Log_ImapSelectFolder0 | Gets "Select folder \"{0}\"." string.
Public property | Log_ImapSetMessageFlags | Gets "Setting flags for messages." string.
Public property | Log_ImapSortDone | Gets "Sorted search done." string.
Public property | Log_ImapUploadMessageDone | Gets "Message uploaded." string.
Public property | Log_ImapWillCopyMessagesTo0 | Gets "Will copy messages to folder \"{0}\"." string.
Public property | Log_ImapWillDownloadEnvelopes | Gets "Will download envelopes." string.
Public property | Log_ImapWillDownloadFoldersOf0Matching1 | Gets "Will download list of sub-folders of \"{0}\" folder matching \"{1}\" condition." string.
Public property | Log_ImapWillFinishIdling | Gets "Will finish idling." string.
Public property | Log_ImapWillIdle | Gets "Will go idle." string.
Public property | Log_ImapWillMoveMessagesTo0 | Gets "Will move messages to folder \"{0}\"." string.
Public property | Log_ImapWillSearch | Gets "Will perform search in the folder." string.
Public property | Log_ImapWillSort | Gets "Will perform sorted search in the folder." string.
Public property | Log_ImapWillTryRegularAuth | Gets "Will try regular LOGIN authentication." string.
Public property | Log_ImapWillUploadMessageTo0 | Gets "Will upload message to folder \"{0}\"." string.
Public property | Log_LoggedInAs0 | Gets "Logged in as \"{0}\"." string.
Public property | Log_MailingFailedJobReEnqueued | Gets "Failed job put back into pending list." string.
Public property | Log_MailingFailedJobsEnqueued | Gets "All failed jobs moved back into pending list." string.
Public property | Log_MailingJob0 | Gets "Job {0}." string.
Public property | Log_MailingNoPendingJobsLeft | Gets "All pending jobs have been put into processing." string.
Public property | Log_MailingPendingJobEnqueued | Gets "New pending job to send e-mail(s)." string.
Public property | Log_MailingPendingJobWentToProcessing | Gets "Processing of a pending job started." string.
Public property | Log_MailingProcessingJobsFinished | Gets "All jobs have been processed." string.
Public property | Log_MailingProcessingJobsStarted | Gets "Processing of pending jobs started." string.
Public property | Log_MailingWorkerThreadDone | Gets "Worker thread with hash {0} and ID {1} has finished all the tasks." string.
Public property | Log_MessageTypeInfo | Gets "INFO" string.
Public property | Log_MessageTypeRecv | Gets "RECV" string.
Public property | Log_MessageTypeSend | Gets "SEND" string.
Public property | Log_MessageTypeUser | Gets "USER" string.
Public property | Log_Pop3ApopAuthNotSupported | Gets "APOP authentication is not supported by the server." string.
Public property | Log_Pop3DeletedMessageIndex0 | Gets "Message (index={0}) marked as deleted." string.
Public property | Log_Pop3DeletedMessagesStartIndex0Count1 | Gets "Messages (startIndex={0}, count={1}) marked as deleted." string.
Public property | Log_Pop3Downloaded0Index1 | Gets "Downloaded {0} (index={1})." string.
Public property | Log_Pop3Downloaded0StartIndex1Count2 | Gets "Downloaded {0} (startIndex={1}, count={2})." string.
Public property | Log_Pop3DownloadList | Gets "Download the list of lengths of all messages in inbox." string.
Public property | Log_Pop3DownloadStat | Gets "Download inbox statistics." string.
Public property | Log_Pop3DownloadUidl | Gets "Download the list of Unique-IDs of all messages in inbox." string.
Public property | Log_Pop3EntireMessage | Gets "entire message" string.
Public property | Log_Pop3EntireMessages | Gets "entire messages" string.
Public property | Log_Pop3GetAdvertizedSaslMethodsViaAuth | Gets "Get the list of advertized SASL authentication methods via AUTH command." string.
Public property | Log_Pop3GetCapabilitiesViaCapa | Gets "Get the list of POP3 capabilities via CAPA command." string.
Public property | Log_Pop3MessageHeader | Gets "message header" string.
Public property | Log_Pop3MessageHeaderAnd0BodyLines | Gets "partial (header + {0} body lines) message" string.
Public property | Log_Pop3MessageHeaders | Gets "message headers" string.
Public property | Log_Pop3MessageHeadersAnd0BodyLines | Gets "partial (header + {0} body lines) messages" string.
Public property | Log_Pop3NothingToDelete | Gets "No messages could be deleted from empty inbox." string.
Public property | Log_Pop3ResetDeletes | Gets "Cancel deletion of all messages marked as deleted." string.
Public property | Log_Pop3WillDeleteMessageIndex0 | Gets "Will mark message (index={0}) as deleted." string.
Public property | Log_Pop3WillDeleteMessagesStartIndex0Count1 | Gets "Will mark messages (startIndex={0}, count={1}) as deleted." string.
Public property | Log_Pop3WillDownload0Index1 | Gets "Will download {0} (index={1})." string.
Public property | Log_Pop3WillDownload0StartIndex1Count2 | Gets "Will download {0} (startIndex={1}, count={2})." string.
Public property | Log_Pop3WillTryApopAuth | Gets "Will try APOP authentication." string.
Public property | Log_Pop3WillTryRegularAuth | Gets "Will try regular USER/PASS authentication." string.
Public property | Log_Pop3ZeroMessagesDownloadedFromEmptyInbox | Gets "Inbox was empty. Zero messages downloaded." string.
Public property | Log_Sasl0AuthUnsupported | Gets "SASL {0} authentication method is not supported by the server." string.
Public property | Log_SendMailDone | Gets "Mail message sent." string.
Public property | Log_SendMailFailedRecipientsAllowed | Gets "Failed recipients allowed." string.
Public property | Log_SendMailFailedRecipientsNotAllowed | Gets "Failed recipients not allowed." string.
Public property | Log_SendMailGotARblListsFor0RblsOf1Total |
Public property | Log_SendMailGotDnsInfoRegardingHost0FromCache | Gets "Got DNS info regarding \"{0}\" from cache." string.
Public property | Log_SendMailGotMXListsFor0DomainsOf1Total | Gets "Retrieved MX records for {0} recipient domain(s) of {1} total." string.
Public property | Log_SendMailMadeDnsQueryToDnsAt0RegardingHost1 | Gets "Made DNS query to DNS server at {0} regarding host \"{1}\"." string.
Public property | Log_SendMailMessageSubmittedToPickupFolderAs0 | Gets "Mail message submitted to pickup folder as \"{0}\"." string.
Public property | Log_SendMailProcessedDnsQueryToDnsAt0RegardingHost1 | Gets "Processed results of DNS query to DNS server at {0} regarding host \"{1}\"." string.
Public property | Log_SendMailSentToMXesOfDomain0 | Gets "Mail message sent to SMTP MX server(s) of domain \"{0}\"." string.
Public property | Log_SendMailSentToRecipientDomains | Gets "Mail message sent to SMTP MX server(s) for every domain." string.
Public property | Log_SendMailSentViaMXLookup | Gets "Mail message sent using MX Lookup." string.
Public property | Log_SendMailTestDone | Gets "Test send of mail message done." string.
Public property | Log_SendMailTestViaMXLookupDone | Gets "Test send of mail message using MX Lookup completed." string.
Public property | Log_SendMailWillGetARblRecordsForIP0 |
Public property | Log_SendMailWillGetMXLists | Gets "Will retrieve MX records for every recipient domain." string.
Public property | Log_SendMailWillMakeDnsQueryToDnsAt0RegardingHost1 | Gets "Will make DNS query to DNS server at {0} regarding host \"{1}\"." string.
Public property | Log_SendMailWillSend | Gets "Will send mail message." string.
Public property | Log_SendMailWillSendToMXesOfDomain0 | Gets "Will send mail message to SMTP MX server(s) of domain \"{0}\"." string.
Public property | Log_SendMailWillSendToRecipientDomains | Gets "Will send mail message to SMTP MX server(s) for every domain." string.
Public property | Log_SendMailWillSendViaMXLookup | Gets "Will send mail message using MX lookup." string.
Public property | Log_SendMailWillSubmitMessageToPickupFolder | Gets "Will submit mail message to pickup folder." string.
Public property | Log_SendMailWillTestSend | Gets "Will test sending mail message." string.
Public property | Log_SendMailWillTestSendViaMXLookup | Gets "Will test sending mail message using MX lookup." string.
Public property | Log_ServerCertAutoValidationSucceeded | Gets "Server certificate validation passed." string.
Public property | Log_ServerCertRetrieved | Gets "Server certificate successfully created from the handle. Can verify it now." string.
Public property | Log_SmtpAuthPopBeforeSmtpFailed | Gets "Warning: POP-before-SMTP authentication failed." string.
Public property | Log_SmtpAuthPopBeforeSmtpSucceeded | Gets "POP-before-SMTP authentication succeeded." string.
Public property | Log_SmtpLoginFailed | Gets "Warning: Authentication failed." string.
Public property | Log_SmtpSendDone | Gets "Message successfully submitted to SMTP server." string.
Public property | Log_SmtpSenderAndRecipientsAccepted | Gets "Sender and recipients accepted by SMTP server." string.
Public property | Log_SmtpSessionReset | Gets "SMTP session was reset." string.
Public property | Log_SmtpSubmittingMessageData | Gets "Will send message data now." string.
Public property | Log_SmtpSubmittingSenderAndRecipients | Gets "Will submit sender and recipients." string.
Public property | Log_SmtpTestSendDone | Gets "Test send succeeded." string.
Public property | Log_SmtpWillHello | Gets "Will send Hello command (HELO or EHLO)." string.
Public property | Log_SmtpWillPerformAuthPopBeforeSmtp | Gets "Will perform POP-before-SMTP authentication." string.
Public property | Log_SmtpWillResetSmtpSession | Gets "Will reset SMTP session." string.
Public property | Log_SmtpWillSendMailMessageToServer0 | Gets "Will send mail message to SMTP server \"{0}\"." string.
Public property | Log_SocketConnectedToIPAddress0OnPort1 | Gets "Socket connected to IP address {0} on port {1}." string.
Public property | Log_SslCredentialsCreated | Gets "TLS/SSL credentials created." string.
Public property | Log_SslHandshakeDone | Gets "TLS/SSL negotiation completed." string.
Public property | Log_StartTls | Gets "Request server to begin TLS/SSL negotiation." string.
Public property | Log_Warning0 | Gets "Warning: {0}" string.
Public property | Log_WillConnectToHost0OnPort1 | Gets "Will connect to host \"{0}\" on port {1}." string.
Public property | Log_WillConnectVia0ProxyAtHost1OnPort2 | Gets "Will actually connect via {0} proxy server at host \"{1}\" on port {2}." string.
Public property | Log_WillCreateSslCredentials | Gets "Will create TLS/SSL credentials." string.
Public property | Log_WillDisconnectFromHost0 | Gets "Will disconnect from host \"{0}\"." string.
Public property | Log_WillLoginAs0 | Gets "Will login as \"{0}\"." string.
Public property | Log_WillPerformSslHandshake | Gets "Will start TLS/SSL negotiation sequence." string.
Public property | Log_WillResolveHost0 | Gets "Will resolve host \"{0}\"." string.
Public property | Log_WillTrySasl0Auth | Gets "Will try SASL {0} authentication method." string.
Public property | Log_WillValidateServerCert | Gets "Will check if server certificate complies with the specified auto-validation flags." string.
Public property | LogParam_MailingFailedOrCancelled | Gets "failed or cancelled" string.
Public property | LogParam_MailingSucceeded | Gets "succeeded" string.
Public property | LogSuffix_Tag0Rows1 | Gets " Tag=\"{0}\", Rows=\"{1}\"." string.
Public property | Pop3AuthCommandUnknown | Gets "AUTH command is not supported by the server." string.
Public property | Pop3CapaCommandUnknown | Gets "CAPA command is not supported by the server." string.
Public property | SmtpHelloed | Gets "SMTP Hello completed." string.
Top
Remarks
The developer can derive a class from Resources class and override some or all properties for the purposes of localization or other tasks which require modification of any messages returned by MailBee (this includes log file messages, error messages, etc).
Caution note Caution
For this class, it's not guaranteed to preserve compatibility with future versions of MailBee library. In particular, properties returning error message strings may be replaced.
Examples

This sample changes the standard log message "Messages (startIndex={0}, count={1}) marked as deleted." (defined by Log_Pop3DeletedMessagesStartIndex0Count1 property) to "{1} message(s) starting at {0} flagged as deleted.". Log_Pop3WillDeleteMessagesStartIndex0Count1 property is overridden as well.

To show the effect of this change, the logging is on, and messages in the POP3 mailbox are flagged as deleted twice (so the log messages are added using the standard resources and then using the modified resources). However, no message is actually deleted since ResetDeletes method is called each time.

To improve readability of the log, all log messages which are not necessary for understanding this sample are filtered out in LogNewEntry event handler.

C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // We set it to true only for the time while DeleteMessages is executing.
    // Alternatively, we could just enable logging only for the time of
    // DeleteMessages execution and have it disabled at other times.
    private static bool    m_addEntry;

    // LogNewEntry event handler
    private static void OnLogNewEntry(object sender, LogNewEntryEventArgs e)
    {
        // Do not add log records which either do not apply to
        // DeleteMessages or contain data transferred between the client
        // and the server. This way, we filter all log messages which do
        // not directly relate to this sample.
        if (!m_addEntry || e.NewEntry.MessageType != LogMessageType.Info)
        {
            e.NewEntry.AddThisEntry = false;
        }
    }

    // The actual code
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the LogNewEntry to filter out unnecessary log records.
        pop.LogNewEntry += new LogNewEntryEventHandler(OnLogNewEntry);

        // Connect to the POP3 server and log in the user account.
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");

        // Enable logging after already connected to the server.
        // Alternatively, we could move this code above pop.Connect
        // and set m_addEntry=false there.
        pop.Log.Enabled = true;
        pop.Log.Filename = @"C:\Temp\pop3_log.txt";
        pop.Log.Clear();

        // Will add the records produced by DeleteMessages, to the log.
        m_addEntry = true;

        // Flag the messages as deleted using Resources class.
        pop.Log.WriteLine("The following 2 log records are added using standard resources");
        pop.DeleteMessages(1, 3);

        // We do not want to overburden the log with ResetDeletes results.
        m_addEntry = false;
        pop.ResetDeletes();

        // Flag the messages as deleted using MyResources class.
        Resources.Instance = new MyResources();
        m_addEntry = true;
        pop.Log.WriteLine(null);
        pop.Log.WriteLine("The following 2 log records are added using MyResources");
        pop.DeleteMessages(1, 3);

        // We do not want to overburden the log with ResetDeletes and Disconnect results.
        m_addEntry = false;
        pop.ResetDeletes();

        pop.Disconnect();
    }
}

// Derive our resources class from Resource and override the properties
// which return the string values used to log DeleteMessages method progress.
class MyResources : Resources
{
    public override string Log_Pop3DeletedMessagesStartIndex0Count1
    {
        get { return "{1} message(s) starting at {0} flagged as deleted."; }
    }

    public override string Log_Pop3WillDeleteMessagesStartIndex0Count1
    {
        get { return "Will flag {1} message(s) starting at {0} as deleted."; }
    }
}

// After running this code, C:\Temp\pop3_log.txt file should look like below.
[00:41:02.54] [USER] The following 2 log records are added using standard resources
[00:41:02.55] [INFO] Will mark messages (startIndex=1, count=3) as deleted.
[00:41:02.56] [INFO] Messages (startIndex=1, count=3) marked as deleted.
[00:41:02.56] [USER]
[00:41:02.57] [USER] The following 2 log records are added using MyResources
[00:41:02.57] [INFO] Will flag 3 message(s) starting at 1 as deleted.
[00:41:02.57] [INFO] 3 message(s) starting at 1 flagged as deleted.
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' We set it to true only for the time while DeleteMessages is executing.
    ' Alternatively, we could just enable logging only for the time of
    ' DeleteMessages execution and have it disabled at other times.
    Private Shared m_addEntry As Boolean

    ' LogNewEntry event handler
    Private Shared Sub OnLogNewEntry(ByVal sender As Object, ByVal e As LogNewEntryEventArgs)

        ' Do not add log records which either do not apply to
        ' DeleteMessages or contain data transferred between the client
        ' and the server. This way, we filter all log messages which do
        ' not directly relate to this sample.
        If (Not m_addEntry) Or (e.NewEntry.MessageType <> LogMessageType.Info) Then
            e.NewEntry.AddThisEntry = False
        End If
    End Sub

    ' The actual code
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LogNewEntry to filter out unnecessary log records.
        AddHandler pop.LogNewEntry, AddressOf OnLogNewEntry

        ' Connect to the POP3 server and log in the user account.
        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")

        ' Enable logging after already connected to the server.
        ' Alternatively, we could move this code above pop.Connect
        ' and set m_addEntry=false there.
        pop.Log.Enabled = True
        pop.Log.Filename = "C:\Temp\pop3_log.txt"
        pop.Log.Clear()

        ' Will add the records produced by DeleteMessages, to the log.
        m_addEntry = True

        ' Flag the messages as deleted using Resources class.
        pop.Log.WriteLine("The following 2 log records are added using standard resources")
        pop.DeleteMessages(1, 3)

        ' We do not want to overburden the log with ResetDeletes results.
        m_addEntry = False
        pop.ResetDeletes()

        ' Flag the messages as deleted using MyResources class.
        MailBee.Resources.Instance = New MyResources
        m_addEntry = True
        pop.Log.WriteLine(Nothing)
        pop.Log.WriteLine("The following 2 log records are added using MyResources")
        pop.DeleteMessages(1, 3)

        ' We do not want to overburden the log with ResetDeletes and Disconnect results.
        m_addEntry = False
        pop.ResetDeletes()

        pop.Disconnect()
    End Sub
End Class

' Derive our resources class from Resource and override the properties
' which return the string values used to log DeleteMessages method progress.
Class MyResources
    Inherits MailBee.Resources
    Public Overrides ReadOnly Property Log_Pop3DeletedMessagesStartIndex0Count1() As String
        Get
            Return "{1} message(s) starting at {0} flagged as deleted."
        End Get
    End Property

    Public Overrides ReadOnly Property Log_Pop3WillDeleteMessagesStartIndex0Count1() As String
        Get
            Return "Will flag {1} message(s) starting at {0} as deleted."
        End Get
    End Property
End Class

' After running this code, C:\Temp\pop3_log.txt file should look like below.
[00:41:02.54] [USER] The following 2 log records are added using standard resources
[00:41:02.55] [INFO] Will mark messages (startIndex=1, count=3) as deleted.
[00:41:02.56] [INFO] Messages (startIndex=1, count=3) marked as deleted.
[00:41:02.56] [USER]
[00:41:02.57] [USER] The following 2 log records are added using MyResources
[00:41:02.57] [INFO] Will flag 3 message(s) starting at 1 as deleted.
[00:41:02.57] [INFO] 3 message(s) starting at 1 flagged as deleted.
See Also

Reference

MailBee Namespace


Resources Constructor

Resources Constructor
Initializes a new instance of the Resources class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Resources()
Public Sub New
See Also

Reference

Resources Class
MailBee Namespace


Resources Methods

Resources Methods

The Resources type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Resources Class
MailBee Namespace


Resources Properties

Resources Properties

The Resources type exposes the following members.

Properties
 | Name | Description
Public property | ErrorDesc_0ComponentNotLicensed | Gets "{0} component not licensed." string.
Public property | ErrorDesc_AbortedByLocalHost | Gets "Socket connection has been aborted by local machine." string.
Public property | ErrorDesc_AbortedByServer | Gets "Socket connection was aborted by remote host." string.
Public property | ErrorDesc_AbortedByUser | Gets "Processing is aborted by user." string.
Public property | ErrorDesc_AlreadyConnected | Gets "Already connected to the server." string.
Public property | ErrorDesc_AlreadyLoggedIn | Gets "Already logged in." string.
Public property | ErrorDesc_AlreadySsl | Gets "TLS/SSL connection already established." string.
Public property | ErrorDesc_ArgumentEmpty | Gets "Empty or null argument value is not allowed." string.
Public property | ErrorDesc_ArgumentInvalid | Gets "Argument value is invalid." string.
Public property | ErrorDesc_ArgumentNull | Gets "Null argument value is not allowed." string.
Public property | ErrorDesc_ArgumentOutOfRange | Gets "Argument value is out of range." string.
Public property | ErrorDesc_BadCredentials | Gets "Wrong account name and/or password." string.
Public property | ErrorDesc_BadDnsResponseHeader | Gets "The header of DNS query response is incorrect." string.
Public property | ErrorDesc_BadMessageData | Gets "The mail message data has been rejected by the server." string.
Public property | ErrorDesc_BadRecipient | Gets "The server rejected the given recipient." string.
Public property | ErrorDesc_BadSender | Gets "The server rejected the specified sender email address." string.
Public property | ErrorDesc_BdatRejected | Gets "BDAT command has been rejected by the server." string.
Public property | ErrorDesc_BdatTimeout | Gets ErrorDesc_SocketTimeout + " This could happen because the SMTP server does not support CHUNKING properly. Set ExtendedSmtpOptions.NoChunking flag to fix this." string.
Public property | ErrorDesc_Busy | Gets "There is already an operation in progress." string.
Public property | ErrorDesc_CertificateDataInvalid | Gets "Certificate data is invalid, of unknown format, or the supplied password is incorrect." string.
Public property | ErrorDesc_CertificateStoreWin32Error | Gets "Win32 function related to certificate store API returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_CertificateValidationError | Gets "Certificate validation failed: the certificate is invalid or expired." string.
Public property | ErrorDesc_CertificateWin32Error | Gets "Certificate-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_ConnectionRefused | Gets "Socket connection has been refused by remote host." string.
Public property | ErrorDesc_ConnectionReset | Gets "An existing connection was forcibly closed by the remote host." string.
Public property | ErrorDesc_Conversion8bitTo7Bit | Gets "The message data will be converted to 7bit format because the given server cannot transmit 8bit data. Some data will be lost." string.
Public property | ErrorDesc_CryptographicException | Gets "CryptographicException occurred." string.
Public property | ErrorDesc_CryptoPrivateKeyInvalid | Gets "Invalid cryptographic private key format." string.
Public property | ErrorDesc_CryptoProviderWin32Error | Gets "Win32 function related to a crypto provider API returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_DataNotAllowed | Gets "The server rejected DATA command." string.
Public property | ErrorDesc_DeadDomain0SmtpMXesInCache | Gets "DNS cache states all SMTP MXes for the domain \"{0}\" are not available or broken." string.
Public property | ErrorDesc_DnsFailureReply | Gets "DNS server replied with Server Failure status." string.
Public property | ErrorDesc_DnsFormatErrorReply | Gets "DNS server replied with Format Error status." string.
Public property | ErrorDesc_DnsInvalidQName | Gets "The length of the item name being queried to DNS server exceeds allowed limit." string.
Public property | ErrorDesc_DnsNameErrorReply | Gets "DNS server replied queried host name was unknown." string.
Public property | ErrorDesc_DnsNotSupportedReply | Gets "DNS server replied with Not Implemented status" string.
Public property | ErrorDesc_DnsQueryMismatch | Gets "The response from DNS server does not correspond to the given query." string.
Public property | ErrorDesc_DnsQueryRefusedReply | Gets "DNS server refused the query. You should try another DNS server." string.
Public property | ErrorDesc_DnsRecursionRequired | Gets "DNS server must support recursion in order to execute the query." string.
Public property | ErrorDesc_DnsUnknownReply | Gets "DNS server replied with unknown status." string.
Public property | ErrorDesc_EhloNotSupported | Gets "EHLO command is not supported by the server." string.
Public property | ErrorDesc_EmptyHostNameForDnsQuery | Gets "Cannot make DNS query for empty host name." string.
Public property | ErrorDesc_EmptyResponseLine | Gets "Status line of the server response contains no status code." string.
Public property | ErrorDesc_EncodingError | Gets "Error occurred during string encoding conversion." string.
Public property | ErrorDesc_EwsFolderAlreadyExists | Gets "Exchange folder already exists." string.
Public property | ErrorDesc_EwsFolderNotFound | Gets "Exchange folder not found." string.
Public property | ErrorDesc_EwsLocalException | Gets "Client-side Exchange error occurred." string.
Public property | ErrorDesc_EwsRemoteException | Gets "Server-side Exchange error occurred." string.
Public property | ErrorDesc_ExternalError | Gets "User code has thrown an exception." string.
Public property | ErrorDesc_FileNotFoundException | Gets "IOException occurred." string.
Public property | ErrorDesc_HostDown | Gets "Remote host is down." string.
Public property | ErrorDesc_HostNotFound | Gets "Remote host not found." string.
Public property | ErrorDesc_HostUnreachable | Gets "Remote host is unreachable." string.
Public property | ErrorDesc_IllegalContext | Gets "This operation is not allowed in the current context." string.
Public property | ErrorDesc_IllegalInCurrentState | Gets "An attempt to call a method of an object in the inappropriate state." string.
Public property | ErrorDesc_IllegalInMultiThreadMode | Gets "This operation is allowed in single-thread mode only." string.
Public property | ErrorDesc_IllegalRaiseEventsMode | Gets "Wait is not allowed unless RaiseEventsViaMessageLoop=false." string.
Public property | ErrorDesc_ImapFolderNotSelected | Gets "A folder must be selected on the server. Call SelectFolder or ExamineFolder first." string.
Public property | ErrorDesc_ImapIdleNotSupported | Gets "The IMAP4 server does not support IDLE capability required to go into IDLE mode." string.
Public property | ErrorDesc_ImapMessageIndexNotFound | Gets "The message with the specified index does not exist on the server." string.
Public property | ErrorDesc_ImapNamespaceNotSupported | Gets "The IMAP4 server does not support NAMESPACE capability." string.
Public property | ErrorDesc_ImapQuotaNotSupported | Gets "The IMAP4 server does not support QUOTA capability required to obtain account and folder quotas." string.
Public property | ErrorDesc_ImapResponseNotFound | Gets "No required data found in the server response." string.
Public property | ErrorDesc_ImapSortNotSupported | Gets "The IMAP4 server does not support SORT capability required to perform sorted search." string.
Public property | ErrorDesc_ImapUidPlusNotSupported | Gets "The IMAP4 server does not support UIDPLUS capability required for the current operation to complete." string.
Public property | ErrorDesc_ImpersonationWin32Error | Gets "Impersonation-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_InconsistentResponse | Gets "The response received from the server refers to non-existent data." string.
Public property | ErrorDesc_InternalError | Gets "Internal error occurred." string.
Public property | ErrorDesc_InvalidBase64DataInResponse | Gets "Base64 data received from the server cannot be decoded." string.
Public property | ErrorDesc_InvalidBinaryResponse | Gets "The binary response received from the server cannot be parsed." string.
Public property | ErrorDesc_InvalidDataFormat | Gets "Supplied data has invalid format." string.
Public property | ErrorDesc_InvalidDataSyntax | Gets "Supplied string has invalid syntax." string.
Public property | ErrorDesc_InvalidDateFormat | Gets "Supplied string date format is invalid." string.
Public property | ErrorDesc_InvalidDomain0InCache | Gets "DNS cache states the domain \"{0}\" does not exist." string.
Public property | ErrorDesc_InvalidImapEnvelope | Gets The envelope data is corrupted or incorrect. Envelope.IsValid will be false." string.
Public property | ErrorDesc_InvalidOperationException | Gets "InvalidOperationException occurred." string.
Public property | ErrorDesc_InvalidResponse | Gets "The response received from the server could not be parsed." string.
Public property | ErrorDesc_InvalidResponseItem | Gets "The particular item of the response data cannot be parsed." string.
Public property | ErrorDesc_IOException | Gets "IOException occurred." string.
Public property | ErrorDesc_JobInBatchFailed | Gets "At least one job failed in the batch. Further processing is stopped. Enable/see log file for more information." string.
Public property | ErrorDesc_LoginWin32Error | Gets "The server has rejected authentication data sent by the client." string.
Public property | ErrorDesc_MessageDataTooLarge | Gets "The length of message data exceeds maximum allowed limit for the given server." string.
Public property | ErrorDesc_NegativeResponse | Gets "The server has responded with negative reply." string.
Public property | ErrorDesc_NoAllowedRecipients | Gets "The server rejected all the recipients of the mail message." string.
Public property | ErrorDesc_NoCredentials | Gets "No credentials have been supplied for login." string.
Public property | ErrorDesc_NoDnsAttemptsLeft | Gets "DNS server has failed too many times and is now considered down." string.
Public property | ErrorDesc_NoDnsServersAvailable | Gets "At least one DNS server must be registered in the system in order to perform direct send." string.
Public property | ErrorDesc_NoDnsServersSpecified | Gets "At least one DNS server must be specified in order to perform direct send or MX query." string.
Public property | ErrorDesc_NoDomainsForMXLookup | Gets "At least one recipient domain must be specified in order to perform MX lookup." string.
Public property | ErrorDesc_NoDomainsToSendFor | Gets "At least one recipient domain must be specified in order to send mail to domains MXes." string.
Public property | ErrorDesc_NoIP4AddressesFound | Gets "No IPv4-compatible end point found." string.
Public property | ErrorDesc_NoMessageInImapResponse | Gets "No required mail message data found in the server response." string.
Public property | ErrorDesc_NoOperationToEnd | Gets "There is no such operation in progress." string.
Public property | ErrorDesc_NoRecipients | Gets "At least one recipient must be specified." string.
Public property | ErrorDesc_NoSender | Gets "No sender specified for the mail message." string.
Public property | ErrorDesc_NoSmtpOrDnsServersSpecified | Gets "At least one DNS or SMTP server must be specified in order to send mail." string.
Public property | ErrorDesc_NoSmtpServersSpecified | Gets "At least one SMTP server must be specified in order to send to relay server." string.
Public property | ErrorDesc_NoSupportedLoginMethods | Gets "None of the specified authentication methods is supported by the server." string.
Public property | ErrorDesc_NotConnected | Gets "Not yet connected to the server. Call Connect first." string.
Public property | ErrorDesc_NotHelloed | Gets "SMTP Hello (HELO or EHLO) has not yet been sent. Call Hello first." string.
Public property | ErrorDesc_NotImpersonated | Gets "Not impersonated yet. Call LogonAs first." string.
Public property | ErrorDesc_NotLoggedIn | Gets "Not yet logged in. Call Login first." string.
Public property | ErrorDesc_ObjectReadOnly | Gets "An attempt to modify the object state has been made while IsReadOnly is set to true." string.
Public property | ErrorDesc_OK | Gets "No error." string.
Public property | ErrorDesc_OleDocAttemptToReplaceExistingBlockAllocationTable | Gets "Attempt to replace existing OLE2 BlockAllocationTable." string.
Public property | ErrorDesc_OleDocBatCountExceedsLimit | Gets "OLE2 BAT count exceeds limit, yet XBAT index indicates no valid entries." string.
Public property | ErrorDesc_OleDocBlock0AlreadyRemoved | Gets "OLE2 Block[{0}] already removed." string.
Public property | ErrorDesc_OleDocBuildingError | Gets "An OLE2 building error occurred." string.
Public property | ErrorDesc_OleDocCannotOpenInternalDocumentStorage | Gets "Cannot open internal OLE2 document storage." string.
Public property | ErrorDesc_OleDocCannotRemoveBlock0OutOfRange1 | Gets "Cannot remove OLE2 block[{0}] out of range[0 - {1}]." string.
Public property | ErrorDesc_OleDocCannotReturnEmptyData | Gets "Cannot return empty OLE2 data." string.
Public property | ErrorDesc_OleDocCouldNotFindAllBlocks | Gets "Could not find all OLE2 blocks." string.
Public property | ErrorDesc_OleDocDuplicateName0 | Gets "Duplicate OLE2 name {0}." string.
Public property | ErrorDesc_OleDocEntry0IsNotDocumentEntry | Gets "OLE2 entry '{0}' is not a DocumentEntry." string.
Public property | ErrorDesc_OleDocIllegalBlockCount0 | Gets "Illegal OLE2 block count; minimum count is 1, got {0} instead." string.
Public property | ErrorDesc_OleDocImproperlyInitializedList | Gets "Improperly initialized list: no OLE2 block allocation table provided." string.
Public property | ErrorDesc_OleDocIndex0IsUnused | Gets "OLE2 index {0} is unused." string.
Public property | ErrorDesc_OleDocInvalidHeaderSignatureRead0Expected1 | Gets "Invalid OLE2 header signature (Outlook MSG message must be a binary file with a valid OLE2 signature). Read {0}, expected {1}." string.
Public property | ErrorDesc_OleDocParsingError | Gets "An OLE2 parsing error occurred." string.
Public property | ErrorDesc_OleDocTriedToWriteTooMuchData | Gets "Tried to write too much OLE2 data." string.
Public property | ErrorDesc_OleDocUnableToReadEntireHeader0ReadExpected1 | Gets "Unable to read the entire OLE2 header: {0} byte(s) read; expected {1} bytes." string.
Public property | ErrorDesc_OleDocXmlNotOle2Format | Gets "The supplied data appears to be in the Office 2007+ XML. MailBee.NET only supports OLE2 document format." string.
Public property | ErrorDesc_OutlookPstAttachmentIsEmpty | Gets "PST attachment is empty." string.
Public property | ErrorDesc_OutlookPstAttemptingToGetNonBinaryData | Gets "Attempting to get non-binary data where they are not expected in PST." string.
Public property | ErrorDesc_OutlookPstBadSignature0 | Gets "Unable to process PST descriptor node, bad signature: {0}" string.
Public property | ErrorDesc_OutlookPstCantGetChildFoldersForFolder01ChildCount23 | Gets "Can't get child folders for folder {0}({1}) child count: {2} - {3}." string.
Public property | ErrorDesc_OutlookPstExpectingLocalDescriptorNodeRef | Gets "Local PST descriptor node ref was expected but not found." string.
Public property | ErrorDesc_OutlookPstExternalReferenceButNoLocalDescriptorItems | Gets "External reference but no localDescriptorItems where they are expected in PST." string.
Public property | ErrorDesc_OutlookPstInvalidDescriptorsOffsetPassed | Gets "Unable to create PST descriptor, invalid descriptor offset." string.
Public property | ErrorDesc_OutlookPstInvalidFileHeader0 | Gets "Invalid PST file header: {0}, expected: !BDN." string.
Public property | ErrorDesc_OutlookPstInvalidInternalBlockSize | Gets "Invalid PST internal block size." string.
Public property | ErrorDesc_OutlookPstIOExceptionReadingSubNode0 | Gets "IOException reading PST subNode: 0x{0:X8}." string.
Public property | ErrorDesc_OutlookPstMissingAttachmentDescriptorItemFor0 | Gets "Missing attachment descriptor item for: {0}." string.
Public property | ErrorDesc_OutlookPstMultipleValueArraysInSubdescriptorsUnsupported | Gets "Multiple value array in PST subdescriptor encountered." string.
Public property | ErrorDesc_OutlookPstOnlyUnencryptedFilesSupported | Gets "Only unencrypted and compressable PST files are supported at this time." string.
Public property | ErrorDesc_OutlookPstParsingError | Gets "Outlook .PST file parsing error occurred." string.
Public property | ErrorDesc_OutlookPstUnableToCreate7cTable | Gets "Unable to create PSTTable7C, table is not 7c." string.
Public property | ErrorDesc_OutlookPstUnableToCreateBcTable | Gets "Unable to create PSTTableBC, table is not bc." string.
Public property | ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0Only1InThisEmail | Gets "Unable to fetch PST attachment #{0}, only {1} attachment(s) found in this e-mail message." string.
Public property | ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0UnableToReadAttachmentDetailsTable | Gets "Unable to fetch PST attachment #{0}, unable to read attachment details table." string.
Public property | ErrorDesc_OutlookPstUnableToFetchRecipientNumber0 | Gets "Unable to fetch PST recipient #{0}." string.
Public property | ErrorDesc_OutlookPstUnableToFind0 | Gets "Unable to find {0} in PST data." string.
Public property | ErrorDesc_OutlookPstUnableToFindNode0 | Gets "Unable to find PST node: {0}." string.
Public property | ErrorDesc_OutlookPstUnableToParseTable0 | Gets "Unable to parse PST table, can't find BTHHEADER header information: {0}." string.
Public property | ErrorDesc_OutlookPstUnableToParseTableBadType | Gets "Unable to parse PST table, bad table type." string.
Public property | ErrorDesc_OutlookPstUnableToParseTableBadType0 | Gets "Unable to parse PST table, bad table type. Unknown identifier: 0x{0}." string.
Public property | ErrorDesc_OutlookPstUnableToProcessArray | Gets "Unable to process PST array, not an array." string.
Public property | ErrorDesc_OutlookPstUnableToProcessXBlock | Gets "Unable to process PST XBlock, incorrect identifier." string.
Public property | ErrorDesc_OutlookPstUnableToReadDescriptorNode | Gets "Unable to read PST descriptor node, not a descriptor." string.
Public property | ErrorDesc_OutlookPstUnableToReadDescriptorNodeIsNotADescriptor | Gets "Unable to read descriptor node, is not a descriptor." string.
Public property | ErrorDesc_OutlookPstUnableToReadSignature | Gets "Unable to read PST Signature." string.
Public property | ErrorDesc_OutlookPstUnableToSeekPastEndOfItemSize0SeekingTo1 | Gets "Unable to seek past end of PST item. size = {0}, seeking to: {1}." string.
Public property | ErrorDesc_OutlookPstUnknownChildType01 | Gets "Unknown PST child type: {0} - {1}." string.
Public property | ErrorDesc_OutlookPstUnrecognisedPstFileVersion0 | Gets "Unrecognised PST File version: {0}." string.
Public property | ErrorDesc_Pop3AuthCommandUnknown | Gets "The server does not support AUTH command. SASL authentication will not be available." string.
Public property | ErrorDesc_Pop3CapaCommandUnknown | Gets "The server does not support CAPA command. POP3 pipelining will not be available." string.
Public property | ErrorDesc_ProxyAuthMethodsNotAccepted | Gets "None of the methods listed by the client to the proxy server are acceptable." string.
Public property | ErrorDesc_ProxyConnectionDeclined | Gets "The proxy server declined to act as a proxy gateway for the given client." string.
Public property | ErrorDesc_ProxyGssApiAuthFailed | Gets "Proxy GSSAPI authentication failed." string.
Public property | ErrorDesc_ProxyUserPassAuthFailed | Gets "Proxy Username/Password authentication failed." string.
Public property | ErrorDesc_ResponseTimeout | Gets "Establishing connection with the server has been aborted as it was too slow." string.
Public property | ErrorDesc_SaslAnswerRejected | Gets "The server has rejected authentication data sent by the client." string.
Public property | ErrorDesc_SmimeWin32Error | Gets "S/MIME-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_SocketDisposed | Gets "The socket object used by MailBee was unexpectedly closed." string.
Public property | ErrorDesc_SocketException | Gets "SocketException occurred." string.
Public property | ErrorDesc_SocketTimeout | Gets "Socket connection has timed out." string.
Public property | ErrorDesc_SslNegoAuthException | Gets "AuthenticationException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.
Public property | ErrorDesc_SslNegoException | Gets "Exception occurred during SSL negotiation." string.
Public property | ErrorDesc_SslNegoIOException | Gets "IOException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.
Public property | ErrorDesc_SslNegoNotSupportedException | Gets "NotSupportedException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.
Public property | ErrorDesc_SslWin32Error | Gets "SSL-related Win32 function returned an error. See NativeErrorCode property value for more information." string.
Public property | ErrorDesc_StartTlsNotAvailable | Gets "The server does not support STARTTLS (STLS for POP3) command." string.
Public property | ErrorDesc_StreamCannotRead | Gets "The specified stream is closed or write-only or doesn't support seeking (random access)." string.
Public property | ErrorDesc_StreamCannotWrite | Gets "The specified stream is closed or read-only or doesn't support seeking (random access)." string.
Public property | ErrorDesc_SyncIONotSupported | Gets "Sync I/O not supported by this platform. Use async I/O instead." string.
Public property | ErrorDesc_TnefAttributeChecksumInvalid | Gets "Invalid checksum of TNEF attribute." string.
Public property | ErrorDesc_TnefAttributeLevelInvalid0 | Gets "Invalid TNEF attribute level: {0}." string.
Public property | ErrorDesc_TnefCompressedRtfCrc32Failed | Gets "TNEF compressed-RTF CRC32 failed." string.
Public property | ErrorDesc_TnefCompressedRtfDataSizeMismatch | Gets "TNEF compressed-RTF data size mismatch." string.
Public property | ErrorDesc_TnefCompressedRtfHeaderInvalid | Gets "Invalid TNEF compressed-RTF header." string.
Public property | ErrorDesc_TnefGuidInvalid0 | Gets "Invalid TNEF Guid: {0}." string.
Public property | ErrorDesc_TnefLevelTypeInvalid0 | Gets "Invalid TNEF level type: {0}." string.
Public property | ErrorDesc_TnefMapiMultivalueIsNotAllowedInSingleMapiValue | Gets "Multivalue is not allowed in single MapiValue." string.
Public property | ErrorDesc_TnefMapiPropTypeInvalid0 | Gets "Invalid MapiProp type: {0}." string.
Public property | ErrorDesc_TnefMapiTypeUnknown0 | Gets "Unknown TNEF MAPI type: {0}." string.
Public property | ErrorDesc_TnefSignature0Invalid | Gets "Invalid TNEF signature 0x{0} (not a valid TNEF stream)." string.
Public property | ErrorDesc_TnefUnexpectedEndOfStream | Gets "Unexpected end of TNEF stream." string.
Public property | ErrorDesc_TnefUnknownRtfCompressionType0 | Gets "TNEF Unknown RTF compression type (magic number {0})." string.
Public property | ErrorDesc_UnauthorizedAccessException | Gets "IOException occurred." string.
Public property | ErrorDesc_Unknown | Gets "Unknown error." string.
Public property | ErrorDesc_UnsupportedLoginMethod | Gets "The specified authentication method is not supported by the server." string.
Public property | ErrorDesc_WebException | Gets "IOException occurred." string.
Public property | ErrorDesc_XmlException | Gets "IOException occurred." string.
Public property | ErrorDescSuffix_DnsResponseCode0HostName1Base64EncodedData2 | Gets " DnsResponseCode: {0}, HostName DNS server was queried about: \"{1}\", Base64 encoded response data: {2} (trailing zero bytes truncated)." string.
Public property | ErrorDescSuffix_ImapInvalidEnvelopeMessageNumber0 | Gets " The invalid envelope message number is: {0}." string.
Public property | ErrorDescSuffix_ImapNonExistentMessageNumber0 | Gets " Non-existent message number is: {0}." string.
Public property | ErrorDescSuffix_ImapNonExistentUid0 | Gets " Non-existent UID is: {0}." string.
Public property | ErrorDescSuffix_InnerException0 | Gets " InnerException message follows: {0}" string.
Public property | ErrorDescSuffix_ResponseString0 | Gets " The server responded: {0}." string.
Public property | ErrorDescSuffix_ServerResponded0 | Gets " The server responded: {0}." string.
Public property | ErrorDescSuffix_Win32ErrorCode0Desc1 | Gets " The Win32 error code is: {0}. The Win32 description is: {1}." string.
 | Instance | Gets or sets the object of either Resources class or any derived class, which defines string resources used by MailBee.
Public property | LicenseKeyComVersion | Gets "LicenseKey is for MailBee COM/ActiveX version rather than MailBee.NET version." string.
Public property | LicenseKeyInvalid | Gets "LicenseKey is invalid. See documentation on MailBee.Global.LicenseKey property of the component for more information." string.
Public property | LicenseKeyIsWriteOnlyWarning | Gets "Warning: LicenseKey property is write-only." string.
Public property | LicenseKeyOlderVersion | Gets "LicenseKey is for an older version of MailBee.NET components." string.
Public property | LicenseKeyTrialExpired | Gets "Trial LicenseKey is expired." string.
Public property | Log_0BytesReceived | Gets "Total {0} bytes received." string.
Public property | Log_0BytesSent | Gets "Data chunk of {0} bytes sent." string.
Public property | Log_AbortRequested | Gets "User code called Abort." string.
Public property | Log_AssemblyVersion0 | Gets "Assembly version: {0}." string.
Public property | Log_Base64Banner | Gets "Binary data is Base64-encoded" string.
Public property | Log_ConnectedToServerAtHost0OnPort1 | Gets "Connected to mail service at host \"{0}\" on port {1} and ready." string.
Public property | Log_DisconnectedFromHost0 | Gets "Disconnected from host \"{0}\"." string.
Public property | Log_Dns0RecordsFoundForHost1 | Gets "{0} DNS record(s) found for host \"{1}\"." string.
Public property | Log_DnsCreatingQueryAboutHost0 | Gets "Creating DNS query about host \"{0}\"." string.
Public property | Log_DnsParsingReceivedResponse | Gets "Parsing a response that was received from DNS server." string.
Public property | Log_DnsQueryDone | Gets "DNS query done." string.
Public property | Log_DnsRecordOfATypeHasIP0 | Gets "DNS record of A type. IP={0}." string.
Public property | Log_DnsRecordOfCNameTypeIsAliasFor0 | Gets "DNS record of CNAME type. Alias for \"{0}\"." string.
Public property | Log_DnsRecordOfMXTypeHasSmtpHost0OfPreference1 | Gets DNS record of MX type. SmtpHost=\"{0}\", Preference={1}." string.
Public property | Log_DnsRecordOfPtrTypeDenotesDomain0 | Gets "DNS record of PTR type. Denotes domain \"{0}\"." string.
Public property | Log_DnsRecordOfTxtTypeHas0Strings | Gets "DNS record of TXT type. Has {0} strings." string.
Public property | Log_DnsRecordOfUnknownType | Gets "DNS record of unknown type detected." string.
Public property | Log_DnsRecursionIsNotSupported | Gets "Recursion is not supported by DNS server." string.
Public property | Log_DnsRecursionIsSupported | Gets "Recursion is supported by DNS server." string.
Public property | Log_DnsRecursionStatusUnknown | Gets "Recursion status is unknown for the given DNS server." string.
Public property | Log_DnsSendingQueryToEndPoint0 | Gets "Sending query to DNS server at \"{0}\"." string.
Public property | Log_Error0 | Gets "Error: {0}" string.
Public property | Log_Ews0AttachmentsReturned | Gets "{0} attachments returned." string.
Public property | Log_EwsAttachmentNotFound | Gets "Attachment not found." string.
Public property | Log_EwsDownloadFolderByFullNameRecursivelyFoundNothing | Gets "Finding folder by full name recursively found nothing" string.
Public property | Log_EwsFolderFullName0AlreadyExists | Gets "Folder full name \"{0}\" already exists." string.
Public property | Log_EwsFolderFullName0MatchedToId1 | Gets "Folder full name \"{0}\" matched to folder ID {1}" string.
Public property | Log_EwsFolderFullName0NotFound | Gets "Folder full name \"{0}\" not found." string.
Public property | Log_EwsOperationDone | Gets "Operation done." string.
Public property | Log_EwsOperationDone0ItemsReturned | Gets "Operation done, {0} item(s) returned." string.
Public property | Log_EwsOperationDone0MessagesDeleted | Gets "Operation done, {0} messages deleted." string.
Public property | Log_EwsWillAddAttachmentAndUpdateItem | Gets "Will add attachment and update item." string.
Public property | Log_EwsWillBindFolderId0 | Gets "Will bind folder ID {0}." string.
Public property | Log_EwsWillBindItemId0 | Gets "Will bind item ID {0}." string.
Public property | Log_EwsWillCheckFolderExistsByFullName0 | Gets "Will check folder existance by full name \"{0}\"." string.
Public property | Log_EwsWillCheckFolderExistsByShortName0InParentFolderId1 | Gets "Will check folder existance by short name \"{0}\" in parent folder ID {1}." string.
Public property | Log_EwsWillCopyItemToFolderId0 | Gets "Will copy item to folder ID {0}." string.
Public property | Log_EwsWillCreateFolder0 | Gets "Will create folder \"{0}\"." string.
Public property | Log_EwsWillCreateFolder0InId1 | Gets "Will create folder \"{0}\" in folder ID {1}." string.
Public property | Log_EwsWillDelete0AttachmentsAndUpdateItem | Gets "Will delete {0} attachment(s) and update item." string.
Public property | Log_EwsWillDeleteAllAttachmentsAndUpdateItem | Gets "Will delete all attachments and update item." string.
Public property | Log_EwsWillDeleteFolderUsingMethod0 | Gets "Will delete folder using method {0}." string.
Public property | Log_EwsWillDeleteItemsUsingMethod0 | Gets "Will delete items using method {0}." string.
Public property | Log_EwsWillDeleteItemUsingMethod0 | Gets "Will delete item using method {0}." string.
Public property | Log_EwsWillDownloadFolderByFullName0InContainingFolderId1 | Gets "Will find and download folder by full name \"{0}\" in containing folder ID {1}." string.
Public property | Log_EwsWillDownloadFolderByFullName0Recursively | Gets "Will find and download folder by full name \"{0}\" recursively." string.
Public property | Log_EwsWillDownloadFolderByShortName0InParentFolderId1 | Gets "Will find and download folder by short name \"{0}\" in parent folder ID {1}." string.
Public property | Log_EwsWillEmptyFolderUsingMethod0 | Gets "Will empty folder using method {0}." string.
Public property | Log_EwsWillFindFolderIdByShortName0InParentFolderId1 | Gets "Will find FolderId by short name \"{0}\" in parent folder ID {1}." string.
Public property | Log_EwsWillFindFolders | Gets "Will find folders." string.
Public property | Log_EwsWillFindItemsInFolderId0 | Gets "Will find items in folder ID {0}." string.
Public property | Log_EwsWillGet0Attachments | Gets "Will get {0} attachment(s)." string.
Public property | Log_EwsWillLoadPropertiesForItems | Gets "Will load properties for items." string.
Public property | Log_EwsWillMoveFolderToId0 | Gets "Will move folder to folder ID {0}." string.
Public property | Log_EwsWillMoveItemToFolderId0 | Gets "Will move item to folder ID {0}." string.
Public property | Log_EwsWillRenameFolderTo0 | Gets "Will rename folder to \"{0}\"." string.
Public property | Log_EwsWillRenameOrMoveFolderWithOldFullName0ToNewFullName1 | Gets "Will rename or move folder with old full name \"{0}\" to new full name \"{1}\"." string.
Public property | Log_EwsWillResolveName0 | Gets "Will resolve name \"{0}\"." string.
Public property | Log_EwsWillSendEmail | Gets "Will send email." string.
Public property | Log_EwsWillSendEmailAndSaveCopy | Gets "Will send email and save copy." string.
Public property | Log_EwsWillSendEmailAndSaveCopyInFolderId0 | Gets "Will send email and save copy in folder ID {0}." string.
Public property | Log_EwsWillUpdateItemId0 | Gets "Will update item ID {0}." string.
Public property | Log_EwsWillUpload0BytesMessageIntoFolderId1 | Gets "Will upload {0} bytes message into folder ID {1}." string.
Public property | Log_Host0ResolvedToIP1 | Gets "Host \"{0}\" resolved to IP address(es) {1}." string.
Public property | Log_ImapCloseFolder | Gets "Close folder." string.
Public property | Log_ImapCopyMessagesDone | Gets "Messages copied." string.
Public property | Log_ImapDownloadEnvelopesDone | Gets "Envelopes downloaded" string.
Public property | Log_ImapDownloadFoldersDone | Gets "Folder list downloaded." string.
Public property | Log_ImapExpunge | Gets "Expunge all deleted messages from the folder." string.
Public property | Log_ImapExpunge0 | Gets "Expunge messages with UIDs \"{0}\" from the folder." string.
Public property | Log_ImapFolderQuota0 | Gets "Obtain quota limits and usage for folder \"{0}\"." string.
Public property | Log_ImapFolderStatus0 | Gets "Get statistics for folder \"{0}\"." string.
Public property | Log_ImapGetCapabilitiesViaCapability | Gets "Get the list of IMAP4 capabilities via CAPABILITY command." string.
Public property | Log_ImapGettingQuotaFromList | Gets "Processing a single quota from quota list." string.
Public property | Log_ImapIdleDone | Gets "Idle done." string.
Public property | Log_ImapLiteralOfLength0 | Gets "Literal of length {0}." string.
Public property | Log_ImapManageFolder0 | Gets "Manage folder \"{0}\"." string.
Public property | Log_ImapMatchingQuotaFound | Gets "Matching quota found." string.
Public property | Log_ImapMoveMessagesDone | Gets "Messages moved." string.
Public property | Log_ImapNamespace | Gets "Get namespaces for the account." string.
Public property | Log_ImapPreauthenticatedUser | Gets "Preauthenticated user" string.
Public property | Log_ImapRenameFolder0To1 | Gets "Rename folder \"{0}\" to \"{1}\"." string.
Public property | Log_ImapSearchDone | Gets "Search done." string.
Public property | Log_ImapSelectFolder0 | Gets "Select folder \"{0}\"." string.
Public property | Log_ImapSetMessageFlags | Gets "Setting flags for messages." string.
Public property | Log_ImapSortDone | Gets "Sorted search done." string.
Public property | Log_ImapUploadMessageDone | Gets "Message uploaded." string.
Public property | Log_ImapWillCopyMessagesTo0 | Gets "Will copy messages to folder \"{0}\"." string.
Public property | Log_ImapWillDownloadEnvelopes | Gets "Will download envelopes." string.
Public property | Log_ImapWillDownloadFoldersOf0Matching1 | Gets "Will download list of sub-folders of \"{0}\" folder matching \"{1}\" condition." string.
Public property | Log_ImapWillFinishIdling | Gets "Will finish idling." string.
Public property | Log_ImapWillIdle | Gets "Will go idle." string.
Public property | Log_ImapWillMoveMessagesTo0 | Gets "Will move messages to folder \"{0}\"." string.
Public property | Log_ImapWillSearch | Gets "Will perform search in the folder." string.
Public property | Log_ImapWillSort | Gets "Will perform sorted search in the folder." string.
Public property | Log_ImapWillTryRegularAuth | Gets "Will try regular LOGIN authentication." string.
Public property | Log_ImapWillUploadMessageTo0 | Gets "Will upload message to folder \"{0}\"." string.
Public property | Log_LoggedInAs0 | Gets "Logged in as \"{0}\"." string.
Public property | Log_MailingFailedJobReEnqueued | Gets "Failed job put back into pending list." string.
Public property | Log_MailingFailedJobsEnqueued | Gets "All failed jobs moved back into pending list." string.
Public property | Log_MailingJob0 | Gets "Job {0}." string.
Public property | Log_MailingNoPendingJobsLeft | Gets "All pending jobs have been put into processing." string.
Public property | Log_MailingPendingJobEnqueued | Gets "New pending job to send e-mail(s)." string.
Public property | Log_MailingPendingJobWentToProcessing | Gets "Processing of a pending job started." string.
Public property | Log_MailingProcessingJobsFinished | Gets "All jobs have been processed." string.
Public property | Log_MailingProcessingJobsStarted | Gets "Processing of pending jobs started." string.
Public property | Log_MailingWorkerThreadDone | Gets "Worker thread with hash {0} and ID {1} has finished all the tasks." string.
Public property | Log_MessageTypeInfo | Gets "INFO" string.
Public property | Log_MessageTypeRecv | Gets "RECV" string.
Public property | Log_MessageTypeSend | Gets "SEND" string.
Public property | Log_MessageTypeUser | Gets "USER" string.
Public property | Log_Pop3ApopAuthNotSupported | Gets "APOP authentication is not supported by the server." string.
Public property | Log_Pop3DeletedMessageIndex0 | Gets "Message (index={0}) marked as deleted." string.
Public property | Log_Pop3DeletedMessagesStartIndex0Count1 | Gets "Messages (startIndex={0}, count={1}) marked as deleted." string.
Public property | Log_Pop3Downloaded0Index1 | Gets "Downloaded {0} (index={1})." string.
Public property | Log_Pop3Downloaded0StartIndex1Count2 | Gets "Downloaded {0} (startIndex={1}, count={2})." string.
Public property | Log_Pop3DownloadList | Gets "Download the list of lengths of all messages in inbox." string.
Public property | Log_Pop3DownloadStat | Gets "Download inbox statistics." string.
Public property | Log_Pop3DownloadUidl | Gets "Download the list of Unique-IDs of all messages in inbox." string.
Public property | Log_Pop3EntireMessage | Gets "entire message" string.
Public property | Log_Pop3EntireMessages | Gets "entire messages" string.
Public property | Log_Pop3GetAdvertizedSaslMethodsViaAuth | Gets "Get the list of advertized SASL authentication methods via AUTH command." string.
Public property | Log_Pop3GetCapabilitiesViaCapa | Gets "Get the list of POP3 capabilities via CAPA command." string.
Public property | Log_Pop3MessageHeader | Gets "message header" string.
Public property | Log_Pop3MessageHeaderAnd0BodyLines | Gets "partial (header + {0} body lines) message" string.
Public property | Log_Pop3MessageHeaders | Gets "message headers" string.
Public property | Log_Pop3MessageHeadersAnd0BodyLines | Gets "partial (header + {0} body lines) messages" string.
Public property | Log_Pop3NothingToDelete | Gets "No messages could be deleted from empty inbox." string.
Public property | Log_Pop3ResetDeletes | Gets "Cancel deletion of all messages marked as deleted." string.
Public property | Log_Pop3WillDeleteMessageIndex0 | Gets "Will mark message (index={0}) as deleted." string.
Public property | Log_Pop3WillDeleteMessagesStartIndex0Count1 | Gets "Will mark messages (startIndex={0}, count={1}) as deleted." string.
Public property | Log_Pop3WillDownload0Index1 | Gets "Will download {0} (index={1})." string.
Public property | Log_Pop3WillDownload0StartIndex1Count2 | Gets "Will download {0} (startIndex={1}, count={2})." string.
Public property | Log_Pop3WillTryApopAuth | Gets "Will try APOP authentication." string.
Public property | Log_Pop3WillTryRegularAuth | Gets "Will try regular USER/PASS authentication." string.
Public property | Log_Pop3ZeroMessagesDownloadedFromEmptyInbox | Gets "Inbox was empty. Zero messages downloaded." string.
Public property | Log_Sasl0AuthUnsupported | Gets "SASL {0} authentication method is not supported by the server." string.
Public property | Log_SendMailDone | Gets "Mail message sent." string.
Public property | Log_SendMailFailedRecipientsAllowed | Gets "Failed recipients allowed." string.
Public property | Log_SendMailFailedRecipientsNotAllowed | Gets "Failed recipients not allowed." string.
Public property | Log_SendMailGotARblListsFor0RblsOf1Total |
Public property | Log_SendMailGotDnsInfoRegardingHost0FromCache | Gets "Got DNS info regarding \"{0}\" from cache." string.
Public property | Log_SendMailGotMXListsFor0DomainsOf1Total | Gets "Retrieved MX records for {0} recipient domain(s) of {1} total." string.
Public property | Log_SendMailMadeDnsQueryToDnsAt0RegardingHost1 | Gets "Made DNS query to DNS server at {0} regarding host \"{1}\"." string.
Public property | Log_SendMailMessageSubmittedToPickupFolderAs0 | Gets "Mail message submitted to pickup folder as \"{0}\"." string.
Public property | Log_SendMailProcessedDnsQueryToDnsAt0RegardingHost1 | Gets "Processed results of DNS query to DNS server at {0} regarding host \"{1}\"." string.
Public property | Log_SendMailSentToMXesOfDomain0 | Gets "Mail message sent to SMTP MX server(s) of domain \"{0}\"." string.
Public property | Log_SendMailSentToRecipientDomains | Gets "Mail message sent to SMTP MX server(s) for every domain." string.
Public property | Log_SendMailSentViaMXLookup | Gets "Mail message sent using MX Lookup." string.
Public property | Log_SendMailTestDone | Gets "Test send of mail message done." string.
Public property | Log_SendMailTestViaMXLookupDone | Gets "Test send of mail message using MX Lookup completed." string.
Public property | Log_SendMailWillGetARblRecordsForIP0 |
Public property | Log_SendMailWillGetMXLists | Gets "Will retrieve MX records for every recipient domain." string.
Public property | Log_SendMailWillMakeDnsQueryToDnsAt0RegardingHost1 | Gets "Will make DNS query to DNS server at {0} regarding host \"{1}\"." string.
Public property | Log_SendMailWillSend | Gets "Will send mail message." string.
Public property | Log_SendMailWillSendToMXesOfDomain0 | Gets "Will send mail message to SMTP MX server(s) of domain \"{0}\"." string.
Public property | Log_SendMailWillSendToRecipientDomains | Gets "Will send mail message to SMTP MX server(s) for every domain." string.
Public property | Log_SendMailWillSendViaMXLookup | Gets "Will send mail message using MX lookup." string.
Public property | Log_SendMailWillSubmitMessageToPickupFolder | Gets "Will submit mail message to pickup folder." string.
Public property | Log_SendMailWillTestSend | Gets "Will test sending mail message." string.
Public property | Log_SendMailWillTestSendViaMXLookup | Gets "Will test sending mail message using MX lookup." string.
Public property | Log_ServerCertAutoValidationSucceeded | Gets "Server certificate validation passed." string.
Public property | Log_ServerCertRetrieved | Gets "Server certificate successfully created from the handle. Can verify it now." string.
Public property | Log_SmtpAuthPopBeforeSmtpFailed | Gets "Warning: POP-before-SMTP authentication failed." string.
Public property | Log_SmtpAuthPopBeforeSmtpSucceeded | Gets "POP-before-SMTP authentication succeeded." string.
Public property | Log_SmtpLoginFailed | Gets "Warning: Authentication failed." string.
Public property | Log_SmtpSendDone | Gets "Message successfully submitted to SMTP server." string.
Public property | Log_SmtpSenderAndRecipientsAccepted | Gets "Sender and recipients accepted by SMTP server." string.
Public property | Log_SmtpSessionReset | Gets "SMTP session was reset." string.
Public property | Log_SmtpSubmittingMessageData | Gets "Will send message data now." string.
Public property | Log_SmtpSubmittingSenderAndRecipients | Gets "Will submit sender and recipients." string.
Public property | Log_SmtpTestSendDone | Gets "Test send succeeded." string.
Public property | Log_SmtpWillHello | Gets "Will send Hello command (HELO or EHLO)." string.
Public property | Log_SmtpWillPerformAuthPopBeforeSmtp | Gets "Will perform POP-before-SMTP authentication." string.
Public property | Log_SmtpWillResetSmtpSession | Gets "Will reset SMTP session." string.
Public property | Log_SmtpWillSendMailMessageToServer0 | Gets "Will send mail message to SMTP server \"{0}\"." string.
Public property | Log_SocketConnectedToIPAddress0OnPort1 | Gets "Socket connected to IP address {0} on port {1}." string.
Public property | Log_SslCredentialsCreated | Gets "TLS/SSL credentials created." string.
Public property | Log_SslHandshakeDone | Gets "TLS/SSL negotiation completed." string.
Public property | Log_StartTls | Gets "Request server to begin TLS/SSL negotiation." string.
Public property | Log_Warning0 | Gets "Warning: {0}" string.
Public property | Log_WillConnectToHost0OnPort1 | Gets "Will connect to host \"{0}\" on port {1}." string.
Public property | Log_WillConnectVia0ProxyAtHost1OnPort2 | Gets "Will actually connect via {0} proxy server at host \"{1}\" on port {2}." string.
Public property | Log_WillCreateSslCredentials | Gets "Will create TLS/SSL credentials." string.
Public property | Log_WillDisconnectFromHost0 | Gets "Will disconnect from host \"{0}\"." string.
Public property | Log_WillLoginAs0 | Gets "Will login as \"{0}\"." string.
Public property | Log_WillPerformSslHandshake | Gets "Will start TLS/SSL negotiation sequence." string.
Public property | Log_WillResolveHost0 | Gets "Will resolve host \"{0}\"." string.
Public property | Log_WillTrySasl0Auth | Gets "Will try SASL {0} authentication method." string.
Public property | Log_WillValidateServerCert | Gets "Will check if server certificate complies with the specified auto-validation flags." string.
Public property | LogParam_MailingFailedOrCancelled | Gets "failed or cancelled" string.
Public property | LogParam_MailingSucceeded | Gets "succeeded" string.
Public property | LogSuffix_Tag0Rows1 | Gets " Tag=\"{0}\", Rows=\"{1}\"." string.
Public property | Pop3AuthCommandUnknown | Gets "AUTH command is not supported by the server." string.
Public property | Pop3CapaCommandUnknown | Gets "CAPA command is not supported by the server." string.
Public property | SmtpHelloed | Gets "SMTP Hello completed." string.
Top
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_0ComponentNotLicensed Property

ResourcesErrorDesc_0ComponentNotLicensed Property
Gets "{0} component not licensed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_0ComponentNotLicensed { get; }
Public Overridable ReadOnly Property ErrorDesc_0ComponentNotLicensed As String
    Get

Property Value

Type: String
Remarks
{0} is a placeholder fot the component name, such as Pop3, Powerup, etc.
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_AbortedByLocalHost Property

ResourcesErrorDesc_AbortedByLocalHost Property
Gets "Socket connection has been aborted by local machine." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_AbortedByLocalHost { get; }
Public Overridable ReadOnly Property ErrorDesc_AbortedByLocalHost As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_AbortedByServer Property

ResourcesErrorDesc_AbortedByServer Property
Gets "Socket connection was aborted by remote host." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_AbortedByServer { get; }
Public Overridable ReadOnly Property ErrorDesc_AbortedByServer As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_AbortedByUser Property

ResourcesErrorDesc_AbortedByUser Property
Gets "Processing is aborted by user." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_AbortedByUser { get; }
Public Overridable ReadOnly Property ErrorDesc_AbortedByUser As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_AlreadyConnected Property

ResourcesErrorDesc_AlreadyConnected Property
Gets "Already connected to the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_AlreadyConnected { get; }
Public Overridable ReadOnly Property ErrorDesc_AlreadyConnected As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_AlreadyLoggedIn Property

ResourcesErrorDesc_AlreadyLoggedIn Property
Gets "Already logged in." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_AlreadyLoggedIn { get; }
Public Overridable ReadOnly Property ErrorDesc_AlreadyLoggedIn As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_AlreadySsl Property

ResourcesErrorDesc_AlreadySsl Property
Gets "TLS/SSL connection already established." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_AlreadySsl { get; }
Public Overridable ReadOnly Property ErrorDesc_AlreadySsl As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ArgumentEmpty Property

ResourcesErrorDesc_ArgumentEmpty Property
Gets "Empty or null argument value is not allowed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ArgumentEmpty { get; }
Public Overridable ReadOnly Property ErrorDesc_ArgumentEmpty As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ArgumentInvalid Property

ResourcesErrorDesc_ArgumentInvalid Property
Gets "Argument value is invalid." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ArgumentInvalid { get; }
Public Overridable ReadOnly Property ErrorDesc_ArgumentInvalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ArgumentNull Property

ResourcesErrorDesc_ArgumentNull Property
Gets "Null argument value is not allowed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ArgumentNull { get; }
Public Overridable ReadOnly Property ErrorDesc_ArgumentNull As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ArgumentOutOfRange Property

ResourcesErrorDesc_ArgumentOutOfRange Property
Gets "Argument value is out of range." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ArgumentOutOfRange { get; }
Public Overridable ReadOnly Property ErrorDesc_ArgumentOutOfRange As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BadCredentials Property

ResourcesErrorDesc_BadCredentials Property
Gets "Wrong account name and/or password." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BadCredentials { get; }
Public Overridable ReadOnly Property ErrorDesc_BadCredentials As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BadDnsResponseHeader Property

ResourcesErrorDesc_BadDnsResponseHeader Property
Gets "The header of DNS query response is incorrect." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BadDnsResponseHeader { get; }
Public Overridable ReadOnly Property ErrorDesc_BadDnsResponseHeader As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BadMessageData Property

ResourcesErrorDesc_BadMessageData Property
Gets "The mail message data has been rejected by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BadMessageData { get; }
Public Overridable ReadOnly Property ErrorDesc_BadMessageData As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BadRecipient Property

ResourcesErrorDesc_BadRecipient Property
Gets "The server rejected the given recipient." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BadRecipient { get; }
Public Overridable ReadOnly Property ErrorDesc_BadRecipient As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BadSender Property

ResourcesErrorDesc_BadSender Property
Gets "The server rejected the specified sender email address." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BadSender { get; }
Public Overridable ReadOnly Property ErrorDesc_BadSender As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BdatRejected Property

ResourcesErrorDesc_BdatRejected Property
Gets "BDAT command has been rejected by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BdatRejected { get; }
Public Overridable ReadOnly Property ErrorDesc_BdatRejected As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_BdatTimeout Property

ResourcesErrorDesc_BdatTimeout Property
Gets ErrorDesc_SocketTimeout + " This could happen because the SMTP server does not support CHUNKING properly. Set ExtendedSmtpOptions.NoChunking flag to fix this." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_BdatTimeout { get; }
Public Overridable ReadOnly Property ErrorDesc_BdatTimeout As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_Busy Property

ResourcesErrorDesc_Busy Property
Gets "There is already an operation in progress." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_Busy { get; }
Public Overridable ReadOnly Property ErrorDesc_Busy As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CertificateDataInvalid Property

ResourcesErrorDesc_CertificateDataInvalid Property
Gets "Certificate data is invalid, of unknown format, or the supplied password is incorrect." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CertificateDataInvalid { get; }
Public Overridable ReadOnly Property ErrorDesc_CertificateDataInvalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CertificateStoreWin32Error Property

ResourcesErrorDesc_CertificateStoreWin32Error Property
Gets "Win32 function related to certificate store API returned an error. See NativeErrorCode property value for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CertificateStoreWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_CertificateStoreWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CertificateValidationError Property

ResourcesErrorDesc_CertificateValidationError Property
Gets "Certificate validation failed: the certificate is invalid or expired." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CertificateValidationError { get; }
Public Overridable ReadOnly Property ErrorDesc_CertificateValidationError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CertificateWin32Error Property

ResourcesErrorDesc_CertificateWin32Error Property
Gets "Certificate-related Win32 function returned an error. See NativeErrorCode property value for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CertificateWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_CertificateWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ConnectionRefused Property

ResourcesErrorDesc_ConnectionRefused Property
Gets "Socket connection has been refused by remote host." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ConnectionRefused { get; }
Public Overridable ReadOnly Property ErrorDesc_ConnectionRefused As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ConnectionReset Property

ResourcesErrorDesc_ConnectionReset Property
Gets "An existing connection was forcibly closed by the remote host." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ConnectionReset { get; }
Public Overridable ReadOnly Property ErrorDesc_ConnectionReset As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_Conversion8bitTo7Bit Property

ResourcesErrorDesc_Conversion8bitTo7Bit Property
Gets "The message data will be converted to 7bit format because the given server cannot transmit 8bit data. Some data will be lost." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_Conversion8bitTo7Bit { get; }
Public Overridable ReadOnly Property ErrorDesc_Conversion8bitTo7Bit As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CryptographicException Property

ResourcesErrorDesc_CryptographicException Property
Gets "CryptographicException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CryptographicException { get; }
Public Overridable ReadOnly Property ErrorDesc_CryptographicException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CryptoPrivateKeyInvalid Property

ResourcesErrorDesc_CryptoPrivateKeyInvalid Property
Gets "Invalid cryptographic private key format." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CryptoPrivateKeyInvalid { get; }
Public Overridable ReadOnly Property ErrorDesc_CryptoPrivateKeyInvalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_CryptoProviderWin32Error Property

ResourcesErrorDesc_CryptoProviderWin32Error Property
Gets "Win32 function related to a crypto provider API returned an error. See NativeErrorCode property value for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_CryptoProviderWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_CryptoProviderWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DataNotAllowed Property

ResourcesErrorDesc_DataNotAllowed Property
Gets "The server rejected DATA command." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DataNotAllowed { get; }
Public Overridable ReadOnly Property ErrorDesc_DataNotAllowed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DeadDomain0SmtpMXesInCache Property

ResourcesErrorDesc_DeadDomain0SmtpMXesInCache Property
Gets "DNS cache states all SMTP MXes for the domain \"{0}\" are not available or broken." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DeadDomain0SmtpMXesInCache { get; }
Public Overridable ReadOnly Property ErrorDesc_DeadDomain0SmtpMXesInCache As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsFailureReply Property

ResourcesErrorDesc_DnsFailureReply Property
Gets "DNS server replied with Server Failure status." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsFailureReply { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsFailureReply As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsFormatErrorReply Property

ResourcesErrorDesc_DnsFormatErrorReply Property
Gets "DNS server replied with Format Error status." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsFormatErrorReply { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsFormatErrorReply As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsInvalidQName Property

ResourcesErrorDesc_DnsInvalidQName Property
Gets "The length of the item name being queried to DNS server exceeds allowed limit." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsInvalidQName { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsInvalidQName As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsNameErrorReply Property

ResourcesErrorDesc_DnsNameErrorReply Property
Gets "DNS server replied queried host name was unknown." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsNameErrorReply { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsNameErrorReply As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsNotSupportedReply Property

ResourcesErrorDesc_DnsNotSupportedReply Property
Gets "DNS server replied with Not Implemented status" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsNotSupportedReply { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsNotSupportedReply As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsQueryMismatch Property

ResourcesErrorDesc_DnsQueryMismatch Property
Gets "The response from DNS server does not correspond to the given query." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsQueryMismatch { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsQueryMismatch As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsQueryRefusedReply Property

ResourcesErrorDesc_DnsQueryRefusedReply Property
Gets "DNS server refused the query. You should try another DNS server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsQueryRefusedReply { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsQueryRefusedReply As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsRecursionRequired Property

ResourcesErrorDesc_DnsRecursionRequired Property
Gets "DNS server must support recursion in order to execute the query." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsRecursionRequired { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsRecursionRequired As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_DnsUnknownReply Property

ResourcesErrorDesc_DnsUnknownReply Property
Gets "DNS server replied with unknown status." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_DnsUnknownReply { get; }
Public Overridable ReadOnly Property ErrorDesc_DnsUnknownReply As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EhloNotSupported Property

ResourcesErrorDesc_EhloNotSupported Property
Gets "EHLO command is not supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EhloNotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_EhloNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EmptyHostNameForDnsQuery Property

ResourcesErrorDesc_EmptyHostNameForDnsQuery Property
Gets "Cannot make DNS query for empty host name." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EmptyHostNameForDnsQuery { get; }
Public Overridable ReadOnly Property ErrorDesc_EmptyHostNameForDnsQuery As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EmptyResponseLine Property

ResourcesErrorDesc_EmptyResponseLine Property
Gets "Status line of the server response contains no status code." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EmptyResponseLine { get; }
Public Overridable ReadOnly Property ErrorDesc_EmptyResponseLine As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EncodingError Property

ResourcesErrorDesc_EncodingError Property
Gets "Error occurred during string encoding conversion." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EncodingError { get; }
Public Overridable ReadOnly Property ErrorDesc_EncodingError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EwsFolderAlreadyExists Property

ResourcesErrorDesc_EwsFolderAlreadyExists Property
Gets "Exchange folder already exists." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EwsFolderAlreadyExists { get; }
Public Overridable ReadOnly Property ErrorDesc_EwsFolderAlreadyExists As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EwsFolderNotFound Property

ResourcesErrorDesc_EwsFolderNotFound Property
Gets "Exchange folder not found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EwsFolderNotFound { get; }
Public Overridable ReadOnly Property ErrorDesc_EwsFolderNotFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EwsLocalException Property

ResourcesErrorDesc_EwsLocalException Property
Gets "Client-side Exchange error occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EwsLocalException { get; }
Public Overridable ReadOnly Property ErrorDesc_EwsLocalException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_EwsRemoteException Property

ResourcesErrorDesc_EwsRemoteException Property
Gets "Server-side Exchange error occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_EwsRemoteException { get; }
Public Overridable ReadOnly Property ErrorDesc_EwsRemoteException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ExternalError Property

ResourcesErrorDesc_ExternalError Property
Gets "User code has thrown an exception." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ExternalError { get; }
Public Overridable ReadOnly Property ErrorDesc_ExternalError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_FileNotFoundException Property

ResourcesErrorDesc_FileNotFoundException Property
Gets "IOException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_FileNotFoundException { get; }
Public Overridable ReadOnly Property ErrorDesc_FileNotFoundException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_HostDown Property

ResourcesErrorDesc_HostDown Property
Gets "Remote host is down." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_HostDown { get; }
Public Overridable ReadOnly Property ErrorDesc_HostDown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_HostNotFound Property

ResourcesErrorDesc_HostNotFound Property
Gets "Remote host not found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_HostNotFound { get; }
Public Overridable ReadOnly Property ErrorDesc_HostNotFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_HostUnreachable Property

ResourcesErrorDesc_HostUnreachable Property
Gets "Remote host is unreachable." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_HostUnreachable { get; }
Public Overridable ReadOnly Property ErrorDesc_HostUnreachable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_IllegalContext Property

ResourcesErrorDesc_IllegalContext Property
Gets "This operation is not allowed in the current context." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_IllegalContext { get; }
Public Overridable ReadOnly Property ErrorDesc_IllegalContext As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_IllegalInCurrentState Property

ResourcesErrorDesc_IllegalInCurrentState Property
Gets "An attempt to call a method of an object in the inappropriate state." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_IllegalInCurrentState { get; }
Public Overridable ReadOnly Property ErrorDesc_IllegalInCurrentState As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_IllegalInMultiThreadMode Property

ResourcesErrorDesc_IllegalInMultiThreadMode Property
Gets "This operation is allowed in single-thread mode only." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_IllegalInMultiThreadMode { get; }
Public Overridable ReadOnly Property ErrorDesc_IllegalInMultiThreadMode As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_IllegalRaiseEventsMode Property

ResourcesErrorDesc_IllegalRaiseEventsMode Property
Gets "Wait is not allowed unless RaiseEventsViaMessageLoop=false." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_IllegalRaiseEventsMode { get; }
Public Overridable ReadOnly Property ErrorDesc_IllegalRaiseEventsMode As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapFolderNotSelected Property

ResourcesErrorDesc_ImapFolderNotSelected Property
Gets "A folder must be selected on the server. Call SelectFolder or ExamineFolder first." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapFolderNotSelected { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapFolderNotSelected As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapIdleNotSupported Property

ResourcesErrorDesc_ImapIdleNotSupported Property
Gets "The IMAP4 server does not support IDLE capability required to go into IDLE mode." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapIdleNotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapIdleNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapMessageIndexNotFound Property

ResourcesErrorDesc_ImapMessageIndexNotFound Property
Gets "The message with the specified index does not exist on the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapMessageIndexNotFound { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapMessageIndexNotFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapNamespaceNotSupported Property

ResourcesErrorDesc_ImapNamespaceNotSupported Property
Gets "The IMAP4 server does not support NAMESPACE capability." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapNamespaceNotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapNamespaceNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapQuotaNotSupported Property

ResourcesErrorDesc_ImapQuotaNotSupported Property
Gets "The IMAP4 server does not support QUOTA capability required to obtain account and folder quotas." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapQuotaNotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapQuotaNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapResponseNotFound Property

ResourcesErrorDesc_ImapResponseNotFound Property
Gets "No required data found in the server response." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapResponseNotFound { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapResponseNotFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapSortNotSupported Property

ResourcesErrorDesc_ImapSortNotSupported Property
Gets "The IMAP4 server does not support SORT capability required to perform sorted search." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapSortNotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapSortNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImapUidPlusNotSupported Property

ResourcesErrorDesc_ImapUidPlusNotSupported Property
Gets "The IMAP4 server does not support UIDPLUS capability required for the current operation to complete." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImapUidPlusNotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_ImapUidPlusNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ImpersonationWin32Error Property

ResourcesErrorDesc_ImpersonationWin32Error Property
Gets "Impersonation-related Win32 function returned an error. See NativeErrorCode property value for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ImpersonationWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_ImpersonationWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InconsistentResponse Property

ResourcesErrorDesc_InconsistentResponse Property
Gets "The response received from the server refers to non-existent data." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InconsistentResponse { get; }
Public Overridable ReadOnly Property ErrorDesc_InconsistentResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InternalError Property

ResourcesErrorDesc_InternalError Property
Gets "Internal error occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InternalError { get; }
Public Overridable ReadOnly Property ErrorDesc_InternalError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidBase64DataInResponse Property

ResourcesErrorDesc_InvalidBase64DataInResponse Property
Gets "Base64 data received from the server cannot be decoded." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidBase64DataInResponse { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidBase64DataInResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidBinaryResponse Property

ResourcesErrorDesc_InvalidBinaryResponse Property
Gets "The binary response received from the server cannot be parsed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidBinaryResponse { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidBinaryResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidDataFormat Property

ResourcesErrorDesc_InvalidDataFormat Property
Gets "Supplied data has invalid format." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidDataFormat { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidDataFormat As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidDataSyntax Property

ResourcesErrorDesc_InvalidDataSyntax Property
Gets "Supplied string has invalid syntax." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidDataSyntax { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidDataSyntax As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidDateFormat Property

ResourcesErrorDesc_InvalidDateFormat Property
Gets "Supplied string date format is invalid." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidDateFormat { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidDateFormat As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidDomain0InCache Property

ResourcesErrorDesc_InvalidDomain0InCache Property
Gets "DNS cache states the domain \"{0}\" does not exist." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidDomain0InCache { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidDomain0InCache As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidImapEnvelope Property

ResourcesErrorDesc_InvalidImapEnvelope Property
Gets The envelope data is corrupted or incorrect. Envelope.IsValid will be false." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidImapEnvelope { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidImapEnvelope As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidOperationException Property

ResourcesErrorDesc_InvalidOperationException Property
Gets "InvalidOperationException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidOperationException { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidOperationException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidResponse Property

ResourcesErrorDesc_InvalidResponse Property
Gets "The response received from the server could not be parsed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidResponse { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_InvalidResponseItem Property

ResourcesErrorDesc_InvalidResponseItem Property
Gets "The particular item of the response data cannot be parsed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_InvalidResponseItem { get; }
Public Overridable ReadOnly Property ErrorDesc_InvalidResponseItem As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_IOException Property

ResourcesErrorDesc_IOException Property
Gets "IOException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_IOException { get; }
Public Overridable ReadOnly Property ErrorDesc_IOException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_JobInBatchFailed Property

ResourcesErrorDesc_JobInBatchFailed Property
Gets "At least one job failed in the batch. Further processing is stopped. Enable/see log file for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_JobInBatchFailed { get; }
Public Overridable ReadOnly Property ErrorDesc_JobInBatchFailed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_LoginWin32Error Property

ResourcesErrorDesc_LoginWin32Error Property
Gets "The server has rejected authentication data sent by the client." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_LoginWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_LoginWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_MessageDataTooLarge Property

ResourcesErrorDesc_MessageDataTooLarge Property
Gets "The length of message data exceeds maximum allowed limit for the given server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_MessageDataTooLarge { get; }
Public Overridable ReadOnly Property ErrorDesc_MessageDataTooLarge As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NegativeResponse Property

ResourcesErrorDesc_NegativeResponse Property
Gets "The server has responded with negative reply." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NegativeResponse { get; }
Public Overridable ReadOnly Property ErrorDesc_NegativeResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoAllowedRecipients Property

ResourcesErrorDesc_NoAllowedRecipients Property
Gets "The server rejected all the recipients of the mail message." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoAllowedRecipients { get; }
Public Overridable ReadOnly Property ErrorDesc_NoAllowedRecipients As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoCredentials Property

ResourcesErrorDesc_NoCredentials Property
Gets "No credentials have been supplied for login." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoCredentials { get; }
Public Overridable ReadOnly Property ErrorDesc_NoCredentials As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoDnsAttemptsLeft Property

ResourcesErrorDesc_NoDnsAttemptsLeft Property
Gets "DNS server has failed too many times and is now considered down." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoDnsAttemptsLeft { get; }
Public Overridable ReadOnly Property ErrorDesc_NoDnsAttemptsLeft As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoDnsServersAvailable Property

ResourcesErrorDesc_NoDnsServersAvailable Property
Gets "At least one DNS server must be registered in the system in order to perform direct send." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoDnsServersAvailable { get; }
Public Overridable ReadOnly Property ErrorDesc_NoDnsServersAvailable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoDnsServersSpecified Property

ResourcesErrorDesc_NoDnsServersSpecified Property
Gets "At least one DNS server must be specified in order to perform direct send or MX query." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoDnsServersSpecified { get; }
Public Overridable ReadOnly Property ErrorDesc_NoDnsServersSpecified As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoDomainsForMXLookup Property

ResourcesErrorDesc_NoDomainsForMXLookup Property
Gets "At least one recipient domain must be specified in order to perform MX lookup." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoDomainsForMXLookup { get; }
Public Overridable ReadOnly Property ErrorDesc_NoDomainsForMXLookup As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoDomainsToSendFor Property

ResourcesErrorDesc_NoDomainsToSendFor Property
Gets "At least one recipient domain must be specified in order to send mail to domains MXes." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoDomainsToSendFor { get; }
Public Overridable ReadOnly Property ErrorDesc_NoDomainsToSendFor As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoIP4AddressesFound Property

ResourcesErrorDesc_NoIP4AddressesFound Property
Gets "No IPv4-compatible end point found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoIP4AddressesFound { get; }
Public Overridable ReadOnly Property ErrorDesc_NoIP4AddressesFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoMessageInImapResponse Property

ResourcesErrorDesc_NoMessageInImapResponse Property
Gets "No required mail message data found in the server response." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoMessageInImapResponse { get; }
Public Overridable ReadOnly Property ErrorDesc_NoMessageInImapResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoOperationToEnd Property

ResourcesErrorDesc_NoOperationToEnd Property
Gets "There is no such operation in progress." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoOperationToEnd { get; }
Public Overridable ReadOnly Property ErrorDesc_NoOperationToEnd As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoRecipients Property

ResourcesErrorDesc_NoRecipients Property
Gets "At least one recipient must be specified." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoRecipients { get; }
Public Overridable ReadOnly Property ErrorDesc_NoRecipients As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoSender Property

ResourcesErrorDesc_NoSender Property
Gets "No sender specified for the mail message." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoSender { get; }
Public Overridable ReadOnly Property ErrorDesc_NoSender As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoSmtpOrDnsServersSpecified Property

ResourcesErrorDesc_NoSmtpOrDnsServersSpecified Property
Gets "At least one DNS or SMTP server must be specified in order to send mail." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoSmtpOrDnsServersSpecified { get; }
Public Overridable ReadOnly Property ErrorDesc_NoSmtpOrDnsServersSpecified As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoSmtpServersSpecified Property

ResourcesErrorDesc_NoSmtpServersSpecified Property
Gets "At least one SMTP server must be specified in order to send to relay server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoSmtpServersSpecified { get; }
Public Overridable ReadOnly Property ErrorDesc_NoSmtpServersSpecified As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NoSupportedLoginMethods Property

ResourcesErrorDesc_NoSupportedLoginMethods Property
Gets "None of the specified authentication methods is supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NoSupportedLoginMethods { get; }
Public Overridable ReadOnly Property ErrorDesc_NoSupportedLoginMethods As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NotConnected Property

ResourcesErrorDesc_NotConnected Property
Gets "Not yet connected to the server. Call Connect first." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NotConnected { get; }
Public Overridable ReadOnly Property ErrorDesc_NotConnected As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NotHelloed Property

ResourcesErrorDesc_NotHelloed Property
Gets "SMTP Hello (HELO or EHLO) has not yet been sent. Call Hello first." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NotHelloed { get; }
Public Overridable ReadOnly Property ErrorDesc_NotHelloed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NotImpersonated Property

ResourcesErrorDesc_NotImpersonated Property
Gets "Not impersonated yet. Call LogonAs first." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NotImpersonated { get; }
Public Overridable ReadOnly Property ErrorDesc_NotImpersonated As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_NotLoggedIn Property

ResourcesErrorDesc_NotLoggedIn Property
Gets "Not yet logged in. Call Login first." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_NotLoggedIn { get; }
Public Overridable ReadOnly Property ErrorDesc_NotLoggedIn As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ObjectReadOnly Property

ResourcesErrorDesc_ObjectReadOnly Property
Gets "An attempt to modify the object state has been made while IsReadOnly is set to true." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ObjectReadOnly { get; }
Public Overridable ReadOnly Property ErrorDesc_ObjectReadOnly As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OK Property

ResourcesErrorDesc_OK Property
Gets "No error." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OK { get; }
Public Overridable ReadOnly Property ErrorDesc_OK As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocAttemptToReplaceExistingBlockAllocationTable Property

ResourcesErrorDesc_OleDocAttemptToReplaceExistingBlockAllocationTable Property
Gets "Attempt to replace existing OLE2 BlockAllocationTable." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocAttemptToReplaceExistingBlockAllocationTable { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocAttemptToReplaceExistingBlockAllocationTable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocBatCountExceedsLimit Property

ResourcesErrorDesc_OleDocBatCountExceedsLimit Property
Gets "OLE2 BAT count exceeds limit, yet XBAT index indicates no valid entries." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocBatCountExceedsLimit { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocBatCountExceedsLimit As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocBlock0AlreadyRemoved Property

ResourcesErrorDesc_OleDocBlock0AlreadyRemoved Property
Gets "OLE2 Block[{0}] already removed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocBlock0AlreadyRemoved { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocBlock0AlreadyRemoved As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocBuildingError Property

ResourcesErrorDesc_OleDocBuildingError Property
Gets "An OLE2 building error occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocBuildingError { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocBuildingError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocCannotOpenInternalDocumentStorage Property

ResourcesErrorDesc_OleDocCannotOpenInternalDocumentStorage Property
Gets "Cannot open internal OLE2 document storage." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocCannotOpenInternalDocumentStorage { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocCannotOpenInternalDocumentStorage As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocCannotRemoveBlock0OutOfRange1 Property

ResourcesErrorDesc_OleDocCannotRemoveBlock0OutOfRange1 Property
Gets "Cannot remove OLE2 block[{0}] out of range[0 - {1}]." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocCannotRemoveBlock0OutOfRange1 { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocCannotRemoveBlock0OutOfRange1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocCannotReturnEmptyData Property

ResourcesErrorDesc_OleDocCannotReturnEmptyData Property
Gets "Cannot return empty OLE2 data." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocCannotReturnEmptyData { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocCannotReturnEmptyData As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocCouldNotFindAllBlocks Property

ResourcesErrorDesc_OleDocCouldNotFindAllBlocks Property
Gets "Could not find all OLE2 blocks." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocCouldNotFindAllBlocks { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocCouldNotFindAllBlocks As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocDuplicateName0 Property

ResourcesErrorDesc_OleDocDuplicateName0 Property
Gets "Duplicate OLE2 name {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocDuplicateName0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocDuplicateName0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocEntry0IsNotDocumentEntry Property

ResourcesErrorDesc_OleDocEntry0IsNotDocumentEntry Property
Gets "OLE2 entry '{0}' is not a DocumentEntry." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocEntry0IsNotDocumentEntry { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocEntry0IsNotDocumentEntry As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocIllegalBlockCount0 Property

ResourcesErrorDesc_OleDocIllegalBlockCount0 Property
Gets "Illegal OLE2 block count; minimum count is 1, got {0} instead." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocIllegalBlockCount0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocIllegalBlockCount0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocImproperlyInitializedList Property

ResourcesErrorDesc_OleDocImproperlyInitializedList Property
Gets "Improperly initialized list: no OLE2 block allocation table provided." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocImproperlyInitializedList { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocImproperlyInitializedList As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocIndex0IsUnused Property

ResourcesErrorDesc_OleDocIndex0IsUnused Property
Gets "OLE2 index {0} is unused." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocIndex0IsUnused { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocIndex0IsUnused As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocInvalidHeaderSignatureRead0Expected1 Property

ResourcesErrorDesc_OleDocInvalidHeaderSignatureRead0Expected1 Property
Gets "Invalid OLE2 header signature (Outlook MSG message must be a binary file with a valid OLE2 signature). Read {0}, expected {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocInvalidHeaderSignatureRead0Expected1 { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocInvalidHeaderSignatureRead0Expected1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocParsingError Property

ResourcesErrorDesc_OleDocParsingError Property
Gets "An OLE2 parsing error occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocParsingError { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocParsingError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocTriedToWriteTooMuchData Property

ResourcesErrorDesc_OleDocTriedToWriteTooMuchData Property
Gets "Tried to write too much OLE2 data." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocTriedToWriteTooMuchData { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocTriedToWriteTooMuchData As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocUnableToReadEntireHeader0ReadExpected1 Property

ResourcesErrorDesc_OleDocUnableToReadEntireHeader0ReadExpected1 Property
Gets "Unable to read the entire OLE2 header: {0} byte(s) read; expected {1} bytes." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocUnableToReadEntireHeader0ReadExpected1 { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocUnableToReadEntireHeader0ReadExpected1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OleDocXmlNotOle2Format Property

ResourcesErrorDesc_OleDocXmlNotOle2Format Property
Gets "The supplied data appears to be in the Office 2007+ XML. MailBee.NET only supports OLE2 document format." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OleDocXmlNotOle2Format { get; }
Public Overridable ReadOnly Property ErrorDesc_OleDocXmlNotOle2Format As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstAttachmentIsEmpty Property

ResourcesErrorDesc_OutlookPstAttachmentIsEmpty Property
Gets "PST attachment is empty." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstAttachmentIsEmpty { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstAttachmentIsEmpty As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstAttemptingToGetNonBinaryData Property

ResourcesErrorDesc_OutlookPstAttemptingToGetNonBinaryData Property
Gets "Attempting to get non-binary data where they are not expected in PST." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstAttemptingToGetNonBinaryData { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstAttemptingToGetNonBinaryData As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstBadSignature0 Property

ResourcesErrorDesc_OutlookPstBadSignature0 Property
Gets "Unable to process PST descriptor node, bad signature: {0}" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstBadSignature0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstBadSignature0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstCantGetChildFoldersForFolder01ChildCount23 Property

ResourcesErrorDesc_OutlookPstCantGetChildFoldersForFolder01ChildCount23 Property
Gets "Can't get child folders for folder {0}({1}) child count: {2} - {3}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstCantGetChildFoldersForFolder01ChildCount23 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstCantGetChildFoldersForFolder01ChildCount23 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstExpectingLocalDescriptorNodeRef Property

ResourcesErrorDesc_OutlookPstExpectingLocalDescriptorNodeRef Property
Gets "Local PST descriptor node ref was expected but not found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstExpectingLocalDescriptorNodeRef { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstExpectingLocalDescriptorNodeRef As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstExternalReferenceButNoLocalDescriptorItems Property

ResourcesErrorDesc_OutlookPstExternalReferenceButNoLocalDescriptorItems Property
Gets "External reference but no localDescriptorItems where they are expected in PST." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstExternalReferenceButNoLocalDescriptorItems { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstExternalReferenceButNoLocalDescriptorItems As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstInvalidDescriptorsOffsetPassed Property

ResourcesErrorDesc_OutlookPstInvalidDescriptorsOffsetPassed Property
Gets "Unable to create PST descriptor, invalid descriptor offset." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstInvalidDescriptorsOffsetPassed { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstInvalidDescriptorsOffsetPassed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstInvalidFileHeader0 Property

ResourcesErrorDesc_OutlookPstInvalidFileHeader0 Property
Gets "Invalid PST file header: {0}, expected: !BDN." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstInvalidFileHeader0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstInvalidFileHeader0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstInvalidInternalBlockSize Property

ResourcesErrorDesc_OutlookPstInvalidInternalBlockSize Property
Gets "Invalid PST internal block size." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstInvalidInternalBlockSize { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstInvalidInternalBlockSize As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstIOExceptionReadingSubNode0 Property

ResourcesErrorDesc_OutlookPstIOExceptionReadingSubNode0 Property
Gets "IOException reading PST subNode: 0x{0:X8}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstIOExceptionReadingSubNode0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstIOExceptionReadingSubNode0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstMissingAttachmentDescriptorItemFor0 Property

ResourcesErrorDesc_OutlookPstMissingAttachmentDescriptorItemFor0 Property
Gets "Missing attachment descriptor item for: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstMissingAttachmentDescriptorItemFor0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstMissingAttachmentDescriptorItemFor0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstMultipleValueArraysInSubdescriptorsUnsupported Property

ResourcesErrorDesc_OutlookPstMultipleValueArraysInSubdescriptorsUnsupported Property
Gets "Multiple value array in PST subdescriptor encountered." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstMultipleValueArraysInSubdescriptorsUnsupported { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstMultipleValueArraysInSubdescriptorsUnsupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstOnlyUnencryptedFilesSupported Property

ResourcesErrorDesc_OutlookPstOnlyUnencryptedFilesSupported Property
Gets "Only unencrypted and compressable PST files are supported at this time." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstOnlyUnencryptedFilesSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstOnlyUnencryptedFilesSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstParsingError Property

ResourcesErrorDesc_OutlookPstParsingError Property
Gets "Outlook .PST file parsing error occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstParsingError { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstParsingError As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToCreate7cTable Property

ResourcesErrorDesc_OutlookPstUnableToCreate7cTable Property
Gets "Unable to create PSTTable7C, table is not 7c." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToCreate7cTable { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToCreate7cTable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToCreateBcTable Property

ResourcesErrorDesc_OutlookPstUnableToCreateBcTable Property
Gets "Unable to create PSTTableBC, table is not bc." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToCreateBcTable { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToCreateBcTable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0Only1InThisEmail Property

ResourcesErrorDesc_OutlookPstUnableToFetchAttachmentNumber0Only1InThisEmail Property
Gets "Unable to fetch PST attachment #{0}, only {1} attachment(s) found in this e-mail message." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0Only1InThisEmail { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0Only1InThisEmail As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0UnableToReadAttachmentDetailsTable Property

ResourcesErrorDesc_OutlookPstUnableToFetchAttachmentNumber0UnableToReadAttachmentDetailsTable Property
Gets "Unable to fetch PST attachment #{0}, unable to read attachment details table." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0UnableToReadAttachmentDetailsTable { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToFetchAttachmentNumber0UnableToReadAttachmentDetailsTable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToFetchRecipientNumber0 Property

ResourcesErrorDesc_OutlookPstUnableToFetchRecipientNumber0 Property
Gets "Unable to fetch PST recipient #{0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToFetchRecipientNumber0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToFetchRecipientNumber0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToFind0 Property

ResourcesErrorDesc_OutlookPstUnableToFind0 Property
Gets "Unable to find {0} in PST data." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToFind0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToFind0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToFindNode0 Property

ResourcesErrorDesc_OutlookPstUnableToFindNode0 Property
Gets "Unable to find PST node: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToFindNode0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToFindNode0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToParseTable0 Property

ResourcesErrorDesc_OutlookPstUnableToParseTable0 Property
Gets "Unable to parse PST table, can't find BTHHEADER header information: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToParseTable0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToParseTable0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToParseTableBadType Property

ResourcesErrorDesc_OutlookPstUnableToParseTableBadType Property
Gets "Unable to parse PST table, bad table type." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToParseTableBadType { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToParseTableBadType As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToParseTableBadType0 Property

ResourcesErrorDesc_OutlookPstUnableToParseTableBadType0 Property
Gets "Unable to parse PST table, bad table type. Unknown identifier: 0x{0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToParseTableBadType0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToParseTableBadType0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToProcessArray Property

ResourcesErrorDesc_OutlookPstUnableToProcessArray Property
Gets "Unable to process PST array, not an array." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToProcessArray { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToProcessArray As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToProcessXBlock Property

ResourcesErrorDesc_OutlookPstUnableToProcessXBlock Property
Gets "Unable to process PST XBlock, incorrect identifier." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToProcessXBlock { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToProcessXBlock As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToReadDescriptorNode Property

ResourcesErrorDesc_OutlookPstUnableToReadDescriptorNode Property
Gets "Unable to read PST descriptor node, not a descriptor." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToReadDescriptorNode { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToReadDescriptorNode As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToReadDescriptorNodeIsNotADescriptor Property

ResourcesErrorDesc_OutlookPstUnableToReadDescriptorNodeIsNotADescriptor Property
Gets "Unable to read descriptor node, is not a descriptor." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToReadDescriptorNodeIsNotADescriptor { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToReadDescriptorNodeIsNotADescriptor As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToReadSignature Property

ResourcesErrorDesc_OutlookPstUnableToReadSignature Property
Gets "Unable to read PST Signature." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToReadSignature { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToReadSignature As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnableToSeekPastEndOfItemSize0SeekingTo1 Property

ResourcesErrorDesc_OutlookPstUnableToSeekPastEndOfItemSize0SeekingTo1 Property
Gets "Unable to seek past end of PST item. size = {0}, seeking to: {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnableToSeekPastEndOfItemSize0SeekingTo1 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnableToSeekPastEndOfItemSize0SeekingTo1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnknownChildType01 Property

ResourcesErrorDesc_OutlookPstUnknownChildType01 Property
Gets "Unknown PST child type: {0} - {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnknownChildType01 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnknownChildType01 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_OutlookPstUnrecognisedPstFileVersion0 Property

ResourcesErrorDesc_OutlookPstUnrecognisedPstFileVersion0 Property
Gets "Unrecognised PST File version: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_OutlookPstUnrecognisedPstFileVersion0 { get; }
Public Overridable ReadOnly Property ErrorDesc_OutlookPstUnrecognisedPstFileVersion0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_Pop3AuthCommandUnknown Property

ResourcesErrorDesc_Pop3AuthCommandUnknown Property
Gets "The server does not support AUTH command. SASL authentication will not be available." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_Pop3AuthCommandUnknown { get; }
Public Overridable ReadOnly Property ErrorDesc_Pop3AuthCommandUnknown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_Pop3CapaCommandUnknown Property

ResourcesErrorDesc_Pop3CapaCommandUnknown Property
Gets "The server does not support CAPA command. POP3 pipelining will not be available." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_Pop3CapaCommandUnknown { get; }
Public Overridable ReadOnly Property ErrorDesc_Pop3CapaCommandUnknown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ProxyAuthMethodsNotAccepted Property

ResourcesErrorDesc_ProxyAuthMethodsNotAccepted Property
Gets "None of the methods listed by the client to the proxy server are acceptable." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ProxyAuthMethodsNotAccepted { get; }
Public Overridable ReadOnly Property ErrorDesc_ProxyAuthMethodsNotAccepted As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ProxyConnectionDeclined Property

ResourcesErrorDesc_ProxyConnectionDeclined Property
Gets "The proxy server declined to act as a proxy gateway for the given client." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ProxyConnectionDeclined { get; }
Public Overridable ReadOnly Property ErrorDesc_ProxyConnectionDeclined As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ProxyGssApiAuthFailed Property

ResourcesErrorDesc_ProxyGssApiAuthFailed Property
Gets "Proxy GSSAPI authentication failed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ProxyGssApiAuthFailed { get; }
Public Overridable ReadOnly Property ErrorDesc_ProxyGssApiAuthFailed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ProxyUserPassAuthFailed Property

ResourcesErrorDesc_ProxyUserPassAuthFailed Property
Gets "Proxy Username/Password authentication failed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ProxyUserPassAuthFailed { get; }
Public Overridable ReadOnly Property ErrorDesc_ProxyUserPassAuthFailed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_ResponseTimeout Property

ResourcesErrorDesc_ResponseTimeout Property
Gets "Establishing connection with the server has been aborted as it was too slow." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_ResponseTimeout { get; }
Public Overridable ReadOnly Property ErrorDesc_ResponseTimeout As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SaslAnswerRejected Property

ResourcesErrorDesc_SaslAnswerRejected Property
Gets "The server has rejected authentication data sent by the client." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SaslAnswerRejected { get; }
Public Overridable ReadOnly Property ErrorDesc_SaslAnswerRejected As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SmimeWin32Error Property

ResourcesErrorDesc_SmimeWin32Error Property
Gets "S/MIME-related Win32 function returned an error. See NativeErrorCode property value for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SmimeWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_SmimeWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SocketDisposed Property

ResourcesErrorDesc_SocketDisposed Property
Gets "The socket object used by MailBee was unexpectedly closed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SocketDisposed { get; }
Public Overridable ReadOnly Property ErrorDesc_SocketDisposed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SocketException Property

ResourcesErrorDesc_SocketException Property
Gets "SocketException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SocketException { get; }
Public Overridable ReadOnly Property ErrorDesc_SocketException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SocketTimeout Property

ResourcesErrorDesc_SocketTimeout Property
Gets "Socket connection has timed out." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SocketTimeout { get; }
Public Overridable ReadOnly Property ErrorDesc_SocketTimeout As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SslNegoAuthException Property

ResourcesErrorDesc_SslNegoAuthException Property
Gets "AuthenticationException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SslNegoAuthException { get; }
Public Overridable ReadOnly Property ErrorDesc_SslNegoAuthException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SslNegoException Property

ResourcesErrorDesc_SslNegoException Property
Gets "Exception occurred during SSL negotiation." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SslNegoException { get; }
Public Overridable ReadOnly Property ErrorDesc_SslNegoException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SslNegoIOException Property

ResourcesErrorDesc_SslNegoIOException Property
Gets "IOException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SslNegoIOException { get; }
Public Overridable ReadOnly Property ErrorDesc_SslNegoIOException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SslNegoNotSupportedException Property

ResourcesErrorDesc_SslNegoNotSupportedException Property
Gets "NotSupportedException occurred during SSL negotiation. Perhaps, you need to specify a more secure protocol such as TLS 1.2 (see SecurityProtocol.TlsAuto)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SslNegoNotSupportedException { get; }
Public Overridable ReadOnly Property ErrorDesc_SslNegoNotSupportedException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SslWin32Error Property

ResourcesErrorDesc_SslWin32Error Property
Gets "SSL-related Win32 function returned an error. See NativeErrorCode property value for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SslWin32Error { get; }
Public Overridable ReadOnly Property ErrorDesc_SslWin32Error As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_StartTlsNotAvailable Property

ResourcesErrorDesc_StartTlsNotAvailable Property
Gets "The server does not support STARTTLS (STLS for POP3) command." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_StartTlsNotAvailable { get; }
Public Overridable ReadOnly Property ErrorDesc_StartTlsNotAvailable As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_StreamCannotRead Property

ResourcesErrorDesc_StreamCannotRead Property
Gets "The specified stream is closed or write-only or doesn't support seeking (random access)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_StreamCannotRead { get; }
Public Overridable ReadOnly Property ErrorDesc_StreamCannotRead As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_StreamCannotWrite Property

ResourcesErrorDesc_StreamCannotWrite Property
Gets "The specified stream is closed or read-only or doesn't support seeking (random access)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_StreamCannotWrite { get; }
Public Overridable ReadOnly Property ErrorDesc_StreamCannotWrite As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_SyncIONotSupported Property

ResourcesErrorDesc_SyncIONotSupported Property
Gets "Sync I/O not supported by this platform. Use async I/O instead." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_SyncIONotSupported { get; }
Public Overridable ReadOnly Property ErrorDesc_SyncIONotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefAttributeChecksumInvalid Property

ResourcesErrorDesc_TnefAttributeChecksumInvalid Property
Gets "Invalid checksum of TNEF attribute." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefAttributeChecksumInvalid { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefAttributeChecksumInvalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefAttributeLevelInvalid0 Property

ResourcesErrorDesc_TnefAttributeLevelInvalid0 Property
Gets "Invalid TNEF attribute level: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefAttributeLevelInvalid0 { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefAttributeLevelInvalid0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefCompressedRtfCrc32Failed Property

ResourcesErrorDesc_TnefCompressedRtfCrc32Failed Property
Gets "TNEF compressed-RTF CRC32 failed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefCompressedRtfCrc32Failed { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefCompressedRtfCrc32Failed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefCompressedRtfDataSizeMismatch Property

ResourcesErrorDesc_TnefCompressedRtfDataSizeMismatch Property
Gets "TNEF compressed-RTF data size mismatch." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefCompressedRtfDataSizeMismatch { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefCompressedRtfDataSizeMismatch As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefCompressedRtfHeaderInvalid Property

ResourcesErrorDesc_TnefCompressedRtfHeaderInvalid Property
Gets "Invalid TNEF compressed-RTF header." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefCompressedRtfHeaderInvalid { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefCompressedRtfHeaderInvalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefGuidInvalid0 Property

ResourcesErrorDesc_TnefGuidInvalid0 Property
Gets "Invalid TNEF Guid: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefGuidInvalid0 { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefGuidInvalid0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefLevelTypeInvalid0 Property

ResourcesErrorDesc_TnefLevelTypeInvalid0 Property
Gets "Invalid TNEF level type: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefLevelTypeInvalid0 { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefLevelTypeInvalid0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefMapiMultivalueIsNotAllowedInSingleMapiValue Property

ResourcesErrorDesc_TnefMapiMultivalueIsNotAllowedInSingleMapiValue Property
Gets "Multivalue is not allowed in single MapiValue." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefMapiMultivalueIsNotAllowedInSingleMapiValue { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefMapiMultivalueIsNotAllowedInSingleMapiValue As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefMapiPropTypeInvalid0 Property

ResourcesErrorDesc_TnefMapiPropTypeInvalid0 Property
Gets "Invalid MapiProp type: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefMapiPropTypeInvalid0 { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefMapiPropTypeInvalid0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefMapiTypeUnknown0 Property

ResourcesErrorDesc_TnefMapiTypeUnknown0 Property
Gets "Unknown TNEF MAPI type: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefMapiTypeUnknown0 { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefMapiTypeUnknown0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefSignature0Invalid Property

ResourcesErrorDesc_TnefSignature0Invalid Property
Gets "Invalid TNEF signature 0x{0} (not a valid TNEF stream)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefSignature0Invalid { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefSignature0Invalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefUnexpectedEndOfStream Property

ResourcesErrorDesc_TnefUnexpectedEndOfStream Property
Gets "Unexpected end of TNEF stream." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefUnexpectedEndOfStream { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefUnexpectedEndOfStream As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_TnefUnknownRtfCompressionType0 Property

ResourcesErrorDesc_TnefUnknownRtfCompressionType0 Property
Gets "TNEF Unknown RTF compression type (magic number {0})." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_TnefUnknownRtfCompressionType0 { get; }
Public Overridable ReadOnly Property ErrorDesc_TnefUnknownRtfCompressionType0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_UnauthorizedAccessException Property

ResourcesErrorDesc_UnauthorizedAccessException Property
Gets "IOException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_UnauthorizedAccessException { get; }
Public Overridable ReadOnly Property ErrorDesc_UnauthorizedAccessException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_Unknown Property

ResourcesErrorDesc_Unknown Property
Gets "Unknown error." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_Unknown { get; }
Public Overridable ReadOnly Property ErrorDesc_Unknown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_UnsupportedLoginMethod Property

ResourcesErrorDesc_UnsupportedLoginMethod Property
Gets "The specified authentication method is not supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_UnsupportedLoginMethod { get; }
Public Overridable ReadOnly Property ErrorDesc_UnsupportedLoginMethod As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_WebException Property

ResourcesErrorDesc_WebException Property
Gets "IOException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_WebException { get; }
Public Overridable ReadOnly Property ErrorDesc_WebException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDesc_XmlException Property

ResourcesErrorDesc_XmlException Property
Gets "IOException occurred." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDesc_XmlException { get; }
Public Overridable ReadOnly Property ErrorDesc_XmlException As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_DnsResponseCode0HostName1Base64EncodedData2 Property

ResourcesErrorDescSuffix_DnsResponseCode0HostName1Base64EncodedData2 Property
Gets " DnsResponseCode: {0}, HostName DNS server was queried about: \"{1}\", Base64 encoded response data: {2} (trailing zero bytes truncated)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_DnsResponseCode0HostName1Base64EncodedData2 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_DnsResponseCode0HostName1Base64EncodedData2 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_ImapInvalidEnvelopeMessageNumber0 Property

ResourcesErrorDescSuffix_ImapInvalidEnvelopeMessageNumber0 Property
Gets " The invalid envelope message number is: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_ImapInvalidEnvelopeMessageNumber0 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_ImapInvalidEnvelopeMessageNumber0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_ImapNonExistentMessageNumber0 Property

ResourcesErrorDescSuffix_ImapNonExistentMessageNumber0 Property
Gets " Non-existent message number is: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_ImapNonExistentMessageNumber0 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_ImapNonExistentMessageNumber0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_ImapNonExistentUid0 Property

ResourcesErrorDescSuffix_ImapNonExistentUid0 Property
Gets " Non-existent UID is: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_ImapNonExistentUid0 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_ImapNonExistentUid0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_InnerException0 Property

ResourcesErrorDescSuffix_InnerException0 Property
Gets " InnerException message follows: {0}" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_InnerException0 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_InnerException0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_ResponseString0 Property

ResourcesErrorDescSuffix_ResponseString0 Property
Gets " The server responded: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_ResponseString0 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_ResponseString0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_ServerResponded0 Property

ResourcesErrorDescSuffix_ServerResponded0 Property
Gets " The server responded: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_ServerResponded0 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_ServerResponded0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.ErrorDescSuffix_Win32ErrorCode0Desc1 Property

ResourcesErrorDescSuffix_Win32ErrorCode0Desc1 Property
Gets " The Win32 error code is: {0}. The Win32 description is: {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string ErrorDescSuffix_Win32ErrorCode0Desc1 { get; }
Public Overridable ReadOnly Property ErrorDescSuffix_Win32ErrorCode0Desc1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Instance Property

ResourcesInstance Property
Gets or sets the object of either Resources class or any derived class, which defines string resources used by MailBee.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static Resources Instance { get; set; }
Public Shared Property Instance As Resources
    Get
    Set

Property Value

Type: Resources
The object of either Resources class or any derived class, which defines (for Resources class) or overrides (for the derived class) string properties which are used by MailBee to provide textual information (such as log or error messages) to the application.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
If custom resources object should be used for a limited period of time, the developer can save the original value of Instance property into the variable, then assign the new value (a reference to the instance of the class derived from Resources), and finally set Instance property back to the saved reference to the original Resources object when custom resources are no longer needed.
See Also

Reference

Resources Class
MailBee Namespace


Resources.LicenseKeyComVersion Property

ResourcesLicenseKeyComVersion Property
Gets "LicenseKey is for MailBee COM/ActiveX version rather than MailBee.NET version." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LicenseKeyComVersion { get; }
Public Overridable ReadOnly Property LicenseKeyComVersion As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.LicenseKeyInvalid Property

ResourcesLicenseKeyInvalid Property
Gets "LicenseKey is invalid. See documentation on MailBee.Global.LicenseKey property of the component for more information." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LicenseKeyInvalid { get; }
Public Overridable ReadOnly Property LicenseKeyInvalid As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.LicenseKeyIsWriteOnlyWarning Property

ResourcesLicenseKeyIsWriteOnlyWarning Property
Gets "Warning: LicenseKey property is write-only." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LicenseKeyIsWriteOnlyWarning { get; }
Public Overridable ReadOnly Property LicenseKeyIsWriteOnlyWarning As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.LicenseKeyOlderVersion Property

ResourcesLicenseKeyOlderVersion Property
Gets "LicenseKey is for an older version of MailBee.NET components." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LicenseKeyOlderVersion { get; }
Public Overridable ReadOnly Property LicenseKeyOlderVersion As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.LicenseKeyTrialExpired Property

ResourcesLicenseKeyTrialExpired Property
Gets "Trial LicenseKey is expired." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LicenseKeyTrialExpired { get; }
Public Overridable ReadOnly Property LicenseKeyTrialExpired As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_0BytesReceived Property

ResourcesLog_0BytesReceived Property
Gets "Total {0} bytes received." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_0BytesReceived { get; }
Public Overridable ReadOnly Property Log_0BytesReceived As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_0BytesSent Property

ResourcesLog_0BytesSent Property
Gets "Data chunk of {0} bytes sent." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_0BytesSent { get; }
Public Overridable ReadOnly Property Log_0BytesSent As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_AbortRequested Property

ResourcesLog_AbortRequested Property
Gets "User code called Abort." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_AbortRequested { get; }
Public Overridable ReadOnly Property Log_AbortRequested As String
    Get

Property Value

Type: String
Remarks
This member is no longer used.
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_AssemblyVersion0 Property

ResourcesLog_AssemblyVersion0 Property
Gets "Assembly version: {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_AssemblyVersion0 { get; }
Public Overridable ReadOnly Property Log_AssemblyVersion0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Base64Banner Property

ResourcesLog_Base64Banner Property
Gets "Binary data is Base64-encoded" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Base64Banner { get; }
Public Overridable ReadOnly Property Log_Base64Banner As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ConnectedToServerAtHost0OnPort1 Property

ResourcesLog_ConnectedToServerAtHost0OnPort1 Property
Gets "Connected to mail service at host \"{0}\" on port {1} and ready." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ConnectedToServerAtHost0OnPort1 { get; }
Public Overridable ReadOnly Property Log_ConnectedToServerAtHost0OnPort1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DisconnectedFromHost0 Property

ResourcesLog_DisconnectedFromHost0 Property
Gets "Disconnected from host \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DisconnectedFromHost0 { get; }
Public Overridable ReadOnly Property Log_DisconnectedFromHost0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Dns0RecordsFoundForHost1 Property

ResourcesLog_Dns0RecordsFoundForHost1 Property
Gets "{0} DNS record(s) found for host \"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Dns0RecordsFoundForHost1 { get; }
Public Overridable ReadOnly Property Log_Dns0RecordsFoundForHost1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsCreatingQueryAboutHost0 Property

ResourcesLog_DnsCreatingQueryAboutHost0 Property
Gets "Creating DNS query about host \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsCreatingQueryAboutHost0 { get; }
Public Overridable ReadOnly Property Log_DnsCreatingQueryAboutHost0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsParsingReceivedResponse Property

ResourcesLog_DnsParsingReceivedResponse Property
Gets "Parsing a response that was received from DNS server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsParsingReceivedResponse { get; }
Public Overridable ReadOnly Property Log_DnsParsingReceivedResponse As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsQueryDone Property

ResourcesLog_DnsQueryDone Property
Gets "DNS query done." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsQueryDone { get; }
Public Overridable ReadOnly Property Log_DnsQueryDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecordOfATypeHasIP0 Property

ResourcesLog_DnsRecordOfATypeHasIP0 Property
Gets "DNS record of A type. IP={0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecordOfATypeHasIP0 { get; }
Public Overridable ReadOnly Property Log_DnsRecordOfATypeHasIP0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecordOfCNameTypeIsAliasFor0 Property

ResourcesLog_DnsRecordOfCNameTypeIsAliasFor0 Property
Gets "DNS record of CNAME type. Alias for \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecordOfCNameTypeIsAliasFor0 { get; }
Public Overridable ReadOnly Property Log_DnsRecordOfCNameTypeIsAliasFor0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecordOfMXTypeHasSmtpHost0OfPreference1 Property

ResourcesLog_DnsRecordOfMXTypeHasSmtpHost0OfPreference1 Property
Gets DNS record of MX type. SmtpHost=\"{0}\", Preference={1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecordOfMXTypeHasSmtpHost0OfPreference1 { get; }
Public Overridable ReadOnly Property Log_DnsRecordOfMXTypeHasSmtpHost0OfPreference1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecordOfPtrTypeDenotesDomain0 Property

ResourcesLog_DnsRecordOfPtrTypeDenotesDomain0 Property
Gets "DNS record of PTR type. Denotes domain \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecordOfPtrTypeDenotesDomain0 { get; }
Public Overridable ReadOnly Property Log_DnsRecordOfPtrTypeDenotesDomain0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecordOfTxtTypeHas0Strings Property

ResourcesLog_DnsRecordOfTxtTypeHas0Strings Property
Gets "DNS record of TXT type. Has {0} strings." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecordOfTxtTypeHas0Strings { get; }
Public Overridable ReadOnly Property Log_DnsRecordOfTxtTypeHas0Strings As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecordOfUnknownType Property

ResourcesLog_DnsRecordOfUnknownType Property
Gets "DNS record of unknown type detected." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecordOfUnknownType { get; }
Public Overridable ReadOnly Property Log_DnsRecordOfUnknownType As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecursionIsNotSupported Property

ResourcesLog_DnsRecursionIsNotSupported Property
Gets "Recursion is not supported by DNS server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecursionIsNotSupported { get; }
Public Overridable ReadOnly Property Log_DnsRecursionIsNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecursionIsSupported Property

ResourcesLog_DnsRecursionIsSupported Property
Gets "Recursion is supported by DNS server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecursionIsSupported { get; }
Public Overridable ReadOnly Property Log_DnsRecursionIsSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsRecursionStatusUnknown Property

ResourcesLog_DnsRecursionStatusUnknown Property
Gets "Recursion status is unknown for the given DNS server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsRecursionStatusUnknown { get; }
Public Overridable ReadOnly Property Log_DnsRecursionStatusUnknown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_DnsSendingQueryToEndPoint0 Property

ResourcesLog_DnsSendingQueryToEndPoint0 Property
Gets "Sending query to DNS server at \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_DnsSendingQueryToEndPoint0 { get; }
Public Overridable ReadOnly Property Log_DnsSendingQueryToEndPoint0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Error0 Property

ResourcesLog_Error0 Property
Gets "Error: {0}" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Error0 { get; }
Public Overridable ReadOnly Property Log_Error0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Ews0AttachmentsReturned Property

ResourcesLog_Ews0AttachmentsReturned Property
Gets "{0} attachments returned." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Ews0AttachmentsReturned { get; }
Public Overridable ReadOnly Property Log_Ews0AttachmentsReturned As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsAttachmentNotFound Property

ResourcesLog_EwsAttachmentNotFound Property
Gets "Attachment not found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsAttachmentNotFound { get; }
Public Overridable ReadOnly Property Log_EwsAttachmentNotFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsDownloadFolderByFullNameRecursivelyFoundNothing Property

ResourcesLog_EwsDownloadFolderByFullNameRecursivelyFoundNothing Property
Gets "Finding folder by full name recursively found nothing" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsDownloadFolderByFullNameRecursivelyFoundNothing { get; }
Public Overridable ReadOnly Property Log_EwsDownloadFolderByFullNameRecursivelyFoundNothing As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsFolderFullName0AlreadyExists Property

ResourcesLog_EwsFolderFullName0AlreadyExists Property
Gets "Folder full name \"{0}\" already exists." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsFolderFullName0AlreadyExists { get; }
Public Overridable ReadOnly Property Log_EwsFolderFullName0AlreadyExists As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsFolderFullName0MatchedToId1 Property

ResourcesLog_EwsFolderFullName0MatchedToId1 Property
Gets "Folder full name \"{0}\" matched to folder ID {1}" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsFolderFullName0MatchedToId1 { get; }
Public Overridable ReadOnly Property Log_EwsFolderFullName0MatchedToId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsFolderFullName0NotFound Property

ResourcesLog_EwsFolderFullName0NotFound Property
Gets "Folder full name \"{0}\" not found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsFolderFullName0NotFound { get; }
Public Overridable ReadOnly Property Log_EwsFolderFullName0NotFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsOperationDone Property

ResourcesLog_EwsOperationDone Property
Gets "Operation done." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsOperationDone { get; }
Public Overridable ReadOnly Property Log_EwsOperationDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsOperationDone0ItemsReturned Property

ResourcesLog_EwsOperationDone0ItemsReturned Property
Gets "Operation done, {0} item(s) returned." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsOperationDone0ItemsReturned { get; }
Public Overridable ReadOnly Property Log_EwsOperationDone0ItemsReturned As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsOperationDone0MessagesDeleted Property

ResourcesLog_EwsOperationDone0MessagesDeleted Property
Gets "Operation done, {0} messages deleted." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsOperationDone0MessagesDeleted { get; }
Public Overridable ReadOnly Property Log_EwsOperationDone0MessagesDeleted As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillAddAttachmentAndUpdateItem Property

ResourcesLog_EwsWillAddAttachmentAndUpdateItem Property
Gets "Will add attachment and update item." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillAddAttachmentAndUpdateItem { get; }
Public Overridable ReadOnly Property Log_EwsWillAddAttachmentAndUpdateItem As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillBindFolderId0 Property

ResourcesLog_EwsWillBindFolderId0 Property
Gets "Will bind folder ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillBindFolderId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillBindFolderId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillBindItemId0 Property

ResourcesLog_EwsWillBindItemId0 Property
Gets "Will bind item ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillBindItemId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillBindItemId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillCheckFolderExistsByFullName0 Property

ResourcesLog_EwsWillCheckFolderExistsByFullName0 Property
Gets "Will check folder existance by full name \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillCheckFolderExistsByFullName0 { get; }
Public Overridable ReadOnly Property Log_EwsWillCheckFolderExistsByFullName0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillCheckFolderExistsByShortName0InParentFolderId1 Property

ResourcesLog_EwsWillCheckFolderExistsByShortName0InParentFolderId1 Property
Gets "Will check folder existance by short name \"{0}\" in parent folder ID {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillCheckFolderExistsByShortName0InParentFolderId1 { get; }
Public Overridable ReadOnly Property Log_EwsWillCheckFolderExistsByShortName0InParentFolderId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillCopyItemToFolderId0 Property

ResourcesLog_EwsWillCopyItemToFolderId0 Property
Gets "Will copy item to folder ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillCopyItemToFolderId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillCopyItemToFolderId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillCreateFolder0 Property

ResourcesLog_EwsWillCreateFolder0 Property
Gets "Will create folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillCreateFolder0 { get; }
Public Overridable ReadOnly Property Log_EwsWillCreateFolder0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillCreateFolder0InId1 Property

ResourcesLog_EwsWillCreateFolder0InId1 Property
Gets "Will create folder \"{0}\" in folder ID {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillCreateFolder0InId1 { get; }
Public Overridable ReadOnly Property Log_EwsWillCreateFolder0InId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDelete0AttachmentsAndUpdateItem Property

ResourcesLog_EwsWillDelete0AttachmentsAndUpdateItem Property
Gets "Will delete {0} attachment(s) and update item." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDelete0AttachmentsAndUpdateItem { get; }
Public Overridable ReadOnly Property Log_EwsWillDelete0AttachmentsAndUpdateItem As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDeleteAllAttachmentsAndUpdateItem Property

ResourcesLog_EwsWillDeleteAllAttachmentsAndUpdateItem Property
Gets "Will delete all attachments and update item." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDeleteAllAttachmentsAndUpdateItem { get; }
Public Overridable ReadOnly Property Log_EwsWillDeleteAllAttachmentsAndUpdateItem As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDeleteFolderUsingMethod0 Property

ResourcesLog_EwsWillDeleteFolderUsingMethod0 Property
Gets "Will delete folder using method {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDeleteFolderUsingMethod0 { get; }
Public Overridable ReadOnly Property Log_EwsWillDeleteFolderUsingMethod0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDeleteItemsUsingMethod0 Property

ResourcesLog_EwsWillDeleteItemsUsingMethod0 Property
Gets "Will delete items using method {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDeleteItemsUsingMethod0 { get; }
Public Overridable ReadOnly Property Log_EwsWillDeleteItemsUsingMethod0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDeleteItemUsingMethod0 Property

ResourcesLog_EwsWillDeleteItemUsingMethod0 Property
Gets "Will delete item using method {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDeleteItemUsingMethod0 { get; }
Public Overridable ReadOnly Property Log_EwsWillDeleteItemUsingMethod0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDownloadFolderByFullName0InContainingFolderId1 Property

ResourcesLog_EwsWillDownloadFolderByFullName0InContainingFolderId1 Property
Gets "Will find and download folder by full name \"{0}\" in containing folder ID {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDownloadFolderByFullName0InContainingFolderId1 { get; }
Public Overridable ReadOnly Property Log_EwsWillDownloadFolderByFullName0InContainingFolderId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDownloadFolderByFullName0Recursively Property

ResourcesLog_EwsWillDownloadFolderByFullName0Recursively Property
Gets "Will find and download folder by full name \"{0}\" recursively." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDownloadFolderByFullName0Recursively { get; }
Public Overridable ReadOnly Property Log_EwsWillDownloadFolderByFullName0Recursively As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillDownloadFolderByShortName0InParentFolderId1 Property

ResourcesLog_EwsWillDownloadFolderByShortName0InParentFolderId1 Property
Gets "Will find and download folder by short name \"{0}\" in parent folder ID {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillDownloadFolderByShortName0InParentFolderId1 { get; }
Public Overridable ReadOnly Property Log_EwsWillDownloadFolderByShortName0InParentFolderId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillEmptyFolderUsingMethod0 Property

ResourcesLog_EwsWillEmptyFolderUsingMethod0 Property
Gets "Will empty folder using method {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillEmptyFolderUsingMethod0 { get; }
Public Overridable ReadOnly Property Log_EwsWillEmptyFolderUsingMethod0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillFindFolderIdByShortName0InParentFolderId1 Property

ResourcesLog_EwsWillFindFolderIdByShortName0InParentFolderId1 Property
Gets "Will find FolderId by short name \"{0}\" in parent folder ID {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillFindFolderIdByShortName0InParentFolderId1 { get; }
Public Overridable ReadOnly Property Log_EwsWillFindFolderIdByShortName0InParentFolderId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillFindFolders Property

ResourcesLog_EwsWillFindFolders Property
Gets "Will find folders." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillFindFolders { get; }
Public Overridable ReadOnly Property Log_EwsWillFindFolders As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillFindItemsInFolderId0 Property

ResourcesLog_EwsWillFindItemsInFolderId0 Property
Gets "Will find items in folder ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillFindItemsInFolderId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillFindItemsInFolderId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillGet0Attachments Property

ResourcesLog_EwsWillGet0Attachments Property
Gets "Will get {0} attachment(s)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillGet0Attachments { get; }
Public Overridable ReadOnly Property Log_EwsWillGet0Attachments As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillLoadPropertiesForItems Property

ResourcesLog_EwsWillLoadPropertiesForItems Property
Gets "Will load properties for items." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillLoadPropertiesForItems { get; }
Public Overridable ReadOnly Property Log_EwsWillLoadPropertiesForItems As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillMoveFolderToId0 Property

ResourcesLog_EwsWillMoveFolderToId0 Property
Gets "Will move folder to folder ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillMoveFolderToId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillMoveFolderToId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillMoveItemToFolderId0 Property

ResourcesLog_EwsWillMoveItemToFolderId0 Property
Gets "Will move item to folder ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillMoveItemToFolderId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillMoveItemToFolderId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillRenameFolderTo0 Property

ResourcesLog_EwsWillRenameFolderTo0 Property
Gets "Will rename folder to \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillRenameFolderTo0 { get; }
Public Overridable ReadOnly Property Log_EwsWillRenameFolderTo0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillRenameOrMoveFolderWithOldFullName0ToNewFullName1 Property

ResourcesLog_EwsWillRenameOrMoveFolderWithOldFullName0ToNewFullName1 Property
Gets "Will rename or move folder with old full name \"{0}\" to new full name \"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillRenameOrMoveFolderWithOldFullName0ToNewFullName1 { get; }
Public Overridable ReadOnly Property Log_EwsWillRenameOrMoveFolderWithOldFullName0ToNewFullName1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillResolveName0 Property

ResourcesLog_EwsWillResolveName0 Property
Gets "Will resolve name \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillResolveName0 { get; }
Public Overridable ReadOnly Property Log_EwsWillResolveName0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillSendEmail Property

ResourcesLog_EwsWillSendEmail Property
Gets "Will send email." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillSendEmail { get; }
Public Overridable ReadOnly Property Log_EwsWillSendEmail As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillSendEmailAndSaveCopy Property

ResourcesLog_EwsWillSendEmailAndSaveCopy Property
Gets "Will send email and save copy." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillSendEmailAndSaveCopy { get; }
Public Overridable ReadOnly Property Log_EwsWillSendEmailAndSaveCopy As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillSendEmailAndSaveCopyInFolderId0 Property

ResourcesLog_EwsWillSendEmailAndSaveCopyInFolderId0 Property
Gets "Will send email and save copy in folder ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillSendEmailAndSaveCopyInFolderId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillSendEmailAndSaveCopyInFolderId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillUpdateItemId0 Property

ResourcesLog_EwsWillUpdateItemId0 Property
Gets "Will update item ID {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillUpdateItemId0 { get; }
Public Overridable ReadOnly Property Log_EwsWillUpdateItemId0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_EwsWillUpload0BytesMessageIntoFolderId1 Property

ResourcesLog_EwsWillUpload0BytesMessageIntoFolderId1 Property
Gets "Will upload {0} bytes message into folder ID {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_EwsWillUpload0BytesMessageIntoFolderId1 { get; }
Public Overridable ReadOnly Property Log_EwsWillUpload0BytesMessageIntoFolderId1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Host0ResolvedToIP1 Property

ResourcesLog_Host0ResolvedToIP1 Property
Gets "Host \"{0}\" resolved to IP address(es) {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Host0ResolvedToIP1 { get; }
Public Overridable ReadOnly Property Log_Host0ResolvedToIP1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapCloseFolder Property

ResourcesLog_ImapCloseFolder Property
Gets "Close folder." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapCloseFolder { get; }
Public Overridable ReadOnly Property Log_ImapCloseFolder As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapCopyMessagesDone Property

ResourcesLog_ImapCopyMessagesDone Property
Gets "Messages copied." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapCopyMessagesDone { get; }
Public Overridable ReadOnly Property Log_ImapCopyMessagesDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapDownloadEnvelopesDone Property

ResourcesLog_ImapDownloadEnvelopesDone Property
Gets "Envelopes downloaded" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapDownloadEnvelopesDone { get; }
Public Overridable ReadOnly Property Log_ImapDownloadEnvelopesDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapDownloadFoldersDone Property

ResourcesLog_ImapDownloadFoldersDone Property
Gets "Folder list downloaded." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapDownloadFoldersDone { get; }
Public Overridable ReadOnly Property Log_ImapDownloadFoldersDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapExpunge Property

ResourcesLog_ImapExpunge Property
Gets "Expunge all deleted messages from the folder." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapExpunge { get; }
Public Overridable ReadOnly Property Log_ImapExpunge As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapExpunge0 Property

ResourcesLog_ImapExpunge0 Property
Gets "Expunge messages with UIDs \"{0}\" from the folder." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapExpunge0 { get; }
Public Overridable ReadOnly Property Log_ImapExpunge0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapFolderQuota0 Property

ResourcesLog_ImapFolderQuota0 Property
Gets "Obtain quota limits and usage for folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapFolderQuota0 { get; }
Public Overridable ReadOnly Property Log_ImapFolderQuota0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapFolderStatus0 Property

ResourcesLog_ImapFolderStatus0 Property
Gets "Get statistics for folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapFolderStatus0 { get; }
Public Overridable ReadOnly Property Log_ImapFolderStatus0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapGetCapabilitiesViaCapability Property

ResourcesLog_ImapGetCapabilitiesViaCapability Property
Gets "Get the list of IMAP4 capabilities via CAPABILITY command." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapGetCapabilitiesViaCapability { get; }
Public Overridable ReadOnly Property Log_ImapGetCapabilitiesViaCapability As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapGettingQuotaFromList Property

ResourcesLog_ImapGettingQuotaFromList Property
Gets "Processing a single quota from quota list." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapGettingQuotaFromList { get; }
Public Overridable ReadOnly Property Log_ImapGettingQuotaFromList As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapIdleDone Property

ResourcesLog_ImapIdleDone Property
Gets "Idle done." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapIdleDone { get; }
Public Overridable ReadOnly Property Log_ImapIdleDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapLiteralOfLength0 Property

ResourcesLog_ImapLiteralOfLength0 Property
Gets "Literal of length {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapLiteralOfLength0 { get; }
Public Overridable ReadOnly Property Log_ImapLiteralOfLength0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapManageFolder0 Property

ResourcesLog_ImapManageFolder0 Property
Gets "Manage folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapManageFolder0 { get; }
Public Overridable ReadOnly Property Log_ImapManageFolder0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapMatchingQuotaFound Property

ResourcesLog_ImapMatchingQuotaFound Property
Gets "Matching quota found." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapMatchingQuotaFound { get; }
Public Overridable ReadOnly Property Log_ImapMatchingQuotaFound As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapMoveMessagesDone Property

ResourcesLog_ImapMoveMessagesDone Property
Gets "Messages moved." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapMoveMessagesDone { get; }
Public Overridable ReadOnly Property Log_ImapMoveMessagesDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapNamespace Property

ResourcesLog_ImapNamespace Property
Gets "Get namespaces for the account." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapNamespace { get; }
Public Overridable ReadOnly Property Log_ImapNamespace As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapPreauthenticatedUser Property

ResourcesLog_ImapPreauthenticatedUser Property
Gets "Preauthenticated user" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapPreauthenticatedUser { get; }
Public Overridable ReadOnly Property Log_ImapPreauthenticatedUser As String
    Get

Property Value

Type: String
Remarks
This string is used in conjunction with Log_LoggedInAs0 when the user was pre-authenticated by external means. MailBee detects this when PREAUTH response is received from the IMAP4 server.
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapRenameFolder0To1 Property

ResourcesLog_ImapRenameFolder0To1 Property
Gets "Rename folder \"{0}\" to \"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapRenameFolder0To1 { get; }
Public Overridable ReadOnly Property Log_ImapRenameFolder0To1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapSearchDone Property

ResourcesLog_ImapSearchDone Property
Gets "Search done." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapSearchDone { get; }
Public Overridable ReadOnly Property Log_ImapSearchDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapSelectFolder0 Property

ResourcesLog_ImapSelectFolder0 Property
Gets "Select folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapSelectFolder0 { get; }
Public Overridable ReadOnly Property Log_ImapSelectFolder0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapSetMessageFlags Property

ResourcesLog_ImapSetMessageFlags Property
Gets "Setting flags for messages." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapSetMessageFlags { get; }
Public Overridable ReadOnly Property Log_ImapSetMessageFlags As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapSortDone Property

ResourcesLog_ImapSortDone Property
Gets "Sorted search done." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapSortDone { get; }
Public Overridable ReadOnly Property Log_ImapSortDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapUploadMessageDone Property

ResourcesLog_ImapUploadMessageDone Property
Gets "Message uploaded." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapUploadMessageDone { get; }
Public Overridable ReadOnly Property Log_ImapUploadMessageDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillCopyMessagesTo0 Property

ResourcesLog_ImapWillCopyMessagesTo0 Property
Gets "Will copy messages to folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillCopyMessagesTo0 { get; }
Public Overridable ReadOnly Property Log_ImapWillCopyMessagesTo0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillDownloadEnvelopes Property

ResourcesLog_ImapWillDownloadEnvelopes Property
Gets "Will download envelopes." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillDownloadEnvelopes { get; }
Public Overridable ReadOnly Property Log_ImapWillDownloadEnvelopes As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillDownloadFoldersOf0Matching1 Property

ResourcesLog_ImapWillDownloadFoldersOf0Matching1 Property
Gets "Will download list of sub-folders of \"{0}\" folder matching \"{1}\" condition." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillDownloadFoldersOf0Matching1 { get; }
Public Overridable ReadOnly Property Log_ImapWillDownloadFoldersOf0Matching1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillFinishIdling Property

ResourcesLog_ImapWillFinishIdling Property
Gets "Will finish idling." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillFinishIdling { get; }
Public Overridable ReadOnly Property Log_ImapWillFinishIdling As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillIdle Property

ResourcesLog_ImapWillIdle Property
Gets "Will go idle." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillIdle { get; }
Public Overridable ReadOnly Property Log_ImapWillIdle As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillMoveMessagesTo0 Property

ResourcesLog_ImapWillMoveMessagesTo0 Property
Gets "Will move messages to folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillMoveMessagesTo0 { get; }
Public Overridable ReadOnly Property Log_ImapWillMoveMessagesTo0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillSearch Property

ResourcesLog_ImapWillSearch Property
Gets "Will perform search in the folder." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillSearch { get; }
Public Overridable ReadOnly Property Log_ImapWillSearch As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillSort Property

ResourcesLog_ImapWillSort Property
Gets "Will perform sorted search in the folder." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillSort { get; }
Public Overridable ReadOnly Property Log_ImapWillSort As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillTryRegularAuth Property

ResourcesLog_ImapWillTryRegularAuth Property
Gets "Will try regular LOGIN authentication." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillTryRegularAuth { get; }
Public Overridable ReadOnly Property Log_ImapWillTryRegularAuth As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ImapWillUploadMessageTo0 Property

ResourcesLog_ImapWillUploadMessageTo0 Property
Gets "Will upload message to folder \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ImapWillUploadMessageTo0 { get; }
Public Overridable ReadOnly Property Log_ImapWillUploadMessageTo0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_LoggedInAs0 Property

ResourcesLog_LoggedInAs0 Property
Gets "Logged in as \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_LoggedInAs0 { get; }
Public Overridable ReadOnly Property Log_LoggedInAs0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingFailedJobReEnqueued Property

ResourcesLog_MailingFailedJobReEnqueued Property
Gets "Failed job put back into pending list." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingFailedJobReEnqueued { get; }
Public Overridable ReadOnly Property Log_MailingFailedJobReEnqueued As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingFailedJobsEnqueued Property

ResourcesLog_MailingFailedJobsEnqueued Property
Gets "All failed jobs moved back into pending list." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingFailedJobsEnqueued { get; }
Public Overridable ReadOnly Property Log_MailingFailedJobsEnqueued As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingJob0 Property

ResourcesLog_MailingJob0 Property
Gets "Job {0}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingJob0 { get; }
Public Overridable ReadOnly Property Log_MailingJob0 As String
    Get

Property Value

Type: String
Remarks
Parameter #0 can take values of LogParam_MailingSucceeded or LogParam_MailingFailedOrCancelled.
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingNoPendingJobsLeft Property

ResourcesLog_MailingNoPendingJobsLeft Property
Gets "All pending jobs have been put into processing." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingNoPendingJobsLeft { get; }
Public Overridable ReadOnly Property Log_MailingNoPendingJobsLeft As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingPendingJobEnqueued Property

ResourcesLog_MailingPendingJobEnqueued Property
Gets "New pending job to send e-mail(s)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingPendingJobEnqueued { get; }
Public Overridable ReadOnly Property Log_MailingPendingJobEnqueued As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingPendingJobWentToProcessing Property

ResourcesLog_MailingPendingJobWentToProcessing Property
Gets "Processing of a pending job started." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingPendingJobWentToProcessing { get; }
Public Overridable ReadOnly Property Log_MailingPendingJobWentToProcessing As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingProcessingJobsFinished Property

ResourcesLog_MailingProcessingJobsFinished Property
Gets "All jobs have been processed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingProcessingJobsFinished { get; }
Public Overridable ReadOnly Property Log_MailingProcessingJobsFinished As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingProcessingJobsStarted Property

ResourcesLog_MailingProcessingJobsStarted Property
Gets "Processing of pending jobs started." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingProcessingJobsStarted { get; }
Public Overridable ReadOnly Property Log_MailingProcessingJobsStarted As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MailingWorkerThreadDone Property

ResourcesLog_MailingWorkerThreadDone Property
Gets "Worker thread with hash {0} and ID {1} has finished all the tasks." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MailingWorkerThreadDone { get; }
Public Overridable ReadOnly Property Log_MailingWorkerThreadDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MessageTypeInfo Property

ResourcesLog_MessageTypeInfo Property
Gets "INFO" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MessageTypeInfo { get; }
Public Overridable ReadOnly Property Log_MessageTypeInfo As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MessageTypeRecv Property

ResourcesLog_MessageTypeRecv Property
Gets "RECV" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MessageTypeRecv { get; }
Public Overridable ReadOnly Property Log_MessageTypeRecv As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MessageTypeSend Property

ResourcesLog_MessageTypeSend Property
Gets "SEND" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MessageTypeSend { get; }
Public Overridable ReadOnly Property Log_MessageTypeSend As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_MessageTypeUser Property

ResourcesLog_MessageTypeUser Property
Gets "USER" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_MessageTypeUser { get; }
Public Overridable ReadOnly Property Log_MessageTypeUser As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3ApopAuthNotSupported Property

ResourcesLog_Pop3ApopAuthNotSupported Property
Gets "APOP authentication is not supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3ApopAuthNotSupported { get; }
Public Overridable ReadOnly Property Log_Pop3ApopAuthNotSupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3DeletedMessageIndex0 Property

ResourcesLog_Pop3DeletedMessageIndex0 Property
Gets "Message (index={0}) marked as deleted." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3DeletedMessageIndex0 { get; }
Public Overridable ReadOnly Property Log_Pop3DeletedMessageIndex0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3DeletedMessagesStartIndex0Count1 Property

ResourcesLog_Pop3DeletedMessagesStartIndex0Count1 Property
Gets "Messages (startIndex={0}, count={1}) marked as deleted." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3DeletedMessagesStartIndex0Count1 { get; }
Public Overridable ReadOnly Property Log_Pop3DeletedMessagesStartIndex0Count1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3Downloaded0Index1 Property

ResourcesLog_Pop3Downloaded0Index1 Property
Gets "Downloaded {0} (index={1})." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3Downloaded0Index1 { get; }
Public Overridable ReadOnly Property Log_Pop3Downloaded0Index1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3Downloaded0StartIndex1Count2 Property

ResourcesLog_Pop3Downloaded0StartIndex1Count2 Property
Gets "Downloaded {0} (startIndex={1}, count={2})." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3Downloaded0StartIndex1Count2 { get; }
Public Overridable ReadOnly Property Log_Pop3Downloaded0StartIndex1Count2 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3DownloadList Property

ResourcesLog_Pop3DownloadList Property
Gets "Download the list of lengths of all messages in inbox." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3DownloadList { get; }
Public Overridable ReadOnly Property Log_Pop3DownloadList As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3DownloadStat Property

ResourcesLog_Pop3DownloadStat Property
Gets "Download inbox statistics." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3DownloadStat { get; }
Public Overridable ReadOnly Property Log_Pop3DownloadStat As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3DownloadUidl Property

ResourcesLog_Pop3DownloadUidl Property
Gets "Download the list of Unique-IDs of all messages in inbox." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3DownloadUidl { get; }
Public Overridable ReadOnly Property Log_Pop3DownloadUidl As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3EntireMessage Property

ResourcesLog_Pop3EntireMessage Property
Gets "entire message" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3EntireMessage { get; }
Public Overridable ReadOnly Property Log_Pop3EntireMessage As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3EntireMessages Property

ResourcesLog_Pop3EntireMessages Property
Gets "entire messages" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3EntireMessages { get; }
Public Overridable ReadOnly Property Log_Pop3EntireMessages As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3GetAdvertizedSaslMethodsViaAuth Property

ResourcesLog_Pop3GetAdvertizedSaslMethodsViaAuth Property
Gets "Get the list of advertized SASL authentication methods via AUTH command." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3GetAdvertizedSaslMethodsViaAuth { get; }
Public Overridable ReadOnly Property Log_Pop3GetAdvertizedSaslMethodsViaAuth As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3GetCapabilitiesViaCapa Property

ResourcesLog_Pop3GetCapabilitiesViaCapa Property
Gets "Get the list of POP3 capabilities via CAPA command." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3GetCapabilitiesViaCapa { get; }
Public Overridable ReadOnly Property Log_Pop3GetCapabilitiesViaCapa As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3MessageHeader Property

ResourcesLog_Pop3MessageHeader Property
Gets "message header" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3MessageHeader { get; }
Public Overridable ReadOnly Property Log_Pop3MessageHeader As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3MessageHeaderAnd0BodyLines Property

ResourcesLog_Pop3MessageHeaderAnd0BodyLines Property
Gets "partial (header + {0} body lines) message" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3MessageHeaderAnd0BodyLines { get; }
Public Overridable ReadOnly Property Log_Pop3MessageHeaderAnd0BodyLines As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3MessageHeaders Property

ResourcesLog_Pop3MessageHeaders Property
Gets "message headers" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3MessageHeaders { get; }
Public Overridable ReadOnly Property Log_Pop3MessageHeaders As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3MessageHeadersAnd0BodyLines Property

ResourcesLog_Pop3MessageHeadersAnd0BodyLines Property
Gets "partial (header + {0} body lines) messages" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3MessageHeadersAnd0BodyLines { get; }
Public Overridable ReadOnly Property Log_Pop3MessageHeadersAnd0BodyLines As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3NothingToDelete Property

ResourcesLog_Pop3NothingToDelete Property
Gets "No messages could be deleted from empty inbox." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3NothingToDelete { get; }
Public Overridable ReadOnly Property Log_Pop3NothingToDelete As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3ResetDeletes Property

ResourcesLog_Pop3ResetDeletes Property
Gets "Cancel deletion of all messages marked as deleted." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3ResetDeletes { get; }
Public Overridable ReadOnly Property Log_Pop3ResetDeletes As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3WillDeleteMessageIndex0 Property

ResourcesLog_Pop3WillDeleteMessageIndex0 Property
Gets "Will mark message (index={0}) as deleted." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3WillDeleteMessageIndex0 { get; }
Public Overridable ReadOnly Property Log_Pop3WillDeleteMessageIndex0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3WillDeleteMessagesStartIndex0Count1 Property

ResourcesLog_Pop3WillDeleteMessagesStartIndex0Count1 Property
Gets "Will mark messages (startIndex={0}, count={1}) as deleted." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3WillDeleteMessagesStartIndex0Count1 { get; }
Public Overridable ReadOnly Property Log_Pop3WillDeleteMessagesStartIndex0Count1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3WillDownload0Index1 Property

ResourcesLog_Pop3WillDownload0Index1 Property
Gets "Will download {0} (index={1})." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3WillDownload0Index1 { get; }
Public Overridable ReadOnly Property Log_Pop3WillDownload0Index1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3WillDownload0StartIndex1Count2 Property

ResourcesLog_Pop3WillDownload0StartIndex1Count2 Property
Gets "Will download {0} (startIndex={1}, count={2})." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3WillDownload0StartIndex1Count2 { get; }
Public Overridable ReadOnly Property Log_Pop3WillDownload0StartIndex1Count2 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3WillTryApopAuth Property

ResourcesLog_Pop3WillTryApopAuth Property
Gets "Will try APOP authentication." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3WillTryApopAuth { get; }
Public Overridable ReadOnly Property Log_Pop3WillTryApopAuth As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3WillTryRegularAuth Property

ResourcesLog_Pop3WillTryRegularAuth Property
Gets "Will try regular USER/PASS authentication." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3WillTryRegularAuth { get; }
Public Overridable ReadOnly Property Log_Pop3WillTryRegularAuth As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Pop3ZeroMessagesDownloadedFromEmptyInbox Property

ResourcesLog_Pop3ZeroMessagesDownloadedFromEmptyInbox Property
Gets "Inbox was empty. Zero messages downloaded." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Pop3ZeroMessagesDownloadedFromEmptyInbox { get; }
Public Overridable ReadOnly Property Log_Pop3ZeroMessagesDownloadedFromEmptyInbox As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Sasl0AuthUnsupported Property

ResourcesLog_Sasl0AuthUnsupported Property
Gets "SASL {0} authentication method is not supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Sasl0AuthUnsupported { get; }
Public Overridable ReadOnly Property Log_Sasl0AuthUnsupported As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailDone Property

ResourcesLog_SendMailDone Property
Gets "Mail message sent." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailDone { get; }
Public Overridable ReadOnly Property Log_SendMailDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailFailedRecipientsAllowed Property

ResourcesLog_SendMailFailedRecipientsAllowed Property
Gets "Failed recipients allowed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailFailedRecipientsAllowed { get; }
Public Overridable ReadOnly Property Log_SendMailFailedRecipientsAllowed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailFailedRecipientsNotAllowed Property

ResourcesLog_SendMailFailedRecipientsNotAllowed Property
Gets "Failed recipients not allowed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailFailedRecipientsNotAllowed { get; }
Public Overridable ReadOnly Property Log_SendMailFailedRecipientsNotAllowed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailGotARblListsFor0RblsOf1Total Property

ResourcesLog_SendMailGotARblListsFor0RblsOf1Total Property

[Missing <summary> documentation for "P:MailBee.Resources.Log_SendMailGotARblListsFor0RblsOf1Total"]

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailGotARblListsFor0RblsOf1Total { get; }
Public Overridable ReadOnly Property Log_SendMailGotARblListsFor0RblsOf1Total As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailGotDnsInfoRegardingHost0FromCache Property

ResourcesLog_SendMailGotDnsInfoRegardingHost0FromCache Property
Gets "Got DNS info regarding \"{0}\" from cache." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailGotDnsInfoRegardingHost0FromCache { get; }
Public Overridable ReadOnly Property Log_SendMailGotDnsInfoRegardingHost0FromCache As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailGotMXListsFor0DomainsOf1Total Property

ResourcesLog_SendMailGotMXListsFor0DomainsOf1Total Property
Gets "Retrieved MX records for {0} recipient domain(s) of {1} total." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailGotMXListsFor0DomainsOf1Total { get; }
Public Overridable ReadOnly Property Log_SendMailGotMXListsFor0DomainsOf1Total As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailMadeDnsQueryToDnsAt0RegardingHost1 Property

ResourcesLog_SendMailMadeDnsQueryToDnsAt0RegardingHost1 Property
Gets "Made DNS query to DNS server at {0} regarding host \"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailMadeDnsQueryToDnsAt0RegardingHost1 { get; }
Public Overridable ReadOnly Property Log_SendMailMadeDnsQueryToDnsAt0RegardingHost1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailMessageSubmittedToPickupFolderAs0 Property

ResourcesLog_SendMailMessageSubmittedToPickupFolderAs0 Property
Gets "Mail message submitted to pickup folder as \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailMessageSubmittedToPickupFolderAs0 { get; }
Public Overridable ReadOnly Property Log_SendMailMessageSubmittedToPickupFolderAs0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailProcessedDnsQueryToDnsAt0RegardingHost1 Property

ResourcesLog_SendMailProcessedDnsQueryToDnsAt0RegardingHost1 Property
Gets "Processed results of DNS query to DNS server at {0} regarding host \"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailProcessedDnsQueryToDnsAt0RegardingHost1 { get; }
Public Overridable ReadOnly Property Log_SendMailProcessedDnsQueryToDnsAt0RegardingHost1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailSentToMXesOfDomain0 Property

ResourcesLog_SendMailSentToMXesOfDomain0 Property
Gets "Mail message sent to SMTP MX server(s) of domain \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailSentToMXesOfDomain0 { get; }
Public Overridable ReadOnly Property Log_SendMailSentToMXesOfDomain0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailSentToRecipientDomains Property

ResourcesLog_SendMailSentToRecipientDomains Property
Gets "Mail message sent to SMTP MX server(s) for every domain." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailSentToRecipientDomains { get; }
Public Overridable ReadOnly Property Log_SendMailSentToRecipientDomains As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailSentViaMXLookup Property

ResourcesLog_SendMailSentViaMXLookup Property
Gets "Mail message sent using MX Lookup." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailSentViaMXLookup { get; }
Public Overridable ReadOnly Property Log_SendMailSentViaMXLookup As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailTestDone Property

ResourcesLog_SendMailTestDone Property
Gets "Test send of mail message done." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailTestDone { get; }
Public Overridable ReadOnly Property Log_SendMailTestDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailTestViaMXLookupDone Property

ResourcesLog_SendMailTestViaMXLookupDone Property
Gets "Test send of mail message using MX Lookup completed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailTestViaMXLookupDone { get; }
Public Overridable ReadOnly Property Log_SendMailTestViaMXLookupDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillGetARblRecordsForIP0 Property

ResourcesLog_SendMailWillGetARblRecordsForIP0 Property

[Missing <summary> documentation for "P:MailBee.Resources.Log_SendMailWillGetARblRecordsForIP0"]

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillGetARblRecordsForIP0 { get; }
Public Overridable ReadOnly Property Log_SendMailWillGetARblRecordsForIP0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillGetMXLists Property

ResourcesLog_SendMailWillGetMXLists Property
Gets "Will retrieve MX records for every recipient domain." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillGetMXLists { get; }
Public Overridable ReadOnly Property Log_SendMailWillGetMXLists As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillMakeDnsQueryToDnsAt0RegardingHost1 Property

ResourcesLog_SendMailWillMakeDnsQueryToDnsAt0RegardingHost1 Property
Gets "Will make DNS query to DNS server at {0} regarding host \"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillMakeDnsQueryToDnsAt0RegardingHost1 { get; }
Public Overridable ReadOnly Property Log_SendMailWillMakeDnsQueryToDnsAt0RegardingHost1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillSend Property

ResourcesLog_SendMailWillSend Property
Gets "Will send mail message." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillSend { get; }
Public Overridable ReadOnly Property Log_SendMailWillSend As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillSendToMXesOfDomain0 Property

ResourcesLog_SendMailWillSendToMXesOfDomain0 Property
Gets "Will send mail message to SMTP MX server(s) of domain \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillSendToMXesOfDomain0 { get; }
Public Overridable ReadOnly Property Log_SendMailWillSendToMXesOfDomain0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillSendToRecipientDomains Property

ResourcesLog_SendMailWillSendToRecipientDomains Property
Gets "Will send mail message to SMTP MX server(s) for every domain." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillSendToRecipientDomains { get; }
Public Overridable ReadOnly Property Log_SendMailWillSendToRecipientDomains As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillSendViaMXLookup Property

ResourcesLog_SendMailWillSendViaMXLookup Property
Gets "Will send mail message using MX lookup." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillSendViaMXLookup { get; }
Public Overridable ReadOnly Property Log_SendMailWillSendViaMXLookup As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillSubmitMessageToPickupFolder Property

ResourcesLog_SendMailWillSubmitMessageToPickupFolder Property
Gets "Will submit mail message to pickup folder." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillSubmitMessageToPickupFolder { get; }
Public Overridable ReadOnly Property Log_SendMailWillSubmitMessageToPickupFolder As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillTestSend Property

ResourcesLog_SendMailWillTestSend Property
Gets "Will test sending mail message." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillTestSend { get; }
Public Overridable ReadOnly Property Log_SendMailWillTestSend As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SendMailWillTestSendViaMXLookup Property

ResourcesLog_SendMailWillTestSendViaMXLookup Property
Gets "Will test sending mail message using MX lookup." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SendMailWillTestSendViaMXLookup { get; }
Public Overridable ReadOnly Property Log_SendMailWillTestSendViaMXLookup As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ServerCertAutoValidationSucceeded Property

ResourcesLog_ServerCertAutoValidationSucceeded Property
Gets "Server certificate validation passed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ServerCertAutoValidationSucceeded { get; }
Public Overridable ReadOnly Property Log_ServerCertAutoValidationSucceeded As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_ServerCertRetrieved Property

ResourcesLog_ServerCertRetrieved Property
Gets "Server certificate successfully created from the handle. Can verify it now." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_ServerCertRetrieved { get; }
Public Overridable ReadOnly Property Log_ServerCertRetrieved As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpAuthPopBeforeSmtpFailed Property

ResourcesLog_SmtpAuthPopBeforeSmtpFailed Property
Gets "Warning: POP-before-SMTP authentication failed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpAuthPopBeforeSmtpFailed { get; }
Public Overridable ReadOnly Property Log_SmtpAuthPopBeforeSmtpFailed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpAuthPopBeforeSmtpSucceeded Property

ResourcesLog_SmtpAuthPopBeforeSmtpSucceeded Property
Gets "POP-before-SMTP authentication succeeded." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpAuthPopBeforeSmtpSucceeded { get; }
Public Overridable ReadOnly Property Log_SmtpAuthPopBeforeSmtpSucceeded As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpLoginFailed Property

ResourcesLog_SmtpLoginFailed Property
Gets "Warning: Authentication failed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpLoginFailed { get; }
Public Overridable ReadOnly Property Log_SmtpLoginFailed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpSendDone Property

ResourcesLog_SmtpSendDone Property
Gets "Message successfully submitted to SMTP server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpSendDone { get; }
Public Overridable ReadOnly Property Log_SmtpSendDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpSenderAndRecipientsAccepted Property

ResourcesLog_SmtpSenderAndRecipientsAccepted Property
Gets "Sender and recipients accepted by SMTP server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpSenderAndRecipientsAccepted { get; }
Public Overridable ReadOnly Property Log_SmtpSenderAndRecipientsAccepted As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpSessionReset Property

ResourcesLog_SmtpSessionReset Property
Gets "SMTP session was reset." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpSessionReset { get; }
Public Overridable ReadOnly Property Log_SmtpSessionReset As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpSubmittingMessageData Property

ResourcesLog_SmtpSubmittingMessageData Property
Gets "Will send message data now." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpSubmittingMessageData { get; }
Public Overridable ReadOnly Property Log_SmtpSubmittingMessageData As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpSubmittingSenderAndRecipients Property

ResourcesLog_SmtpSubmittingSenderAndRecipients Property
Gets "Will submit sender and recipients." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpSubmittingSenderAndRecipients { get; }
Public Overridable ReadOnly Property Log_SmtpSubmittingSenderAndRecipients As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpTestSendDone Property

ResourcesLog_SmtpTestSendDone Property
Gets "Test send succeeded." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpTestSendDone { get; }
Public Overridable ReadOnly Property Log_SmtpTestSendDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpWillHello Property

ResourcesLog_SmtpWillHello Property
Gets "Will send Hello command (HELO or EHLO)." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpWillHello { get; }
Public Overridable ReadOnly Property Log_SmtpWillHello As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpWillPerformAuthPopBeforeSmtp Property

ResourcesLog_SmtpWillPerformAuthPopBeforeSmtp Property
Gets "Will perform POP-before-SMTP authentication." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpWillPerformAuthPopBeforeSmtp { get; }
Public Overridable ReadOnly Property Log_SmtpWillPerformAuthPopBeforeSmtp As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpWillResetSmtpSession Property

ResourcesLog_SmtpWillResetSmtpSession Property
Gets "Will reset SMTP session." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpWillResetSmtpSession { get; }
Public Overridable ReadOnly Property Log_SmtpWillResetSmtpSession As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SmtpWillSendMailMessageToServer0 Property

ResourcesLog_SmtpWillSendMailMessageToServer0 Property
Gets "Will send mail message to SMTP server \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SmtpWillSendMailMessageToServer0 { get; }
Public Overridable ReadOnly Property Log_SmtpWillSendMailMessageToServer0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SocketConnectedToIPAddress0OnPort1 Property

ResourcesLog_SocketConnectedToIPAddress0OnPort1 Property
Gets "Socket connected to IP address {0} on port {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SocketConnectedToIPAddress0OnPort1 { get; }
Public Overridable ReadOnly Property Log_SocketConnectedToIPAddress0OnPort1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SslCredentialsCreated Property

ResourcesLog_SslCredentialsCreated Property
Gets "TLS/SSL credentials created." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SslCredentialsCreated { get; }
Public Overridable ReadOnly Property Log_SslCredentialsCreated As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_SslHandshakeDone Property

ResourcesLog_SslHandshakeDone Property
Gets "TLS/SSL negotiation completed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_SslHandshakeDone { get; }
Public Overridable ReadOnly Property Log_SslHandshakeDone As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_StartTls Property

ResourcesLog_StartTls Property
Gets "Request server to begin TLS/SSL negotiation." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_StartTls { get; }
Public Overridable ReadOnly Property Log_StartTls As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_Warning0 Property

ResourcesLog_Warning0 Property
Gets "Warning: {0}" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_Warning0 { get; }
Public Overridable ReadOnly Property Log_Warning0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillConnectToHost0OnPort1 Property

ResourcesLog_WillConnectToHost0OnPort1 Property
Gets "Will connect to host \"{0}\" on port {1}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillConnectToHost0OnPort1 { get; }
Public Overridable ReadOnly Property Log_WillConnectToHost0OnPort1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillConnectVia0ProxyAtHost1OnPort2 Property

ResourcesLog_WillConnectVia0ProxyAtHost1OnPort2 Property
Gets "Will actually connect via {0} proxy server at host \"{1}\" on port {2}." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillConnectVia0ProxyAtHost1OnPort2 { get; }
Public Overridable ReadOnly Property Log_WillConnectVia0ProxyAtHost1OnPort2 As String
    Get

Property Value

Type: String
Remarks
Parameter {0} is a placeholder for the proxy type: SOCKS4, SOCKS5, or HTTP.
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillCreateSslCredentials Property

ResourcesLog_WillCreateSslCredentials Property
Gets "Will create TLS/SSL credentials." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillCreateSslCredentials { get; }
Public Overridable ReadOnly Property Log_WillCreateSslCredentials As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillDisconnectFromHost0 Property

ResourcesLog_WillDisconnectFromHost0 Property
Gets "Will disconnect from host \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillDisconnectFromHost0 { get; }
Public Overridable ReadOnly Property Log_WillDisconnectFromHost0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillLoginAs0 Property

ResourcesLog_WillLoginAs0 Property
Gets "Will login as \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillLoginAs0 { get; }
Public Overridable ReadOnly Property Log_WillLoginAs0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillPerformSslHandshake Property

ResourcesLog_WillPerformSslHandshake Property
Gets "Will start TLS/SSL negotiation sequence." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillPerformSslHandshake { get; }
Public Overridable ReadOnly Property Log_WillPerformSslHandshake As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillResolveHost0 Property

ResourcesLog_WillResolveHost0 Property
Gets "Will resolve host \"{0}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillResolveHost0 { get; }
Public Overridable ReadOnly Property Log_WillResolveHost0 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillTrySasl0Auth Property

ResourcesLog_WillTrySasl0Auth Property
Gets "Will try SASL {0} authentication method." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillTrySasl0Auth { get; }
Public Overridable ReadOnly Property Log_WillTrySasl0Auth As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Log_WillValidateServerCert Property

ResourcesLog_WillValidateServerCert Property
Gets "Will check if server certificate complies with the specified auto-validation flags." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Log_WillValidateServerCert { get; }
Public Overridable ReadOnly Property Log_WillValidateServerCert As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.LogParam_MailingFailedOrCancelled Property

ResourcesLogParam_MailingFailedOrCancelled Property
Gets "failed or cancelled" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LogParam_MailingFailedOrCancelled { get; }
Public Overridable ReadOnly Property LogParam_MailingFailedOrCancelled As String
    Get

Property Value

Type: String
Remarks
Can be used as a parameter #0 in Log_MailingJob0 pattern.
See Also

Reference

Resources Class
MailBee Namespace


Resources.LogParam_MailingSucceeded Property

ResourcesLogParam_MailingSucceeded Property
Gets "succeeded" string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LogParam_MailingSucceeded { get; }
Public Overridable ReadOnly Property LogParam_MailingSucceeded As String
    Get

Property Value

Type: String
Remarks
Can be used as a parameter #0 in Log_MailingJob0 pattern.
See Also

Reference

Resources Class
MailBee Namespace


Resources.LogSuffix_Tag0Rows1 Property

ResourcesLogSuffix_Tag0Rows1 Property
Gets " Tag=\"{0}\", Rows=\"{1}\"." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string LogSuffix_Tag0Rows1 { get; }
Public Overridable ReadOnly Property LogSuffix_Tag0Rows1 As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Pop3AuthCommandUnknown Property

ResourcesPop3AuthCommandUnknown Property
Gets "AUTH command is not supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Pop3AuthCommandUnknown { get; }
Public Overridable ReadOnly Property Pop3AuthCommandUnknown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.Pop3CapaCommandUnknown Property

ResourcesPop3CapaCommandUnknown Property
Gets "CAPA command is not supported by the server." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string Pop3CapaCommandUnknown { get; }
Public Overridable ReadOnly Property Pop3CapaCommandUnknown As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


Resources.SmtpHelloed Property

ResourcesSmtpHelloed Property
Gets "SMTP Hello completed." string.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual string SmtpHelloed { get; }
Public Overridable ReadOnly Property SmtpHelloed As String
    Get

Property Value

Type: String
See Also

Reference

Resources Class
MailBee Namespace


SaslMethod Class

SaslMethod Class
Provides a framework for developing custom SASL authentication mechanisms.
Inheritance Hierarchy
SystemObject
MailBeeSaslMethod

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class SaslMethod
Public MustInherit Class SaslMethod

The SaslMethod type exposes the following members.

Constructors
 | Name | Description
Public method | SaslMethod | Initializes a new instance of the SaslMethod class
Top
Methods
 | Name | Description
Public method | AccountDataIsPassword | Designates if only the password must be set (password-only method).
 | CreateNextClientAnswer | When overridden in a derived class, generates client's next answer in the authentication protocol exchange series.
Public method | Dispose | Disposes managed and unmananged resources used by the SASL mechanism.
Protected method | Dispose(Boolean) | Actually disposes managed and unmananged resources used by the SASL mechanism.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetSaslID | When overridden in a derived class, returns uppercase name of a SASL method implemented by that class (such as "LOGIN", "NTLM", etc).
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IsFipsCompliant | Denotes if this authentication method is FIPS-compliant.
Public method | IsSecure | When overridden in a derived class, designates whether the implemented SASL mechanism is secure or not.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | RequiresCredentials | Designates whether or not the implemented SASL mechanism can operate without user credentials passed in AccountName and Password property values.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AccountDomain | Reserved for future use.
Public property | AccountName | Gets or sets a user account name on the mail server.
Public property | ClientAnswer | Gets or sets an array of bytes which represents a client answer to a server challenge.
Public property | ClientAnswerEncoding | Gets or sets an encoding of the client answer data.
Public property | ExpectBase64Challenge | Gets or sets the status of whether Base64-encoded data is expected in the pending response from the server.
Public property | Password | Gets or sets a user account password on the mail server.
Public property | ServerChallenge | Gets or sets an array of bytes which represents a server challenge.
Public property | ServerChallengeEncoding | Gets or sets an encoding of the server challenge data.
Public property | ServerName | Gets the domain name of the mail server.
Public property | ServiceName | Gets the upper-case name of the protocol being used.
Public property | Stage | Gets or sets the current stage of the authentication protocol exchange.
Public property | TargetName | Gets the SPN (target name).
Top
Remarks

Instances of derived classes can be used with mailer classes such as Pop3, Imap or Smtp for employing non-standard login mechanisms.

Implementation of SASL authentication mechanism requires the developer to override the following methods:

  • CreateNextClientAnswer
  • GetSaslID
  • IsSecure

Also, the developer can override RequiresCredentials method which returns true by default. This can be used for implementing an authentication method which can obtain user credentials itself and does not require AccountName and Password properties be set. For instance, MailBee implementation of NTLM method can obtain user credentials from the operating system when they are not supplied in AccountName and Password properties.
Examples
This sample shows the entire implementation of SASL LOGIN authentication method. Although SASL LOGIN method is already built into MailBee, you can use this sample for developing your own SASL authentication methods.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// User-defined SASL LOGIN method implementation
public class SaslLoginMethod : SaslMethod
{
    public override string GetSaslID()
    {
        return "LOGIN";
    }

    public override void CreateNextClientAnswer()
    {
        switch (Stage)
        {
            case 0:
                ClientAnswer = ClientAnswerEncoding.GetBytes(AccountName);
                Stage++;
                break;
            case 1:
                ClientAnswer = ClientAnswerEncoding.GetBytes(Password);
                Stage++;
                break;
        }
    }

    public override bool IsSecure() { return false; }
}

// User-defined SASL LOGIN method usage (put this code into an existing class of your application)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret", AuthenticationMethods.SaslUserDefined, AuthenticationOptions.None, new SaslLoginMethod());
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail

' User-defined SASL LOGIN method implementation
Public Class SaslLoginMethod
    Inherits SaslMethod
    Public Overloads Overrides Function GetSaslID() As String
        Return "LOGIN"
    End Function

    Public Overloads Overrides Sub CreateNextClientAnswer()
        Select Case Stage
            Case 0
                ClientAnswer = ClientAnswerEncoding.GetBytes(AccountName)
                Stage += 1
            Case 1
                ClientAnswer = ClientAnswerEncoding.GetBytes(Password)
                Stage += 1
        End Select
    End Sub

    Public Overloads Overrides Function IsSecure() As Boolean
        Return False
    End Function
End Class

' User-defined SASL LOGIN method usage (put this code into an existing class of your application)
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret", AuthenticationMethods.SaslUserDefined, AuthenticationOptions.None, New SaslLoginMethod)
pop.Disconnect()
See Also

Reference

MailBee Namespace
MailBeeAuthenticationOptions
Pop3Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
ImapLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
SmtpServerAuthMethods


SaslMethod Constructor

SaslMethod Constructor
Initializes a new instance of the SaslMethod class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SaslMethod()
Public Sub New
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod Methods

SaslMethod Methods

The SaslMethod type exposes the following members.

Methods
 | Name | Description
Public method | AccountDataIsPassword | Designates if only the password must be set (password-only method).
 | CreateNextClientAnswer | When overridden in a derived class, generates client's next answer in the authentication protocol exchange series.
Public method | Dispose | Disposes managed and unmananged resources used by the SASL mechanism.
Protected method | Dispose(Boolean) | Actually disposes managed and unmananged resources used by the SASL mechanism.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetSaslID | When overridden in a derived class, returns uppercase name of a SASL method implemented by that class (such as "LOGIN", "NTLM", etc).
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IsFipsCompliant | Denotes if this authentication method is FIPS-compliant.
Public method | IsSecure | When overridden in a derived class, designates whether the implemented SASL mechanism is secure or not.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | RequiresCredentials | Designates whether or not the implemented SASL mechanism can operate without user credentials passed in AccountName and Password property values.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.AccountDataIsPassword Method

SaslMethodAccountDataIsPassword Method
Designates if only the password must be set (password-only method).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual bool AccountDataIsPassword()
Public Overridable Function AccountDataIsPassword As Boolean

Return Value

Type: Boolean
Must return false in case if this authentication method requires login and password, or true is the account name is included in the password (for instance, in case of OAuth method). If RequiresCredentials is false, this method has no effect.
Remarks
In most cases, this method should return false. In OAuth case, the account name is not defined, you only need to supply the account signature which includes multiple parameters (some of which may be treated as the password).
See Also

Reference

SaslMethod Class
MailBee Namespace
SaslMethodRequiresCredentials


SaslMethod.CreateNextClientAnswer Method

SaslMethodCreateNextClientAnswer Method
When overridden in a derived class, generates client's next answer in the authentication protocol exchange series.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract void CreateNextClientAnswer()
Public MustOverride Sub CreateNextClientAnswer
Remarks

This method must implement SASL authentication mechanism as generating answer to the server challenge. The server challenge must be read from ServerChallenge property. The resulting answer must be put in ClientAnswer property value.

If SASL mechanism being implemented requires more than one client answer in the series, Stage property can be read and modified by this method in order to keep track of the authentication protocol exchange progress.

Examples
This sample shows CreateNextClientAnswer implementation for SASL PLAIN authentication method.
C#
VB
Copy
public override void CreateNextClientAnswer()
{
    switch (Stage)
    {
        case 0:
            ClientAnswer = ClientAnswerEncoding.GetBytes("\0" + AccountName + "\0" + Password);
            Stage++;
            break;
    }
}
Public Overloads Overrides Sub CreateNextClientAnswer()
    Select Case Stage
        Case 0
            ClientAnswer = ClientAnswerEncoding.GetBytes(String.Format("\0{0}\0{1}", AccountName, Password))
            Stage += 1
    End Select
End Sub
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.Dispose Method

SaslMethodDispose Method
Overload List
 | Name | Description
Public method | Dispose | Disposes managed and unmananged resources used by the SASL mechanism.
Protected method | Dispose(Boolean) | Actually disposes managed and unmananged resources used by the SASL mechanism.
Top
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.Dispose Method

SaslMethodDispose Method
Disposes managed and unmananged resources used by the SASL mechanism.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose
Remarks
MailBee calls this method automatically when finished with SASL authentication. If your custom class has any resources to be freed, override Dispose(Boolean) method and free the resources there.
See Also

Reference

SaslMethod Class
Dispose Overload
MailBee Namespace


SaslMethod.Dispose Method (Boolean)

SaslMethodDispose Method (Boolean)
Actually disposes managed and unmananged resources used by the SASL mechanism.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true if managed resources must be freed.
Remarks
Override this method if your class has resources to be freed.
See Also

Reference

SaslMethod Class
Dispose Overload
MailBee Namespace


SaslMethod.GetSaslID Method

SaslMethodGetSaslID Method
When overridden in a derived class, returns uppercase name of a SASL method implemented by that class (such as "LOGIN", "NTLM", etc).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract string GetSaslID()
Public MustOverride Function GetSaslID As String

Return Value

Type: String
Uppercase name of a SASL method.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.IsFipsCompliant Method

SaslMethodIsFipsCompliant Method
Denotes if this authentication method is FIPS-compliant.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual bool IsFipsCompliant()
Public Overridable Function IsFipsCompliant As Boolean

Return Value

Type: Boolean
true if the method is FIPS-compliant; otherwise, false. >By default, returns true.
Remarks
Override this method in case if its implementation uses weak algorithms like MD5 or RC4 which are not FIPS-compliant. Such methods will be discarded during authentication when FipsMode is enabled.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.IsSecure Method

SaslMethodIsSecure Method
When overridden in a derived class, designates whether the implemented SASL mechanism is secure or not.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract bool IsSecure()
Public MustOverride Function IsSecure As Boolean

Return Value

Type: Boolean
true if the implemented SASL mechanism is secure; otherwise, false.
Remarks
Secure methods do not transmit passwords over the network as clear-text or Base64.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.RequiresCredentials Method

SaslMethodRequiresCredentials Method
Designates whether or not the implemented SASL mechanism can operate without user credentials passed in AccountName and Password property values.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual bool RequiresCredentials()
Public Overridable Function RequiresCredentials As Boolean

Return Value

Type: Boolean
By default, returns true.
Remarks
The developer should override this method if the implemented SASL mechanism can obtain credentials in some other way when they are not supplied by the caller. For instance, MailBee NTLM implementation can get the credentials from the operating system.
Note Note
If AccountDataIsPassword is false, this designates Password must be a null reference (Nothing in Visual Basic). For instance, OAuth authentication method requires this.
See Also

Reference

SaslMethod Class
MailBee Namespace
SaslMethodAccountDataIsPassword


SaslMethod Properties

SaslMethod Properties

The SaslMethod type exposes the following members.

Properties
 | Name | Description
Public property | AccountDomain | Reserved for future use.
Public property | AccountName | Gets or sets a user account name on the mail server.
Public property | ClientAnswer | Gets or sets an array of bytes which represents a client answer to a server challenge.
Public property | ClientAnswerEncoding | Gets or sets an encoding of the client answer data.
Public property | ExpectBase64Challenge | Gets or sets the status of whether Base64-encoded data is expected in the pending response from the server.
Public property | Password | Gets or sets a user account password on the mail server.
Public property | ServerChallenge | Gets or sets an array of bytes which represents a server challenge.
Public property | ServerChallengeEncoding | Gets or sets an encoding of the server challenge data.
Public property | ServerName | Gets the domain name of the mail server.
Public property | ServiceName | Gets the upper-case name of the protocol being used.
Public property | Stage | Gets or sets the current stage of the authentication protocol exchange.
Public property | TargetName | Gets the SPN (target name).
Top
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.AccountDomain Property

SaslMethodAccountDomain Property
Reserved for future use.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountDomain { get; set; }
Public Property AccountDomain As String
    Get
    Set

Property Value

Type: String
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.AccountName Property

SaslMethodAccountName Property
Gets or sets a user account name on the mail server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; set; }
Public Property AccountName As String
    Get
    Set

Property Value

Type: String
The name of the user account on the mail server.
Remarks
To the moment when the authentication protocol exchange starts, this property is already set, so you can use it in CreateNextClientAnswer implementation.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ClientAnswer Property

SaslMethodClientAnswer Property
Gets or sets an array of bytes which represents a client answer to a server challenge.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] ClientAnswer { get; set; }
Public Property ClientAnswer As Byte()
    Get
    Set

Property Value

Type: Byte
The client answer data to be sent by the client to the server.
Remarks
MailBee will use the value of this property as a client answer to the server challenge. MailBee gets this property value, converts the data into Base64, and then sends it to the server.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ClientAnswerEncoding Property

SaslMethodClientAnswerEncoding Property
Gets or sets an encoding of the client answer data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ClientAnswerEncoding { get; set; }
Public Property ClientAnswerEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
By default, the value of RequestEncoding property of the mailer component (such as Pop3.RequestEncoding, such as Imap.RequestEncoding or Smtp.RequestEncoding).
Remarks
You can use this encoding to convert string data (such as account names, passwords, etc) into bytes if required by your algorithm.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ExpectBase64Challenge Property

SaslMethodExpectBase64Challenge Property
Gets or sets the status of whether Base64-encoded data is expected in the pending response from the server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ExpectBase64Challenge { get; set; }
Public Property ExpectBase64Challenge As Boolean
    Get
    Set

Property Value

Type: Boolean
The boolean status of whether Base64-encoded data is expected in the pending response from the server. The default value is true.
Remarks
The developer should set this property to false (usually in the derived class constructor) if the server returns non-base64 data in the first challenge, and then set it back to true in overridden CreateNextClientAnswer method. This is required when implementing a method such as NTLM.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.Password Property

SaslMethodPassword Property
Gets or sets a user account password on the mail server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; set; }
Public Property Password As String
    Get
    Set

Property Value

Type: String
The password of the user account on the mail server.
Remarks
To the moment when the authentication protocol exchange starts, this property is already set, so you can use it in CreateNextClientAnswer implementation.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ServerChallenge Property

SaslMethodServerChallenge Property
Gets or sets an array of bytes which represents a server challenge.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] ServerChallenge { get; set; }
Public Property ServerChallenge As Byte()
    Get
    Set

Property Value

Type: Byte
The challenge data sent by the server to the client.
Remarks
MailBee will assign a server challenge value to this property during the authentication protocol exchange. Although the server sends challenge data as Base64 string, MailBee decodes this data from Base64 first, and then assigns the decoded data value to this property.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ServerChallengeEncoding Property

SaslMethodServerChallengeEncoding Property
Gets or sets an encoding of the server challenge data.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ServerChallengeEncoding { get; set; }
Public Property ServerChallengeEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
By default, the value of ResponseEncoding property of the mailer component (such as Pop3.ResponseEncoding, Imap.ResponseEncoding or Smtp.ResponseEncoding).
Remarks
You can use this encoding to convert portions of the server challenge from bytes to strings if required by your algorithm.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ServerName Property

SaslMethodServerName Property
Gets the domain name of the mail server.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ServerName { get; }
Public ReadOnly Property ServerName As String
    Get

Property Value

Type: String
The domain name or IP address string of the mail server to which the connection has been made.
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.ServiceName Property

SaslMethodServiceName Property
Gets the upper-case name of the protocol being used.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ServiceName { get; }
Public ReadOnly Property ServiceName As String
    Get

Property Value

Type: String
The upper-case name of the protocol being used (such as POP3, SMTP, or IMAP).
See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.Stage Property

SaslMethodStage Property
Gets or sets the current stage of the authentication protocol exchange.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Stage { get; set; }
Public Property Stage As Integer
    Get
    Set

Property Value

Type: Int32
The default value is 0.
Remarks

Some SASL authentication mechanisms require several "server challenge - client request" iterations. In order to keep track of the current stage, you can use this property.

Also, you should update this property value when required by your algorithm. Most algorithms assume incrementing the current stage value each time new answer from the client is ready (i.e. on each CreateNextClientAnswer method call).

See Also

Reference

SaslMethod Class
MailBee Namespace


SaslMethod.TargetName Property

SaslMethodTargetName Property
Gets the SPN (target name).

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TargetName { get; }
Public ReadOnly Property TargetName As String
    Get

Property Value

Type: String
The target name (Service Principal Name). Can be a null reference (Nothing in Visual Basic).
Remarks
Usually used with Kerberos. When doing Kerberos auth, the default value is constructed as ServiceName + "/" + ServerName. The developer may, however, set it explicitly using the corresponding Login overload of the mailer component. Other authentication methods do not use this value.
See Also

Reference

SaslMethod Class
MailBee Namespace


SortableByPriorityCollection Class

SortableByPriorityCollection Class
Represents an abstract parent for all MailBee collections sorted by Priority value of their elements.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBeeSortableByPriorityCollection
MailBee.DnsMXDnsServerCollection
MailBee.SmtpMailSmtpServerCollection

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class SortableByPriorityCollection : CollectionBase
Public MustInherit Class SortableByPriorityCollection
    Inherits CollectionBase

The SortableByPriorityCollection type exposes the following members.

Constructors
 | Name | Description
Protected method | SortableByPriorityCollection | Initializes a new instance of the SortableByPriorityCollection class
Top
Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | SortByPriority | Sorts the items in the collection by their priority value.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

Sorting by priority is used to sort DnsServer and SmtpServer objects in their corresponding collections so that servers with higher priority (also called preference) would be used first.

In send mail scenarios, having servers sorted by the priority value allows MailBee to send mails to high-priority servers while low priority servers are used as backup servers in the case if the primary servers fail.

See Also

Reference

MailBee Namespace
MailBee.DnsMXDnsServerCollection
MailBee.SmtpMailSmtpServerCollection


SortableByPriorityCollection Constructor

SortableByPriorityCollection Constructor
Initializes a new instance of the SortableByPriorityCollection class

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected SortableByPriorityCollection()
Protected Sub New
See Also

Reference

SortableByPriorityCollection Class
MailBee Namespace


SortableByPriorityCollection Methods

SortableByPriorityCollection Methods

The SortableByPriorityCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | SortByPriority | Sorts the items in the collection by their priority value.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SortableByPriorityCollection Class
MailBee Namespace


SortableByPriorityCollection.SortByPriority Method

SortableByPriorityCollectionSortByPriority Method
Sorts the items in the collection by their priority value.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SortByPriority()
Public Sub SortByPriority
Remarks

Lower values are preferred. For instance, if the collection had 4 elements with the following priority values: 1, 0, 3, 0, then after calling this method, the elements would be reordered as: 0, 0, 1, 3.

If this method detects the collection is already sorted, no elements will be reordered. In other words, this method performs stable sort (in contrast to unstable sort when equal elements may be reordered).

This method can be used if the developer changes priority of elements already added to the collection and wants to get the collection re-ordered accordingly new values of priority.

See Also

Reference

SortableByPriorityCollection Class
MailBee Namespace


SortableByPriorityCollection Properties

SortableByPriorityCollection Properties

The SortableByPriorityCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

SortableByPriorityCollection Class
MailBee Namespace


TopLevelProtocolType Enumeration

TopLevelProtocolType Enumeration
Defines types of MailBee main protocols.

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum TopLevelProtocolType
Public Enumeration TopLevelProtocolType
Members
Member name | Value | Description
Unknown | 0 | The current context is unknown.
Dns | 1 | The current context is DNS.
Smtp | 2 | The current context is SMTP.
Pop3 | 3 | The current context is POP3.
Imap | 4 | The current context is IMAP.
Ews | 5 | The current context is EWS (Exchange Web Services).
Remarks

This enumeration is mainly used as the type of Protocol property of many network-specific exceptions and events (such as ConnectedEventArgs.Protocol).

The value of such a property indicates the context in which the corresponding exception or event has occurred. This provides the developer with additional information on the exception or event.

For instance, the developer implementing sending mail via Smtp component can read this property in the exception handler in order to determine whether the exception was caused by SMTP connection error or by DNS/MX error (or even by POP3 error during POP-before-SMTP authentication).

See Also

Reference

MailBee Namespace


MailBee.AddressCheck Namespace

MailBee.AddressCheck Namespace

MailBee.AddressCheck namespace enables applications to verify bulks of e-mail addresses for syntax (using regular expressions) and existence (with DNX MX lookup queries, test SMTP connections, and send attempts). Supports multi-threading.

Validating multiple addresses at once is only supported in classic .NET Framework, and .NET Standard 2.0 compatible environments (.NET Core 2.0 and newer, UWP for Windows 10 Fall Creators Update and newer). With .NET Core 1.0/1.1 and older UWP, only single addresses can be validated at a time.

Classes
 | Class | Description
 | EmailAddressValidator | Provides means for bulk verification of e-mail addresses.
Public class | VerifiedEventArgs | Contains the event data for Verified event.
Public class | VerifyingEventArgs | Contains the event data for Verifying event.
Delegates
 | Delegate | Description
Public delegate | VerifiedEventHandler | Represents the method that will handle Verified event.
Public delegate | VerifyingEventHandler | Represents the method that will handle Verifying event.
Enumerations
 | Enumeration | Description
Public enumeration | AddressValidationLevel | Defines levels of e-mail address verification.


VerifiedEventArgs Class

VerifiedEventArgs Class
Contains the event data for Verified event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.AddressCheckVerifiedEventArgs

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class VerifiedEventArgs : CommonEventArgs
Public Class VerifiedEventArgs
    Inherits CommonEventArgs

The VerifiedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DataReader | The data reader from which MailBee takes e-mail addresses to verify.
Public property | DataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | DataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | Email | The e-mail address just checked.
Public property | Reason | A reference to the exception object which contains the reason why the given e-mail address failed the verification.
Public property | Result | The result of verification of the given e-mail address.
Public property | Row | The data row containing the given e-mail address.
Public property | RowIndex | The index of the data row in the source data table.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Table | The data table which was used as a source of e-mail addresses to verify.
Top
Remarks
Many event properties of Verified and Verifying events have the same meaning and described in detail only in VerifyingEventArgs topic.
See Also

Reference

MailBee.AddressCheck Namespace


VerifiedEventArgs Methods

VerifiedEventArgs Methods

The VerifiedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs Properties

VerifiedEventArgs Properties

The VerifiedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | DataReader | The data reader from which MailBee takes e-mail addresses to verify.
Public property | DataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | DataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | Email | The e-mail address just checked.
Public property | Reason | A reference to the exception object which contains the reason why the given e-mail address failed the verification.
Public property | Result | The result of verification of the given e-mail address.
Public property | Row | The data row containing the given e-mail address.
Public property | RowIndex | The index of the data row in the source data table.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Table | The data table which was used as a source of e-mail addresses to verify.
Top
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.DataReader Property

VerifiedEventArgsDataReader Property
The data reader from which MailBee takes e-mail addresses to verify.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader DataReader { get; }
Public ReadOnly Property DataReader As IDataReader
    Get

Property Value

Type: IDataReader
A reference to the data reader if it was passed as an input, or a null reference (Nothing in Visual Basic) if the input was DataTable or a string array.
Remarks
See DataReader for explanations.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.DataReaderColumnNames Property

VerifiedEventArgsDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] DataReaderColumnNames { get; }
Public ReadOnly Property DataReaderColumnNames As String()
    Get

Property Value

Type: String
A reference to the string array where each item is the result of GetName(Int32) call for each column, made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks
See DataReaderColumnNames for explanations.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.DataReaderRowValues Property

VerifiedEventArgsDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] DataReaderRowValues { get; }
Public ReadOnly Property DataReaderRowValues As Object()
    Get

Property Value

Type: Object
A reference to the result of GetValues(Object) call made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks
See DataReaderRowValues for explanations.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.Email Property

VerifiedEventArgsEmail Property
The e-mail address just checked.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Email { get; }
Public ReadOnly Property Email As String
    Get

Property Value

Type: String
The string containing the e-mail address. Cannot be a null reference (Nothing in Visual Basic).
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.Reason Property

VerifiedEventArgsReason Property
A reference to the exception object which contains the reason why the given e-mail address failed the verification.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailBeeException Reason { get; }
Public ReadOnly Property Reason As MailBeeException
    Get

Property Value

Type: MailBeeException
A reference to the exception object representing the reason of the e-mail address failure; or a null reference (Nothing in Visual Basic) if the e-mail address successfully passed the verification.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.Result Property

VerifiedEventArgsResult Property
The result of verification of the given e-mail address.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AddressValidationLevel Result { get; }
Public ReadOnly Property Result As AddressValidationLevel
    Get

Property Value

Type: AddressValidationLevel
OK if the e-mail address successfully passed the requested verification procedures; otherwise, the level at which the verification failed.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.Row Property

VerifiedEventArgsRow Property
The data row containing the given e-mail address.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataRow Row { get; }
Public ReadOnly Property Row As DataRow
    Get

Property Value

Type: DataRow
A reference to the data row which contains the cell with the given e-mail address. Set when Table is set.
Remarks
See Row for explanations.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.RowIndex Property

VerifiedEventArgsRowIndex Property
The index of the data row in the source data table.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int RowIndex { get; }
Public ReadOnly Property RowIndex As Integer
    Get

Property Value

Type: Int32
A non-negative number which denotes the index of the Row in the source data Table.
Remarks
See RowIndex for explanations.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventArgs.Table Property

VerifiedEventArgsTable Property
The data table which was used as a source of e-mail addresses to verify.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable Table { get; }
Public ReadOnly Property Table As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table passed by the caller as input, or the data table built by MailBee if the input was a string array, or a null reference (Nothing in Visual Basic) if the input was IDataReader.
Remarks
See Table for explanations.
See Also

Reference

VerifiedEventArgs Class
MailBee.AddressCheck Namespace


VerifiedEventHandler Delegate

VerifiedEventHandler Delegate
Represents the method that will handle Verified event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void VerifiedEventHandler(
    Object sender,
    VerifiedEventArgs e
)
Public Delegate Sub VerifiedEventHandler (
    sender As Object,
    e As VerifiedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.AddressCheckVerifiedEventArgs
See Also

Reference

MailBee.AddressCheck Namespace


VerifyingEventArgs Class

VerifyingEventArgs Class
Contains the event data for Verifying event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.AddressCheckVerifyingEventArgs

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class VerifyingEventArgs : CommonEventArgs
Public Class VerifyingEventArgs
    Inherits CommonEventArgs

The VerifyingEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DataReader | The data reader from which MailBee takes e-mail addresses to verify.
Public property | DataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | DataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | Email | The e-mail address to be checked.
Public property | Row | The data row containing the given e-mail address.
Public property | RowIndex | The index of the data row in the source data table.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Table | The data table which was used as a source of e-mail addresses to verify.
Public property | VerifyIt | Gets or sets if MailBee should verify the given e-mail address or skip it.
Top
See Also

Reference

MailBee.AddressCheck Namespace


VerifyingEventArgs Methods

VerifyingEventArgs Methods

The VerifyingEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs Properties

VerifyingEventArgs Properties

The VerifyingEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | DataReader | The data reader from which MailBee takes e-mail addresses to verify.
Public property | DataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | DataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | Email | The e-mail address to be checked.
Public property | Row | The data row containing the given e-mail address.
Public property | RowIndex | The index of the data row in the source data table.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Table | The data table which was used as a source of e-mail addresses to verify.
Public property | VerifyIt | Gets or sets if MailBee should verify the given e-mail address or skip it.
Top
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.DataReader Property

VerifyingEventArgsDataReader Property
The data reader from which MailBee takes e-mail addresses to verify.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader DataReader { get; }
Public ReadOnly Property DataReader As IDataReader
    Get

Property Value

Type: IDataReader
A reference to the data reader if it was passed as an input, or a null reference (Nothing in Visual Basic) if the input was DataTable or a string array.
Remarks
Note that you must not advance the position of data reader (such as with Read method). MailBee will do this itself. Also, if the verification process is multi-threaded, you cannot use this property to access the current row. Another thread may already use the reader to read the next data row. Use DataReaderRowValues and DataReaderColumnNames propeties to read the field values corresponding to the current row.
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.DataReaderColumnNames Property

VerifyingEventArgsDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] DataReaderColumnNames { get; }
Public ReadOnly Property DataReaderColumnNames As String()
    Get

Property Value

Type: String
A reference to the string array where each item is the result of GetName(Int32) call for each column, made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks

Can be used in conjunction with DataReaderRowValues property to access elements by their names, such as with e.DataReaderRowValues[Array.IndexOf(e.DataReaderColumnNames, "id")] call (in C# syntax, assuming e is VerifyingEventArgs instance).

If you know the index of the field you need to access, you can use it directly, such as e.DataReaderRowValues[0].

See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.DataReaderRowValues Property

VerifyingEventArgsDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] DataReaderRowValues { get; }
Public ReadOnly Property DataReaderRowValues As Object()
    Get

Property Value

Type: Object
A reference to the result of GetValues(Object) call made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks
This property is useful in case of multi-threaded e-mail verification when the IDataReader could have already advance to next records to the moment when this event occurs. It guarantees that the data in this array will correspond to that e-mail address for which this event was raised.
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.Email Property

VerifyingEventArgsEmail Property
The e-mail address to be checked.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Email { get; }
Public ReadOnly Property Email As String
    Get

Property Value

Type: String
The string containing the e-mail address. Cannot be a null reference (Nothing in Visual Basic).
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.Row Property

VerifyingEventArgsRow Property
The data row containing the given e-mail address.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataRow Row { get; }
Public ReadOnly Property Row As DataRow
    Get

Property Value

Type: DataRow
A reference to the data row which contains the cell with the given e-mail address. Set when Table is set.
Remarks

When you supply DataTable in Verify(DataTable, String) call, MailBee uses that DataTable and makes it available in this event handler with Table property. When you supply a string array as the data source (using Verify(String) call), MailBee builds Table from the input string array. Anyway, during the bulk check, MailBee goes through the DataTable picking up data rows one-by-one and getting e-mail addresses from there.

If the input is a string array, the row will contain a single column named "email".

When the input is IDataReader rather than DataTable, this property is a null reference (Nothing in Visual Basic).

See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.RowIndex Property

VerifyingEventArgsRowIndex Property
The index of the data row in the source data table.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int RowIndex { get; }
Public ReadOnly Property RowIndex As Integer
    Get

Property Value

Type: Int32
A non-negative number which denotes the index of the Row in the source data Table.
Remarks
When the input is IDataReader rather than DataTable, this property returns -1.
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.Table Property

VerifyingEventArgsTable Property
The data table which was used as a source of e-mail addresses to verify.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable Table { get; }
Public ReadOnly Property Table As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table passed by the caller as input, or the data table built by MailBee if the input was a string array, or a null reference (Nothing in Visual Basic) if the input was IDataReader.
Remarks
When Table is set, Row denotes the row with RowIndex in Table.
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventArgs.VerifyIt Property

VerifyingEventArgsVerifyIt Property
Gets or sets if MailBee should verify the given e-mail address or skip it.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool VerifyIt { get; set; }
Public Property VerifyIt As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the given e-mail address will be verified; if false, it will be skipped. The default value is true.
Remarks
This property lets you implement whitelists and blacklists. If you encounter certain address which does not need validation (it self or its domain is known to be good, or bad in case of blacklist), you can tell MailBee to skip it. You can implement any logic here.
See Also

Reference

VerifyingEventArgs Class
MailBee.AddressCheck Namespace


VerifyingEventHandler Delegate

VerifyingEventHandler Delegate
Represents the method that will handle Verifying event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void VerifyingEventHandler(
    Object sender,
    VerifyingEventArgs e
)
Public Delegate Sub VerifyingEventHandler (
    sender As Object,
    e As VerifyingEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.AddressCheckVerifyingEventArgs
See Also

Reference

MailBee.AddressCheck Namespace


AddressValidationLevel Enumeration

AddressValidationLevel Enumeration
Defines levels of e-mail address verification.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum AddressValidationLevel
Public Enumeration AddressValidationLevel
Members
Member name | Value | Description
RegexCheck | 0 | Check e-mail address syntax only, via regular experssion (can be customized with RegexPattern property). Very fast and does not make any network queries.
DnsQuery | 1 | In addition to syntax check, do DNS MX query against the domain name part of the e-mail address to determine which SMTP MX server is responsible for delivering e-mail to the given domain. Slower than just syntax check but more accurate as invalid domains are filtered out.
SmtpConnection | 2 | In addition to the previous option, make an attempt to connect to the SMTP MX server determined at the previous stage. If multiple MX servers have been detected and the server having the highest priority is not responding, will also try other MXes of this domain, in accordance with their priorities. Slower than just a DNS MX check but more accurate as it filters out the domains with dead SMTP MX servers.
SendAttempt | 3 | This method not just connects to SMTP MX server but also submits the sender and recipient (where the recipients is the e-mail address being examined) to that MX server. The slowest and the most accurate method.
OK | 4 | Verify(String) method returns this value when the e-mail address check passed successfully. Has the same meaning for Result property of Verified event.
Remarks

The values of this type can be used as both input parameters (when they define how deeply the e-mail address check should go) and return values (when they show at which stage the verification procedure failed).

For instance, if you set the desired level of verification to, let's say, DnsQuery, it means MailBee will do syntax check and DNS MX query check. If both checks are OK, the return value will be OK. Otherwise, the return value will be the level at which the verification failed. For instance, if it failed at syntax check against a regular expression pattern, the return value will be RegexCheck.

Note Note
Use advanced methods of verification (SmtpConnection and SendAttempt) with care. See below the common pitfalls of e-mail address verification which involves making test SMTP connections.
  • If you're running the check from the machine which does not have a properly configured DNS PTR record (also known as rDNS), many servers will reject connections from you. Most computers sending spam do not have such DNS records and the lack of it makes other servers think you're a spammer.
  • If the IP address of that machine is black-listed in some common RBL databases, you'll get the same results.
  • Many servers may indicate some temporary problems even when you try to submit them a valid address. If you got an SendAttempt error for some e-mail address, try to repeat the check in a few hours and if it fails too, next day. Only 3-4 consequtive SendAttempt failures can prove that the e-mail address is really dead. This only applies to SendAttempt checks. For instance, if the e-mail address has invalid syntax, this is not gonna change if you try again later.
  • Opposite scenario, when SendAttempt passes successfully, it still does not guarantee that the e-mail address is correct as some servers accept any name in their domain as valid address during SMTP session, but later send bounce to the sender. Unfortunately, there is no way to workaround this but to extend your system with some mailbox where bounces will arrive, you'll parse them, extract invalid addresses and remove them from your database. MailBee can provide some help with this, see DeliveryStatusParser class for details.
See Also

Reference

MailBee.AddressCheck Namespace


EmailAddressValidator Class

EmailAddressValidator Class
Provides means for bulk verification of e-mail addresses.
Inheritance Hierarchy
SystemObject
MailBee.AddressCheckEmailAddressValidator

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EmailAddressValidator : IComponent,
    IDisposable
Public Class EmailAddressValidator
    Implements IComponent, IDisposable

The EmailAddressValidator type exposes the following members.

Constructors
 | Name | Description
Public method | EmailAddressValidator | Creates an instance of EmailAddressValidator class.
Public method | EmailAddressValidator(String) | Creates and unlocks an instance of EmailAddressValidator class.
Top
Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | ArrayToDataTable | Converts a string array into DataTable containing a single column named "email".
 | BeginVerify | Obsolete. Begins an asynchronous request for verifying a bulk of e-mails addresses.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Public method | EndVerify | Ends the pending asynchronous request for verification of e-mail addresses.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnVerified | Used by MailBee to raise Verified event.
Protected method | OnVerifying | Used by MailBee to raise Verifying event.
Public method | ResetState | Resets the internal state of the component.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Verify(String) | Validates a single e-mail address for correct syntax and, optionally, checks it for existence.
 | Verify(String) | Validates e-mail addresses in the string array given.
 | Verify(DataTable, String) | Validates e-mail addresses in the data table given.
 | Verify(IDataReader, String) | Validates e-mail addresses supplied by the data reader.
Public method | VerifyAsync(String) | async/await version of Verify(String).
Public method | VerifyAsync(String) | async/await version of Verify(String).
Public method | VerifyAsync(DataTable, String) | async/await version of Verify(DataTable, String).
Public method | VerifyAsync(IDataReader, String) | async/await version of Verify(IDataReader, String).
Top
Properties
 | Name | Description
Public property | DnsServers | Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.
Public property | HelloDomain | Gets or sets the domain string to use as an argument of HELO or EHLO commands when making test connections to SMTP MX servers.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | LocalEndPoint | Gets or sets the local end point which will be used when connecting to SMTP MX servers.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MailFrom | Gets or sets the string to be used as sender when making test connections to SMTP MX servers.
Public property | MaxThreadCount | Gets or sets the maximum number of threads MailBee may create during bulk verification of e-mail addresses. operations.
Public property | Pipelining | Gets or sets whether to use commands pipelining if it's supported by the SMTP MX server.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RegexPattern | Gets or sets the regular expression to check syntax of e-mail addresses.
Public property | Site | Gets or sets the object to be used as a site for the component.
Public property | SmtpTimeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the SMTP MX server.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | ValidationLevel | Gets or sets the level of deepness of e-mail address verification.
Public property | Version | Gets the version of the MailBee assembly.
Top
Events
 | Name | Description
 | DataReceived | Occurs when data is received from the network.
 | DataSent | Occurs when data is sent to the network.
Public event | Disposed | Occurs after the component was disposed.
Public event | ErrorOccurred | Occurs when MailBeeException is thrown internally.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if EmailAddressValidator.Log.MemoryLog is true).
 | Verified | Occurs once an e-mail addresses in a bulk series has been verified.
 | Verifying | Occurs when an e-mail address in a bulk series is about to be verified.
Top
Remarks

This class can validate single addresses and their lists (string array and DataTable are accepted). If your data source is different, you can also create and populate DataTable manually, using ArrayToDataTable(String) method.

There are several levels of verification: syntax check with a regular expression, DNS MX lookup of the domain part of the address, test connection to the SMTP MX server responsible for delivering e-mail to the given domain, and test send attempt (which means not only the connection is made but also the sender and the recipient are submitted to the server). Even in "send attempt" mode, the component does not actually send any e-mails, it stops at the point where the server accepted the given e-mail address as the valid recipient's address. How deep the verification will be is controlled with ValidationLevel property.

You can implement black and white listing of any e-mail addresses or domains in your collection by subscribing to Verifying event. It lets you skip any e-mails from verification, based on your criteria.

By default, the component works in single-thread mode. If you need to verify multiple addresses, you can greatly improve performance by setting MaxThreadCount property. Up to 60 threads are supported.

Note Note
Due to anti-spam filters on many servers, direct validation of e-mail addresses via making test connections and send attempts is not always 100% accurate (there can be both false positives and false negatives). See AddressValidationLevel topic for more details on how to deal with this.

For more info and tutorials, refer to Getting started with Address Validator guide.

Note Note
Database-related functionality is not available in .NET Core and UWP (only single e-mail addresses can be validated there).
Examples

This advanced sample reads and parses the list of e-mail addresses from C:\Temp\input.txt file (creating file it it's missing), performs blacklist check to remove all addresses ending with "@blacklisted.com", and verifies other addresses. Addresses with bad syntax are removed immediately, those which failed due to network errors are given second and third chance. Each run of the app performs a new check on the same list. In the end, no addresses will remain in the list as all the addresses there are fake (you can add real addresses so that the list wouldn't get empty).

For simpler (but less accurate and flexible) examples, refer to Verify(String) or Verified topics.

For clarity of its functioning, this sample does not use multi-threading (MaxThreadCount remains the default value, 1). In production, multi-threading is highly recommended for performance sake.

C#
VB
Copy
using System;
using System.IO;
using System.Data;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    const string EmailColumn = "email";
    const string FailureCountColumn = "failures";
    private static StreamWriter sw = null;

    // Builds the data table from the file contents.
    // For brevity, we don't check if the data has correct format.
    private static DataTable GetDataTable(string[] lines)
    {
        DataTable workTable = new DataTable();
        workTable.Columns.Add(EmailColumn, typeof(string));
        workTable.Columns.Add(FailureCountColumn, typeof(int));

        foreach (string line in lines)
        {
            string[] parts = line.Split(',');
            DataRow row = workTable.NewRow();
            row[EmailColumn] = parts[0];
            row[FailureCountColumn] = int.Parse(parts[1]);
            workTable.Rows.Add(row);
        }

        return workTable;
    }

    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified. Those addresses for which we set VerifyIt
    // to 'false' will be skipped from further verification and Verified
    // event won't occur for them.
    private static void valid_Verifying(object sender, VerifyingEventArgs e)
    {
        try
        {
            Console.WriteLine(string.Format("{0} is being checked against blacklist.", e.Email));

            if (e.Email.EndsWith("@blacklisted.com"))
            {
                // Exclude it from address checking by other methods, and forget it.
                e.VerifyIt = false;
                Console.WriteLine(string.Format("{0} removed due to blacklist hit.", e.Email));
            }

            if (e.VerifyIt)
            {
                Console.WriteLine(string.Format("{0} survived blacklist check.", e.Email));
            }
            else
            {
                Console.WriteLine(string.Format("Discarded: {0}", e.Email));
            }
        }
        catch (Exception ex)
        {
            // At least for debug purposes, it makes sense to catch all exceptions in
            // event handlers as uncaught exceptions here don't cause the app to crash.
            // Without this try/catch, it could be quite hard to understand what went wrong
            // as you'd see no indication of a problem, the event handler would silently
            // die in the middle but the app itself would continue.
            Console.WriteLine(ex.ToString());
        }

        Console.WriteLine();
    }

    // All those e-mail addresses which survived Verifying event handler then get validated,
    // and the validation results (which can be both successful or negative) will be delivered
    // to the application through Verified event handler.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        try
        {
            // Keep the address on the list?
            bool keepIt;

            Console.WriteLine(string.Format("{0}={1}", e.Email, e.Result.ToString()));
            if (e.Reason != null)
            {
                Console.WriteLine("Reason: " + e.Reason.Message);
            }
            int failureCount = (int)e.Row[FailureCountColumn];
            switch (e.Result)
            {
                case AddressValidationLevel.OK:
                    // Address is fine, reset the failure counter if needed.
                    if (failureCount != 0)
                    {
                        failureCount = 0;
                    }
                    keepIt = true;
                    break;
                case AddressValidationLevel.RegexCheck:
                    // Bad syntax, won't keep this address in the list.
                    keepIt = false;
                    break;
                default:
                    failureCount++;
                    if (failureCount > 3)
                    {
                        // Too many failed attempts. Forget this address.
                        keepIt = false;
                    }
                    else
                    {
                        // Give the address another chance.
                        keepIt = true;
                    }
                    break;
            }

            if (keepIt)
            {
                sw.WriteLine(string.Format("{0},{1}", e.Email, failureCount.ToString()));
                Console.WriteLine(string.Format("Written to the file: {0},{1}",
                    e.Email, failureCount.ToString()));
            }
            else
            {
                Console.WriteLine(string.Format("Discarded: {0}", e.Email));
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to events.
        valid.Verifying += new VerifyingEventHandler(valid_Verifying);
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        string inputFile = @"C:\Temp\input.txt";
        string outputFile = @"C:\Temp\output.txt";

        // Create a file with some e-mail addresses to check if it's not already there.
        if (!File.Exists(inputFile))
        {
            // Number is a count of failed attempts to check an address. If it exceeds 3, we'll
            // remove the address from the list. Addresses with invalid syntax will be removed
            // immediately.
            File.WriteAllText(inputFile,
@"john.doe@domain.com,0
user@blacklisted.com,0
alice@company.com,0
somebody@non-exisent.domain,0
bob@incorrect-syntax,0
sarah@example.com,0");
        }

        string[] lines = File.ReadAllLines(inputFile);

        if (lines.Length == 0)
        {
            Console.WriteLine("No addresses left in the list! Delete input.txt and try again.");
        }

        using (sw = new StreamWriter(outputFile))
        {
            // Run the verification in single-threaded mode (for clarity of console output).
            valid.Verify(GetDataTable(lines), EmailColumn);
        }

        // Once the verification finished, replace the input file with the recently generated.
        // This way, we'll refine our list each time the app is run. After several runs, only
        // good addresses will remain.
        File.Delete(inputFile);
        File.Move(outputFile, inputFile);
    }
}
Imports System.IO
Imports System.Data
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    Const EmailColumn As String = "email"
    Const FailureCountColumn As String = "failures"
    Private Shared sw As StreamWriter = Nothing

    ' Builds the data table from the file contents.
    ' For brevity, we don't check if the data has correct format.
    Private Shared Function GetDataTable(ByVal lines As String()) As DataTable
        Dim workTable As New DataTable()
        workTable.Columns.Add(EmailColumn, GetType(String))
        workTable.Columns.Add(FailureCountColumn, GetType(Integer))

        For Each line As String In lines
            Dim parts As String() = line.Split(","c)
            Dim row As DataRow = workTable.NewRow()
            row(EmailColumn) = parts(0)
            row(FailureCountColumn) = Integer.Parse(parts(1))
            workTable.Rows.Add(row)
        Next

        Return workTable
    End Function

    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified. Those addresses for which we set VerifyIt
    ' to 'false' will be skipped from further verification and Verified
    ' event won't occur for them.
    Private Shared Sub valid_Verifying(ByVal sender As Object, ByVal e As VerifyingEventArgs)
        Try
            Console.WriteLine(String.Format("{0} is being checked against blacklist.", e.Email))

            If e.Email.EndsWith("@blacklisted.com") Then
                ' Exclude it from address checking by other methods, and forget it.
                e.VerifyIt = False
                Console.WriteLine(String.Format("{0} removed due to blacklist hit.", e.Email))
            End If

            If e.VerifyIt Then
                Console.WriteLine(String.Format("{0} survived blacklist check.", e.Email))
            Else
                Console.WriteLine(String.Format("Discarded: {0}", e.Email))
            End If
        Catch ex As Exception
            ' At least for debug purposes, it makes sense to catch all exceptions in
            ' event handlers as uncaught exceptions here don't cause the app to crash.
            ' Without this try/catch, it could be quite hard to understand what went wrong
            ' as you'd see no indication of a problem, the event handler would silently
            ' die in the middle but the app itself would continue.
            Console.WriteLine(ex.ToString())
        End Try

        Console.WriteLine()
    End Sub

    ' All those e-mail addresses which survived Verifying event handler then get validated,
    ' and the validation results (which can be both successful or negative) will be delivered
    ' to the application through Verified event handler.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Try
            ' Keep the address on the list?
            Dim keepIt As Boolean

            Console.WriteLine(String.Format("{0}={1}", e.Email, e.Result.ToString()))
            If Not (e.Reason Is Nothing) Then
                Console.WriteLine("Reason: " & e.Reason.Message)
            End If
            Dim failureCount As Integer = CInt(e.Row(FailureCountColumn))
            Select Case e.Result
                Case AddressValidationLevel.OK
                    ' Address is fine, reset the failure counter if needed.
                    If failureCount <> 0 Then
                        failureCount = 0
                    End If
                    keepIt = True
                    Exit Select
                Case AddressValidationLevel.RegexCheck
                    ' Bad syntax, won't keep this address in the list.
                    keepIt = False
                    Exit Select
                Case Else
                    failureCount += 1
                    If failureCount > 3 Then
                        ' Too many failed attempts. Forget this address.
                        keepIt = False
                    Else
                        ' Give the address another chance.
                        keepIt = True
                    End If
                    Exit Select
            End Select

            If keepIt Then
                sw.WriteLine(String.Format("{0},{1}", e.Email, failureCount.ToString()))
                Console.WriteLine(String.Format("Written to the file: {0},{1}", _
                 e.Email, failureCount.ToString()))
            Else
                Console.WriteLine(String.Format("Discarded: {0}", e.Email))
            End If
        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        End Try

        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args As String())
        Dim valid As New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to events.
        AddHandler valid.Verifying, AddressOf valid_Verifying
        AddHandler valid.Verified, AddressOf valid_Verified

        Dim inputFile As String = "C:\Temp\input.txt"
        Dim outputFile As String = "C:\Temp\output.txt"

        ' Create a file with some e-mail addresses to check if it's not already there.
        If Not File.Exists(inputFile) Then
            ' Number is a count of failed attempts to check an address. If it exceeds 3, we'll
            ' remove the address from the list. Addresses with invalid syntax will be removed
            ' immediately.
            File.WriteAllText(inputFile, "john.doe@domain.com,0" & vbCrLf & _
             "user@blacklisted.com,0" & vbCrLf & "alice@company.com,0" & vbCrLf & _
             "somebody@non-exisent.domain,0" & vbCrLf & "bob@incorrect-syntax,0" & vbCrLf _
             & "sarah@example.com,0")
        End If

        Dim lines As String() = File.ReadAllLines(inputFile)

        If lines.Length = 0 Then
            Console.WriteLine("No addresses left in the list! Delete input.txt and try again.")
        End If

        sw = New StreamWriter(outputFile)

        Try
            ' Run the verification in single-threaded mode (for clarity of console output).
            valid.Verify(GetDataTable(lines), EmailColumn)
        Finally
            sw.Close()
        End Try

        ' Once the verification finished, replace the input file with the recently generated.
        ' This way, we'll refine our list each time the app is run. After several runs, only
        ' good addresses will remain.
        File.Delete(inputFile)
        File.Move(outputFile, inputFile)
    End Sub
End Class
See Also

Reference

MailBee.AddressCheck Namespace


EmailAddressValidator Constructor

EmailAddressValidator Constructor
Creates an instance of EmailAddressValidator class.
Overload List
 | Name | Description
Public method | EmailAddressValidator | Creates an instance of EmailAddressValidator class.
Public method | EmailAddressValidator(String) | Creates and unlocks an instance of EmailAddressValidator class.
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator Constructor

EmailAddressValidator Constructor
Creates an instance of EmailAddressValidator class.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressValidator()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET AddressValidator not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

EmailAddressValidator Class
EmailAddressValidator Overload
MailBee.AddressCheck Namespace


EmailAddressValidator Constructor (String)

EmailAddressValidator Constructor (String)
Creates and unlocks an instance of EmailAddressValidator class.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressValidator(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET AddressValidator not licensed and the supplied license key is invalid.
See Also

Reference

EmailAddressValidator Class
EmailAddressValidator Overload
MailBee.AddressCheck Namespace


EmailAddressValidator Methods

EmailAddressValidator Methods

The EmailAddressValidator type exposes the following members.

Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | ArrayToDataTable | Converts a string array into DataTable containing a single column named "email".
 | BeginVerify | Obsolete. Begins an asynchronous request for verifying a bulk of e-mails addresses.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Public method | EndVerify | Ends the pending asynchronous request for verification of e-mail addresses.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnVerified | Used by MailBee to raise Verified event.
Protected method | OnVerifying | Used by MailBee to raise Verifying event.
Public method | ResetState | Resets the internal state of the component.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Verify(String) | Validates a single e-mail address for correct syntax and, optionally, checks it for existence.
 | Verify(String) | Validates e-mail addresses in the string array given.
 | Verify(DataTable, String) | Validates e-mail addresses in the data table given.
 | Verify(IDataReader, String) | Validates e-mail addresses supplied by the data reader.
Public method | VerifyAsync(String) | async/await version of Verify(String).
Public method | VerifyAsync(String) | async/await version of Verify(String).
Public method | VerifyAsync(DataTable, String) | async/await version of Verify(DataTable, String).
Public method | VerifyAsync(IDataReader, String) | async/await version of Verify(IDataReader, String).
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Abort Method

EmailAddressValidatorAbort Method
Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Abort()
Public Sub Abort
Remarks

A method which was in progress when Abort method has been called will throw MailBeeUserAbortException.

This method tries to abort the current network operation immediately, which works for all cases except of resolving a domain name into IP address. Due to .NET framework limitations, this operation cannot be aborted. Thus, sometimes you may experience a several seconds delay between calling this method and getting MailBeeUserAbortException (the time needed for DNS resolve to complete).

Note Note
No events will be raised after this method has been called.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorIsAborted


EmailAddressValidator.ArrayToDataTable Method

EmailAddressValidatorArrayToDataTable Method
Converts a string array into DataTable containing a single column named "email".

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable ArrayToDataTable(
    string[] emails
)
Public Function ArrayToDataTable (
    emails As String()
) As DataTable

Parameters

emails
Type: SystemString
The strings to be put into the resulting data table.

Return Value

Type: DataTable
The data table containing all the strings from the given array put under the "email" column.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails is a null reference (Nothing in Visual Basic).
Remarks
This method is helpful if you need to pass a string array to BeginVerify(DataTable, IDataReader, String, AsyncCallback, Object) asynchronous method which accepts only DataTable as input. At the same time, normal version of Verify method already has Verify(String) overload which accepts string arrays directly.
Examples
The sample below is actually exerpt from MailBee.NET Objects source code which contains the essential parts of ArrayToDataTable(String) method. You can use it as a template to copy-paste and edit if you need to populate DataTable from other sources (like collections, lists or whatever).
C#
VB
Copy
public DataTable ArrayToDataTable(string[] emails)
{
    DataTable workTable = new DataTable();
    workTable.Columns.Add("email", typeof(string));
    foreach (string email in emails)
    {
        DataRow row = workTable.NewRow();
        row["email"] = email;
        workTable.Rows.Add(row);
    }
    return workTable;
}
Public Function ArrayToDataTable(ByVal emails As String()) As DataTable
    Dim workTable As New DataTable
    workTable.Columns.Add("email", GetType(String))
    For Each email As String In emails
        Dim row As DataRow = workTable.NewRow()
        row("email") = email
        workTable.Rows.Add(row)
    Next
    Return workTable
End Function
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.BeginVerify Method

EmailAddressValidatorBeginVerify Method

Note: This API is now obsolete.

Begins an asynchronous request for verifying a bulk of e-mails addresses.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use VerifyAsync instead.")]
public IAsyncResult BeginVerify(
    DataTable emailsAsTable,
    IDataReader emailsAsReader,
    string columnName,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use VerifyAsync instead.")>
Public Function BeginVerify (
    emailsAsTable As DataTable,
    emailsAsReader As IDataReader,
    columnName As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

emailsAsTable
Type: System.DataDataTable
The data table, in columnName column containing the e-mail addresses to check for syntax and, optionally, for existence. Either emailsAsTable or emailsAsReader must be set.
emailsAsReader
Type: System.DataIDataReader
The alternate data source if the application supplies data through IDataReader rather than DataTable.
columnName
Type: SystemString
The name of column in the given data table or data reader, containing the e-mail addresses.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous verification of e-mail addresses.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | Both emailsAsTable and emailsAsTable are a null reference (Nothing in Visual Basic), or columnName is a null reference or an empty string, or DnsServers collection is empty.
Remarks
Note Note
New applications (.NET 4.5+) should use async/await methods instead. The are more efficient and easier to use.

If you set both emailsAsTable and emailsAsReader, emailsAsReader will be ignored.

If you have a string array of e-mails rather than a DataTable, you can use ArrayToDataTable(String) method to make conversion prior to calling this method.

Examples

This WinForms sample demonstrates using async e-mail verification process.

To run it, you'll need to create a WinForm app, put button1 on the form, in Form1 properties click FormClosed event to create its handler, click button1 to create its handler, then replace the Form1.cs/Form1.vb with the code below. C#-specific: the sample below is not wrapped into any namespace so you'll need to remove wrapping namespace from Form1.Designer.cs as well.

This sample also highlights some interesting aspects of multi-threaded and async programming of WinForms apps which are not directly related to MailBee but can help beginner progammers avoid common pitfalls.

C#
VB
Copy
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MailBee;
using MailBee.AddressCheck;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private EmailAddressValidator valid = null;
    private StreamWriter sw = null;

    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private void valid_Verified(object sender, VerifiedEventArgs e)
    {
        try
        {
            // Note that unlike Console version of this sample, which can be found in the documentation on
            // EmailAddressValidator.Verify(DataTable, string) method, we're not using lock here. This is
            // because in WinForms apps events are raised on a single thread (message loop thread), and this
            // eliminates the need to synchronize threads. If we were using Console or ASP.NET app, lock
            // (SyncLock in VB) would be required. Also, it's required if instead of using Verified event,
            // you inherited EmailAddressValidator class and overrided OnVerified method (such methods can
            // execute on any thread).
            sw.WriteLine(string.Format("{0}={1}", e.Email, e.Result.ToString()));
        }
        catch (Exception ex)
        {
            // This is also important. In multi-threaded mode, crashing due to an exception simply
            // closes the worker thread and you may never know what really happened. Thus, it's recommended
            // (at least in debug) to catch all exceptions there and print them out (here, alert window).
            MessageBox.Show(ex.ToString());
        }
    }

    // As it's not allowed to make changes to UI (such as to update button text) directly in the callback
    // (it's Windows limitation) we need to dispatch the call to the message loop thread.
    private delegate void UpdateUserInterfaceDelegate();
    private void UpdateUserInterface()
    {
        button1.Text = "Done";
    }

    // This callback is executed when all addresses have been verified and all threads have been completed.
    private void VerifyCallback(IAsyncResult result)
    {
        try
        {
            // Callbacks can execute on any thread (see the comment in valid_Verified why this can be
            // important). However, we have only one callback, and it does not compete with other callbacks
            // for accessing thread-unsafe resources. If we had the code which can run multiple callbacks
            // simultaneously and the callback included the code used some shared resource (like the same
            // file to write to) we had to guard that code with lock (SyncLock in VB) in that case.
            valid.EndVerify();

            // Another problem of callback's execution on any thread is that we cannot update user interface
            // from a callback. User interface updates must occur only on the main thread (message loop).
            // To workaround this, we're using Invoke which executes UI update on the message loop thread.
            Invoke(new UpdateUserInterfaceDelegate(UpdateUserInterface), null);
        }
        catch (MailBeeUserAbortException)
        {
            sw.WriteLine("Aborted by user");
        }
        finally
        {
            sw.Close();
        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (valid != null)
        {
            // If the user wants to cancel and closes the app, abort things.
            valid.Abort();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (valid != null && valid.IsBusy)
        {
            // No re-entrance while working.
            MessageBox.Show("Busy!");
            return;
        }

        button1.Text = "Busy";
        valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        // Since this sample is multi-threaded, we also set AddContextInfo option
        // to make it easier analyze the log (each record will be tagged with a thread ID).
        valid.Log.Enabled = true;
        valid.Log.Format = LogFormatOptions.AddContextInfo;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to event.
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // In this sample, we'll build DataTable manually from a string array.
        string[] emails = new string[10];
        for (int i = 0; i < emails.Length; i++)
        {
            // Make user0@domain0.com, user1@domain1.com, ..., user9@domain9.com.
            emails[i] = string.Format("user{0}@domain{0}.com", i.ToString());
        }

        // In real apps, you'll get data from database. For now, populate data from
        // string array by putting all the data into a table with one column "email".
        DataTable data = valid.ArrayToDataTable(emails);

        // Enable as many threads as possible.
        valid.MaxThreadCount = -1;

        sw = new StreamWriter(@"C:\Temp\report.txt");

        // Run the verification in multi-threaded mode, asynchronously.
        valid.BeginVerify(data, null, "email", new AsyncCallback(VerifyCallback), null);
    }
}
Imports System.IO
Imports System.Data
Imports MailBee
Imports MailBee.AddressCheck

Public Class Form1
    Private valid As EmailAddressValidator = Nothing
    Private sw As StreamWriter = Nothing

    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Try
            ' Note that unlike Console version of this sample, which can be found in the documentation on
            ' EmailAddressValidator.Verify(DataTable, string) method, we're not using lock here. This is
            ' because in WinForms apps events are raised on a single thread (message loop thread), and this
            ' eliminates the need to synchronize threads. If we were using Console or ASP.NET app, lock
            ' (SyncLock in VB) would be required. Also, it's required if instead of using Verified event,
            ' you inherited EmailAddressValidator class and overrided OnVerified method (such methods can
            ' execute on any thread).
            sw.WriteLine(String.Format("{0}={1}", e.Email, e.Result.ToString()))
        Catch ex As Exception
            ' This is also important. In multi-threaded mode, crashing due to an exception simply
            ' closes the worker thread and you may never know what really happened. Thus, it's recommended
            ' (at least in debug) to catch all exceptions there and print them out (here, alert window).
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

    ' As it's not allowed to make changes to UI (such as to update button text) directly in the callback
    ' (it's Windows limitation) we need to dispatch the call to the message loop thread.
    Private Delegate Sub UpdateUserInterfaceDelegate()
    Private Sub UpdateUserInterface()
        Button1.Text = "Done"
    End Sub

    ' This callback is executed when all addresses have been verified and all threads have been completed.
    Private Sub VerifyCallback(ByVal result As IAsyncResult)
        Try
            ' Callbacks can execute on any thread (see the comment in valid_Verified why this can be
            ' important). However, we have only one callback, and it does not compete with other callbacks
            ' for accessing thread-unsafe resources. If we had the code which can run multiple callbacks
            ' simultaneously and the callback included the code used some shared resource (like the same
            ' file to write to) we had to guard that code with lock (SyncLock in VB) in that case.
            valid.EndVerify()

            ' Another problem of callback's execution on any thread is that we cannot update user interface
            ' from a callback. User interface updates must occur only on the main thread (message loop).
            ' To workaround this, we're using Invoke which executes UI update on the message loop thread.
            Invoke(New UpdateUserInterfaceDelegate(AddressOf UpdateUserInterface), Nothing)
        Catch generatedExceptionName As MailBeeUserAbortException
            sw.WriteLine("Aborted by user")
        Finally
            sw.Close()
        End Try
    End Sub

    Private Sub Form1_FormClosed_1(ByVal sender As System.Object, _
     ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        If Not (valid Is Nothing) Then
            ' If the user wants to cancel and closes the app, abort things.
            valid.Abort()
        End If
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles Button1.Click
        If Not (valid Is Nothing) AndAlso valid.IsBusy Then
            ' No re-entrance while working.
            MessageBox.Show("Busy!")
            Return
        End If

        Button1.Text = "Busy"
        valid = New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        ' Since this sample is multi-threaded, we also set AddContextInfo option
        ' to make it easier analyze the log (each record will be tagged with a thread ID).
        valid.Log.Enabled = True
        valid.Log.Format = LogFormatOptions.AddContextInfo
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to event.
        AddHandler valid.Verified, AddressOf valid_Verified

        ' In this sample, we'll build DataTable manually from a string array.
        Dim emails As String() = New String(9) {}
        For i As Integer = 0 To emails.Length - 1
            ' Make user0@domain0.com, user1@domain1.com, ..., user9@domain9.com.
            emails(i) = String.Format("user{0}@domain{0}.com", i.ToString())
        Next

        ' In real apps, you'll get data from database. For now, populate data from
        ' string array by putting all the data into a table with one column "email".
        Dim data As DataTable = valid.ArrayToDataTable(emails)

        ' Enable as many threads as possible.
        valid.MaxThreadCount = -1

        sw = New StreamWriter("C:\Temp\report.txt")

        ' Run the verification in multi-threaded mode, asynchronously.
        valid.BeginVerify(data, Nothing, "email", New AsyncCallback(AddressOf VerifyCallback), Nothing)
    End Sub
End Class
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Dispose Method

EmailAddressValidatorDispose Method
Overload List
 | Name | Description
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Dispose Method

EmailAddressValidatorDispose Method
Closes opened network connections (if any) and releases any used system resources.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
Usually, the developer does not need to call this method as the object can free its resources automatically.
See Also

Reference

EmailAddressValidator Class
Dispose Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.Dispose Method (Boolean)

EmailAddressValidatorDispose Method (Boolean)
When overridden in a derived class, must release unmananged and optionally managed resources used by the component.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Remarks
If the derived class does not use any additional resources, this method does not need to be overridden. If, however, it's overridden, the developer must also call Dispose method of the base class.
See Also

Reference

EmailAddressValidator Class
Dispose Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.EndVerify Method

EmailAddressValidatorEndVerify Method
Ends the pending asynchronous request for verification of e-mail addresses.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void EndVerify()
Public Sub EndVerify
Exceptions
Exception | Condition
MailBeeUserAbortException | The user code has aborted the component with Abort method.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorBeginVerify(DataTable, IDataReader, String, AsyncCallback, Object)


EmailAddressValidator.OnDataReceived Method

EmailAddressValidatorOnDataReceived Method
Used by MailBee to raise DataReceived event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorDataReceived
SmtpOnConnected(ConnectedEventArgs)


EmailAddressValidator.OnDataSent Method

EmailAddressValidatorOnDataSent Method
Used by MailBee to raise DataSent event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataSent(
    DataTransferEventArgs args
)
Protected Sub OnDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorDataSent
SmtpOnConnected(ConnectedEventArgs)


EmailAddressValidator.OnErrorOccurred Method

EmailAddressValidatorOnErrorOccurred Method
Used by MailBee to raise ErrorOccurred event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnErrorOccurred(
    ErrorEventArgs args
)
Protected Sub OnErrorOccurred (
    args As ErrorEventArgs
)

Parameters

args
Type: MailBeeErrorEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorErrorOccurred


EmailAddressValidator.OnLogNewEntry Method

EmailAddressValidatorOnLogNewEntry Method
Used by MailBee to raise LogNewEntry event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLogNewEntry(
    LogNewEntryEventArgs args
)
Protected Sub OnLogNewEntry (
    args As LogNewEntryEventArgs
)

Parameters

args
Type: MailBeeLogNewEntryEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorLogNewEntry


EmailAddressValidator.OnVerified Method

EmailAddressValidatorOnVerified Method
Used by MailBee to raise Verified event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnVerified(
    VerifiedEventArgs args
)
Protected Sub OnVerified (
    args As VerifiedEventArgs
)

Parameters

args
Type: MailBee.AddressCheckVerifiedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorVerified
SmtpOnConnected(ConnectedEventArgs)


EmailAddressValidator.OnVerifying Method

EmailAddressValidatorOnVerifying Method
Used by MailBee to raise Verifying event.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnVerifying(
    VerifyingEventArgs args
)
Protected Sub OnVerifying (
    args As VerifyingEventArgs
)

Parameters

args
Type: MailBee.AddressCheckVerifyingEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
EmailAddressValidatorVerifying
SmtpOnConnected(ConnectedEventArgs)


EmailAddressValidator.ResetState Method

EmailAddressValidatorResetState Method
Resets the internal state of the component.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ResetState()
Public Sub ResetState
Exceptions
Exception | Condition
MailBeeInvalidStateException | The component is busy. If you need to abort the currently performed operation, call Abort instead.
Remarks
This method will close any opened connections, and will remove IsAborted status if Abort method was previously called. Typically, the developer may use this method to reuse the component after it went into aborted state due to Abort method call.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Verify Method

EmailAddressValidatorVerify Method
Verifies one or more e-mail addresses for correct syntax and, optionally, for existence.
Overload List
Name | Description
Verify(String) | Validates a single e-mail address for correct syntax and, optionally, checks it for existence.
Verify(String) | Validates e-mail addresses in the string array given.
Verify(DataTable, String) | Validates e-mail addresses in the data table given.
Verify(IDataReader, String) | Validates e-mail addresses supplied by the data reader.
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Verify Method (String)

EmailAddressValidatorVerify Method (String)
Validates a single e-mail address for correct syntax and, optionally, checks it for existence.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AddressValidationLevel Verify(
    string email
)
Public Function Verify (
    email As String
) As AddressValidationLevel

Parameters

email
Type: SystemString
The e-mail address to check. Must be somewhat like "user@domain.com".

Return Value

Type: AddressValidationLevel
OK if the validation succeeded, or the particular validation level at which the verification failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic) or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
Remarks
This overload does not raise Verifying and Verified events.
Examples
This sample verifies a single e-mail address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.AddressCheck;

// The actual code (put it into a method of your class)

EmailAddressValidator valid = new EmailAddressValidator();
valid.Log.Enabled = true;
valid.Log.Filename = @"C:\Temp\log.txt";
valid.DnsServers.Autodetect();
Console.WriteLine(valid.Verify("jdoe@company.com").ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.AddressCheck

' The actual code (put it into a method of your class)

Dim valid = New EmailAddressValidator
valid.Log.Enabled = True
valid.Log.Filename = "C:\Temp\log.txt"
valid.DnsServers.Autodetect()
Console.WriteLine(valid.Verify("jdoe@company.com").ToString())
See Also

Reference

EmailAddressValidator Class
Verify Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.Verify Method (String[])

EmailAddressValidatorVerify Method (String)
Validates e-mail addresses in the string array given.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Verify(
    string[] emails
)
Public Sub Verify (
    emails As String()
)

Parameters

emails
Type: SystemString
The array containing the e-mail addresses to check for syntax and, optionally, for existence.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails is a null reference (Nothing in Visual Basic) or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
Remarks

To analyze the results, subscribe to Verified event. To implement blacklist or whitelist, subscribe to Verifying event.

For more info and tutorials, refer to Getting started with Address Validator guide.

Examples
This sample verifies a bulk of 3 addresses. Multi-threading is not used. To activate multi-threading, set MaxThreadCount property.
C#
VB
Copy
using System;
using MailBee;
using MailBee.AddressCheck;
class Program
{
    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        Console.WriteLine("*** Verified ***");
        Console.WriteLine("Email: " + e.Email);
        Console.WriteLine("Result: " + e.Result.ToString());
        if (e.Reason != null)
        {
            Console.WriteLine("Reason: " + e.Reason.Message);
        }
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to event.
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // Populate an array with some e-mails. You can also use DataTable as a source.
        string[] emails = new string[] { "jdoe@company.com", "bob@example.com", "alice@domain.com" };

        // Run the verification in single-threaded mode.
        valid.Verify(emails);
    }
}
Imports System
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Console.WriteLine("*** Verified ***")
        Console.WriteLine(("Email: " & e.Email))
        Console.WriteLine(("Result: " & e.Result.ToString))
        If (Not (e.Reason) Is Nothing) Then
            Console.WriteLine(("Reason: " & e.Reason.Message))
        End If
        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim valid As EmailAddressValidator = New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to event.
        AddHandler valid.Verified, AddressOf valid_Verified

        ' Populate an array with some e-mails. You can also use DataTable as a source.
        Dim emails() As String = New String() {"jdoe@company.com", "bob@example.com", "alice@domain.com"}

        ' Run the verification in single-threaded mode.
        valid.Verify(emails)
    End Sub
End Class
See Also

Reference

EmailAddressValidator Class
Verify Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.Verify Method (DataTable, String)

EmailAddressValidatorVerify Method (DataTable, String)
Validates e-mail addresses in the data table given.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Verify(
    DataTable emails,
    string columnName
)
Public Sub Verify (
    emails As DataTable,
    columnName As String
)

Parameters

emails
Type: System.DataDataTable
The data table, in columnName column containing the e-mail addresses to check for syntax and, optionally, for existence.
columnName
Type: SystemString
The name of column in the given data table, containing the e-mail addresses.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails or columnName is a null reference (Nothing in Visual Basic), columnName is an empty string, or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
Remarks

To analyze the results, subscribe to Verified event. To implement blacklist or whitelist, subscribe to Verifying event.

For more info and tutorials, refer to Getting started with Address Validator guide.

Examples
This sample builds a data table with some e-mail addresses, and verifies them (in real apps, you'll usually get data from database). For performance sake, multi-threading is in use.
Note Note
Unlike similar sample in Getting started with Address Validator guide, the sample below also shows how to deal with race conditions. The sample below uses StreamWriter class to save results in a file. However, this class is not thread-safe. In multi-threaded scenario, you can get situation when multiple threads will try to write into the same file. This is not a problem when MailBee writes from many threads into a single log file (Log property) because it's controlled by MailBee. But StreamWriter instance was created by our own application and needs its own thread synchronizing.
C#
VB
Copy
using System;
using System.IO;
using System.Data;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    private static object syncObject = new object();
    private static StreamWriter sw;

    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        Console.WriteLine("*** Verified ***");
        Console.WriteLine("Email: " + e.Email);
        Console.WriteLine("Result: " + e.Result.ToString());
        if (e.Reason != null)
        {
            Console.WriteLine("Reason: " + e.Reason.Message);
        }
        Console.WriteLine();

        try
        {
            // This lock guarantees only one thread at a time will execute the guarded section.
            lock (syncObject)
            {
                sw.WriteLine(string.Format("{0}={1}", e.Email, e.Result.ToString()));
            }
        }
        catch (Exception ex)
        {
            // This is also important. In multi-threaded mode, crashing due to an exception simply
            // closes the worker thread and you may never know what really happened. Thus, it's recommended
            // (at least in debug) to catch all exceptions there and print them out (such as to Console).
            Console.WriteLine(ex.ToString());
        }
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        // Since this sample is multi-threaded, we also set AddContextInfo option
        // to make it easier analyze the log (each record will be tagged with a thread ID).
        valid.Log.Enabled = true;
        valid.Log.Format = LogFormatOptions.AddContextInfo;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to event.
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // In this sample, we'll build DataTable manually from a string array.
        string[] emails = new string[10];
        for (int i = 0; i < emails.Length; i++)
        {
            // Make user0@domain0.com, user1@domain1.com, ..., user9@domain9.com.
            emails[i] = string.Format("user{0}@domain{0}.com", i.ToString());
        }

        // In real apps, you'll get data from database. For now, populate data from
        // string array by putting all the data into a table with one column "email".
        DataTable data = valid.ArrayToDataTable(emails);

        // Enable as many threads as possible.
        valid.MaxThreadCount = -1;

        using (sw = new StreamWriter(@"C:\Temp\report.txt"))
        {
            // Run the verification in multi-threaded mode.
            valid.Verify(data, "email");
        }
    }
}
Imports System.IO
Imports System.Data
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    Private Shared syncObject As New Object()
    Private Shared sw As StreamWriter

    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Shared Sub valid_Verified(sender As Object, e As VerifiedEventArgs)
        Console.WriteLine("*** Verified ***")
        Console.WriteLine("Email: " & e.Email)
        Console.WriteLine("Result: " & e.Result.ToString())
        If Not (e.Reason Is Nothing) Then
            Console.WriteLine("Reason: " & e.Reason.Message)
        End If
        Console.WriteLine()

        Try
            ' This lock guarantees only one thread at a time will execute the guarded section.
            SyncLock syncObject
                sw.WriteLine(String.Format("{0}={1}", e.Email, e.Result.ToString()))
            End SyncLock
        Catch ex As Exception
            ' This is also important. In multi-threaded mode, crashing due to an exception simply
            ' closes the worker thread and you may never know what really happened. Thus, it's recommended
            ' (at least in debug) to catch all exceptions there and print them out (such as to Console).
            Console.WriteLine(ex.ToString())
        End Try
    End Sub

    Shared Sub Main(args As String())
        Dim valid As New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        ' Since this sample is multi-threaded, we also set AddContextInfo option
        ' to make it easier analyze the log (each record will be tagged with a thread ID).
        valid.Log.Enabled = True
        valid.Log.Format = LogFormatOptions.AddContextInfo
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to event.
        AddHandler valid.Verified, AddressOf valid_Verified

        ' In this sample, we'll build DataTable manually from a string array.
        Dim emails As String() = New String(9) {}
        For i As Integer = 0 To emails.Length - 1
            ' Make user0@domain0.com, user1@domain1.com, ..., user9@domain9.com.
            emails(i) = String.Format("user{0}@domain{0}.com", i.ToString())
        Next

        ' In real apps, you'll get data from database. For now, populate data from
        ' string array by putting all the data into a table with one column "email".
        Dim data As DataTable = valid.ArrayToDataTable(emails)

        ' Enable as many threads as possible.
        valid.MaxThreadCount = -1

        sw = New StreamWriter("C:\Temp\report.txt")
        Try
            ' Run the verification in multi-threaded mode.
            valid.Verify(data, "email")
        Finally
            sw.Close
        End Try
    End Sub
End Class
See Also

Reference

EmailAddressValidator Class
Verify Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.Verify Method (IDataReader, String)

EmailAddressValidatorVerify Method (IDataReader, String)
Validates e-mail addresses supplied by the data reader.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Verify(
    IDataReader emails,
    string columnName
)
Public Sub Verify (
    emails As IDataReader,
    columnName As String
)

Parameters

emails
Type: System.DataIDataReader
The data reader, in columnName column containing the e-mail addresses to check for syntax and, optionally, for existence.
columnName
Type: SystemString
The name of column in the given data reader, containing the e-mail addresses.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails or columnName is a null reference (Nothing in Visual Basic), columnName is an empty string, or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
Remarks

To analyze the results, subscribe to Verified event. To implement blacklist or whitelist, subscribe to Verifying event.

For more info and tutorials, refer to Getting started with Address Validator guide or examine AddressValidatorDemo sample project in MailBee.NET Samples folder.

Examples

This sample takes e-mail addresses from 'emails' table contained in an MS SQL Server database, and verifies them. The table must have numeric 'id' and string (such as nvarchar) 'email' fields.

Multi-threading is in use, and the sample works in the way that it's compatible with forward-only database cursors. Despite of many concurrent threads, the code accesses each data row only once in the sequential order. Once a row has been read, the component remembers the data from it in a temporary storage for later use. Thus, it's safe to advance the data reader and lose the context of the current record as its data are already cached. The component then exposes the cached data to the application code through event handlers. The sample uses this data to implement blacklisting and whitelisting and to report 'id' values of all records being processed, to the console. Read DataReader topic for more info on accessing data reader directly or cached data, in event handlers.

The sample does not save the results of verification in the database. See AddressValidatorDemo sample project if you need this, or browse other code snippets in Getting started with Address Validator guide.

C#
VB
Copy
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    const string SqlDataSource = @"(local)\SQLEXPRESS";
    const string SqlDatabase = "afterlogic";
    const string SqlTable = "emails";
    const string EmailColumn = "email";
    const string IdColumn = "id";

    // Set to false to see another method of reading data from data row in event handlers.
    // Also, when false, it would be much easier to understand the console output as lines
    // from different threads won't mix. Still, 'id' field should help you understand to
    // which email address certain output line corresponds, even in multi-threaded mode.
    const bool EnableMultiThreading = true;

    static SqlConnection _sqlConnection;
    static SqlDataReader _dataReader;
    static SqlCommand _cmd;

    // Gets the data from SQL database. You must have a table such as the one made by
    // AddressValidatorDemo sample project, available in "MailBee.NET Objects\Samples\WinForms"
    // folder of "My Documents" (you can find this folder by clicking "Browse WinForms Samples"
    // button in "MailBee.NET Start Menu").
    //
    // The "emails" table needs to have at least "id" field (numeric) and "email" field
    // (nvarchar or other string type), and some rows in it.
    private static void OpenDataReader()
    {
        SqlConnectionStringBuilder connStringBuilder = new SqlConnectionStringBuilder();
        connStringBuilder.DataSource = SqlDataSource;
        connStringBuilder.InitialCatalog = SqlDatabase;

        // Change this to use SQL Server authentication.
        connStringBuilder.IntegratedSecurity = true;

        // In AddressValidatorDemo, we need MultipleActiveResultSets because we're reading and
        // writing data in the same SQL connection. But in this sample we don't write anything
        // to the SQL server. Thus, we don't need MultipleActiveResultSets functionality.

        // Should you need to write to the database, create separate SqlConnection for that
        // or uncomment the next line.

        // connStringBuilder.MultipleActiveResultSets = true;

        _sqlConnection = new SqlConnection(connStringBuilder.ConnectionString);
        _sqlConnection.Open();
        _cmd = _sqlConnection.CreateCommand();
        _cmd.CommandText = "SELECT * FROM " + SqlTable;
        _dataReader = _cmd.ExecuteReader();
    }

    private static void FreeDataReader()
    {
        if (_dataReader != null)
        {
            _dataReader.Close();
            _dataReader = null;
        }
        if (_cmd != null)
        {
            _cmd.Dispose();
            _cmd = null;
        }
        if (_sqlConnection != null)
        {
            _sqlConnection.Close();
            _sqlConnection = null;
        }
    }

    // This method will be executed for each e-mail address in the bulk,whenever it gets verified.
    // Those addresses for which we set VerifyIt to 'false' will be skipped from further verification
    // and Verified event won't occur for them. This is true for both blacklist and whitelist, in either
    // case we don't need to process the e-mail address deeper if it's already on any of these lists.
    private static void valid_Verifying(object sender, VerifyingEventArgs e)
    {
        try
        {
            // See valid_Verified for explanations.
            int id = (int)e.DataReaderRowValues[0];

            string idStr = id.ToString();

            Console.WriteLine(string.Format("{0}: {1} is being checked against blacklist.",
                idStr, e.Email));

            if (e.Email.EndsWith("@domain.com"))
            {
                // Exclude it from address checking by other methods, and forget it.
                e.VerifyIt = false;
                Console.WriteLine(string.Format("{0}: {1} removed due to blacklist hit.", idStr, e.Email));
            }

            if (e.Email.EndsWith("@server.com"))
            {
                // Exclude it from address checking by other methods, and forget it.
                e.VerifyIt = false;
                Console.WriteLine(string.Format("{0}: {1} does not checking as it's on blacklist.",
                    idStr, e.Email));
            }

            if (e.VerifyIt)
            {
                Console.WriteLine(string.Format("{0}: {1} survived blacklist check and not on whitelist.",
                    idStr, e.Email));
            }
            else
            {
                Console.WriteLine(string.Format("{0}: {1} skipped from further verification.",
                    idStr, e.Email));
            }
        }
        catch (Exception ex)
        {
            // At least for debug purposes, it makes sense to catch all exceptions in
            // event handlers as uncaught exceptions here don't cause the app to crash.
            // Without this try/catch, it could be quite hard to understand what went wrong
            // as you'd see no indication of a problem, the event handler would silently
            // die in the middle but the app itself would continue.
            Console.WriteLine(ex.ToString());
        }

        if (!EnableMultiThreading)
        {
            // See valid_Verified for explanations.
            Console.WriteLine();
        }
    }

    // All those e-mail addresses which passed Verifying event handler then get validated,
    // and the validation results (which can be both successful or negative) will be delivered
    // to the application through Verified event handler.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        try
        {
            int id;

            if (EnableMultiThreading)
            {
                // Demonstrate taking 'id' field. Unlike DataTable, IDataReader does not always permit
                // access to a data row for more than once (which happens when MailBee reads data from it).
                // Luckily, MailBee saves the data row it has read, for later use. That's how you can use it.
                id = (int)e.DataReaderRowValues[0];

                // Or, if we didn't know that 'id' is column #0, we could find it by name:
                id = (int)e.DataReaderRowValues[Array.IndexOf(e.DataReaderColumnNames, "id")];
            }
            else
            {
                // Who said that it's not possible to read from any IDataReader any number of times? Actually,
                // SqlDataReader allows us to read a current row as many times as we want. The only issue is
                // that when the app is multi-threaded, another thread may already advance the reader to the
                // next position and we won't have right data here. But when there is only one thread using
                // the data reader, it's not a problem to read directly from it.
                //
                // Note that it's always safe to use reading from DataReaderRowValues. Just in case if for
                // some reason your app is single-threaded and for a very special reason you need to access
                // IDataReader directly, you now know how to do it.
                id = (int)_dataReader.GetValue(0);

                // Or by name.
                id = (int)_dataReader.GetValue(_dataReader.GetOrdinal("id"));
            }

            string idStr = id.ToString();

            // That's where we display the determined validation level at which the process failed, or OK.
            Console.WriteLine(string.Format("{0}: email={1}, result={2}",
                idStr, e.Email, e.Result.ToString()));

            if (e.Reason != null)
            {
                Console.WriteLine(string.Format("{0}: Reason is: {1}", idStr, e.Reason.Message));
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        if (!EnableMultiThreading)
        {
            // Adding empty lines for clarity at the end of an event handler (to visually separate
            // processing of individual e-mail addresses) makes sense only in single-threaded mode.
            // When multi-threading is on, output from different thread mixes and makes inserting
            // empty lines useless.
            Console.WriteLine();
        }
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to events.
        valid.Verifying += new VerifyingEventHandler(valid_Verifying);
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        if (EnableMultiThreading)
        {
            valid.MaxThreadCount = -1;
        }

        try
        {
            OpenDataReader();

            // Run the verification in multi-threaded or single-threaded mode
            // (adjust EnableMultiThreading const to change the mode).
            valid.Verify(_dataReader, EmailColumn);
        }
        finally
        {
            FreeDataReader();
        }
    }
}
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    Const SqlDataSource As String = "(local)\SQLEXPRESS"
    Const SqlDatabase As String = "afterlogic"
    Const SqlTable As String = "emails"
    Const EmailColumn As String = "email"
    Const IdColumn As String = "id"

    ' Set to false to see another method of reading data from data row in event handlers.
    ' Also, when false, it would be much easier to understand the console output as lines
    ' from different threads won't mix. Still, 'id' field should help you understand to
    ' which email address certain output line corresponds, even in multi-threaded mode.
    Const EnableMultiThreading As Boolean = True

    Shared _sqlConnection As SqlConnection
    Shared _dataReader As SqlDataReader
    Shared _cmd As SqlCommand

    ' Gets the data from SQL database. You must have a table such as the one made by
    ' AddressValidatorDemo sample project, available in "MailBee.NET Objects\Samples"
    ' folder of "My Documents" (you can find this folder by clicking "Browse WinForms Samples"
    ' button in "MailBee.NET Start Menu").
    '
    ' The "emails" table needs to have at least "id" field (numeric) and "email" field
    ' (nvarchar or other string type), and some rows in it.
    Private Shared Sub OpenDataReader()
        Dim connStringBuilder As New SqlConnectionStringBuilder()
        connStringBuilder.DataSource = SqlDataSource
        connStringBuilder.InitialCatalog = SqlDatabase

        ' Change this to use SQL Server authentication.
        connStringBuilder.IntegratedSecurity = True

        ' In AddressValidatorDemo, we need MultipleActiveResultSets because we're reading and
        ' writing data in the same SQL connection. But in this sample we don't write anything
        ' to the SQL server. Thus, we don't need MultipleActiveResultSets functionality.

        ' Should you need to write to the database, create separate SqlConnection for that
        ' or uncomment the next line.

        ' connStringBuilder.MultipleActiveResultSets = true;

        _sqlConnection = New SqlConnection(connStringBuilder.ConnectionString)
        _sqlConnection.Open()
        _cmd = _sqlConnection.CreateCommand()
        _cmd.CommandText = "SELECT * FROM " & SqlTable
        _dataReader = _cmd.ExecuteReader()
    End Sub

    Private Shared Sub FreeDataReader()
        If _dataReader IsNot Nothing Then
            _dataReader.Close()
            _dataReader = Nothing
        End If
        If _cmd IsNot Nothing Then
            _cmd.Dispose()
            _cmd = Nothing
        End If
        If _sqlConnection IsNot Nothing Then
            _sqlConnection.Close()
            _sqlConnection = Nothing
        End If
    End Sub

    ' This method will be executed for each e-mail address in the bulk,whenever it gets verified.
    ' Those addresses for which we set VerifyIt to 'false' will be skipped from further verification
    ' and Verified event won't occur for them. This is true for both blacklist and whitelist, in either
    ' case we don't need to process the e-mail address deeper if it's already on any of these lists.
    Private Shared Sub valid_Verifying(sender As Object, e As VerifyingEventArgs)
        Try
            ' See valid_Verified for explanations.
            Dim id As Integer = CInt(e.DataReaderRowValues(0))

            Dim idStr As String = id.ToString()

            Console.WriteLine(String.Format("{0}: {1} is being checked against blacklist.", idStr, e.Email))

            If e.Email.EndsWith("@domain.com") Then
                ' Exclude it from address checking by other methods, and forget it.
                e.VerifyIt = False
                Console.WriteLine(String.Format("{0}: {1} removed due to blacklist hit.", idStr, e.Email))
            End If

            If e.Email.EndsWith("@server.com") Then
                ' Exclude it from address checking by other methods, and forget it.
                e.VerifyIt = False
                Console.WriteLine(String.Format("{0}: {1} does not checking as it's on blacklist.", idStr, _
                    e.Email))
            End If

            If e.VerifyIt Then
                Console.WriteLine(String.Format("{0}: {1} survived blacklist check and not on whitelist.", _
                    idStr, e.Email))
            Else
                Console.WriteLine(String.Format("{0}: {1} skipped from further verification.", idStr, e.Email))
            End If
        Catch ex As Exception
            ' At least for debug purposes, it makes sense to catch all exceptions in
            ' event handlers as uncaught exceptions here don't cause the app to crash.
            ' Without this try/catch, it could be quite hard to understand what went wrong
            ' as you'd see no indication of a problem, the event handler would silently
            ' die in the middle but the app itself would continue.
            Console.WriteLine(ex.ToString())
        End Try

        If Not EnableMultiThreading Then
            ' See valid_Verified for explanations.
            Console.WriteLine()
        End If
    End Sub

    ' All those e-mail addresses which passed Verifying event handler then get validated,
    ' and the validation results (which can be both successful or negative) will be delivered
    ' to the application through Verified event handler.
    Private Shared Sub valid_Verified(sender As Object, e As VerifiedEventArgs)
        Try
            Dim id As Integer

            If EnableMultiThreading Then
                ' Demonstrate taking 'id' field. Unlike DataTable, IDataReader does not always permit
                ' access to a data row for more than once (which happens when MailBee reads data from it).
                ' Luckily, MailBee saves the data row it has read, for later use. That's how you can use it.
                id = CInt(e.DataReaderRowValues(0))

                ' Or, if we didn't know that 'id' is column #0, we could find it by name:
                id = CInt(e.DataReaderRowValues(Array.IndexOf(e.DataReaderColumnNames, "id")))
            Else
                ' Who said that it's not possible to read from any IDataReader any number of times? Actually,
                ' SqlDataReader allows us to read a current row as many times as we want. The only issue is
                ' that when the app is multi-threaded, another thread may already advance the reader to the
                ' next position and we won't have right data here. But when there is only one thread using
                ' the data reader, it's not a problem to read directly from it.
                '
                ' Note that it's always safe to use reading from DataReaderRowValues. Just in case if for
                ' some reason your app is single-threaded and for a very special reason you need to access
                ' IDataReader directly, you now know how to do it.
                id = CInt(_dataReader.GetValue(0))

                ' Or by name.
                id = CInt(_dataReader.GetValue(_dataReader.GetOrdinal("id")))
            End If

            Dim idStr As String = id.ToString()

            ' That's where we display the determined validation level at which the process failed, or OK.
            Console.WriteLine(String.Format("{0}: email={1}, result={2}", idStr, e.Email, e.Result.ToString()))

            If e.Reason IsNot Nothing Then
                Console.WriteLine(String.Format("{0}: Reason is: {1}", idStr, e.Reason.Message))
            End If
        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        End Try

        If Not EnableMultiThreading Then
            ' Adding empty lines for clarity at the end of an event handler (to visually separate
            ' processing of individual e-mail addresses) makes sense only in single-threaded mode.
            ' When multi-threading is on, output from different thread mixes and makes inserting
            ' empty lines useless.
            Console.WriteLine()
        End If
    End Sub

    Shared Sub Main(args As String())
        Dim valid As New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to events.
        AddHandler valid.Verifying, New VerifyingEventHandler(AddressOf valid_Verifying)
        AddHandler valid.Verified, New VerifiedEventHandler(AddressOf valid_Verified)

        If EnableMultiThreading Then
            valid.MaxThreadCount = -1
        End If

        Try
            OpenDataReader()

            ' Run the verification in multi-threaded or single-threaded mode
            ' (adjust EnableMultiThreading const to change the mode).
            valid.Verify(_dataReader, EmailColumn)
        Finally
            FreeDataReader()
        End Try
    End Sub
End Class
See Also

Reference

EmailAddressValidator Class
Verify Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.VerifyAsync Method

EmailAddressValidatorVerifyAsync Method
Overload List
 | Name | Description
Public method | VerifyAsync(String) | async/await version of Verify(String).
Public method | VerifyAsync(String) | async/await version of Verify(String).
Public method | VerifyAsync(DataTable, String) | async/await version of Verify(DataTable, String).
Public method | VerifyAsync(IDataReader, String) | async/await version of Verify(IDataReader, String).
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.VerifyAsync Method (String)

EmailAddressValidatorVerifyAsync Method (String)
async/await version of Verify(String).

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<AddressValidationLevel> VerifyAsync(
    string email
)
Public Function VerifyAsync (
    email As String
) As Task(Of AddressValidationLevel)

Parameters

email
Type: SystemString
The e-mail address to check. Must be somewhat like "user@domain.com".

Return Value

Type: Task AddressValidationLevel
A task that represents the asynchronous operation. The value of TResult parameter is OK if the validation succeeded, or the particular validation level at which the verification failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic) or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
See Also

Reference

EmailAddressValidator Class
VerifyAsync Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.VerifyAsync Method (String[])

EmailAddressValidatorVerifyAsync Method (String)
async/await version of Verify(String).

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task VerifyAsync(
    string[] emails
)
Public Function VerifyAsync (
    emails As String()
) As Task

Parameters

emails
Type: SystemString
The array containing the e-mail addresses to check for syntax and, optionally, for existence.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails is a null reference (Nothing in Visual Basic) or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
See Also

Reference

EmailAddressValidator Class
VerifyAsync Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.VerifyAsync Method (DataTable, String)

EmailAddressValidatorVerifyAsync Method (DataTable, String)
async/await version of Verify(DataTable, String).

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task VerifyAsync(
    DataTable emails,
    string columnName
)
Public Function VerifyAsync (
    emails As DataTable,
    columnName As String
) As Task

Parameters

emails
Type: System.DataDataTable
The data table, in columnName column containing the e-mail addresses to check for syntax and, optionally, for existence.
columnName
Type: SystemString
The name of column in the given data table, containing the e-mail addresses.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails or columnName is a null reference (Nothing in Visual Basic), columnName is an empty string, or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
See Also

Reference

EmailAddressValidator Class
VerifyAsync Overload
MailBee.AddressCheck Namespace


EmailAddressValidator.VerifyAsync Method (IDataReader, String)

EmailAddressValidatorVerifyAsync Method (IDataReader, String)
async/await version of Verify(IDataReader, String).

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task VerifyAsync(
    IDataReader emails,
    string columnName
)
Public Function VerifyAsync (
    emails As IDataReader,
    columnName As String
) As Task

Parameters

emails
Type: System.DataIDataReader
The data reader, in columnName column containing the e-mail addresses to check for syntax and, optionally, for existence.
columnName
Type: SystemString
The name of column in the given data reader, containing the e-mail addresses.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emails or columnName is a null reference (Nothing in Visual Basic), columnName is an empty string, or DnsServers collection is empty.
MailBeeUserAbortException | The user code has aborted the component with Abort method.
See Also

Reference

EmailAddressValidator Class
VerifyAsync Overload
MailBee.AddressCheck Namespace


EmailAddressValidator Properties

EmailAddressValidator Properties

The EmailAddressValidator type exposes the following members.

Properties
 | Name | Description
Public property | DnsServers | Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.
Public property | HelloDomain | Gets or sets the domain string to use as an argument of HELO or EHLO commands when making test connections to SMTP MX servers.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | LocalEndPoint | Gets or sets the local end point which will be used when connecting to SMTP MX servers.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MailFrom | Gets or sets the string to be used as sender when making test connections to SMTP MX servers.
Public property | MaxThreadCount | Gets or sets the maximum number of threads MailBee may create during bulk verification of e-mail addresses. operations.
Public property | Pipelining | Gets or sets whether to use commands pipelining if it's supported by the SMTP MX server.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RegexPattern | Gets or sets the regular expression to check syntax of e-mail addresses.
Public property | Site | Gets or sets the object to be used as a site for the component.
Public property | SmtpTimeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the SMTP MX server.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | ValidationLevel | Gets or sets the level of deepness of e-mail address verification.
Public property | Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.DnsServers Property

EmailAddressValidatorDnsServers Property
Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServerCollection DnsServers { get; }
Public ReadOnly Property DnsServers As DnsServerCollection
    Get

Property Value

Type: DnsServerCollection
The DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.
Remarks

All e-mail validation levels but RegexCheck utilize DNS MX lookup and thus need some DNS servers (at least one) to operate.

MailBee can auto-detect which DNS servers are available in the system. The developer can use Autodetect method to retrieve DNS settings from OS or from the config file.

If multiple DNS servers specified, MailBee will distribute load between the available DNS servers to improve performance. However, if some servers have lower Priority than others, they will not be tried unless primary servers fail.

See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace
MailBee.DnsMXDnsServer


EmailAddressValidator.HelloDomain Property

EmailAddressValidatorHelloDomain Property
Gets or sets the domain string to use as an argument of HELO or EHLO commands when making test connections to SMTP MX servers.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HelloDomain { get; set; }
Public Property HelloDomain As String
    Get
    Set

Property Value

Type: String
The EHLO/HELO argument which should be the public host name of the machine making connection to the SMTP MX server, or an empty string which tells MailBee to use the local IP address or the host name of that machine. The default value is an empty string.
Remarks
This property is only used if ValidationLevel is SmtpConnection or SendAttempt.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.IsAborted Property

EmailAddressValidatorIsAborted Property
Indicates whether Abort method has been called for the component.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsAborted { get; }
Public ReadOnly Property IsAborted As Boolean
    Get

Property Value

Type: Boolean
true if Abort method has already been called; otherwise, false. The default value is false.
Remarks

In aborted state, the component does not raise any events, and most methods, if called, will immediately return an error or throw an exception.

See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.IsBusy Property

EmailAddressValidatorIsBusy Property
Indicates whether the component is performing a lengthy operation.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBusy { get; }
Public ReadOnly Property IsBusy As Boolean
    Get

Property Value

Type: Boolean
A bool value indicating whether the component is busy because it's doing some work.
Remarks
When the component is busy, it's not possible to start another lengthy operation. For instance, if the component connects to the server or transfers data over the network, no other network operation can be started at this time. Any attempt to do so will result in MailBeeInvalidStateException.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.LocalEndPoint Property

EmailAddressValidatorLocalEndPoint Property
Gets or sets the local end point which will be used when connecting to SMTP MX servers.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EndPoint LocalEndPoint { get; set; }
Public Property LocalEndPoint As EndPoint
    Get
    Set

Property Value

Type: EndPoint
A reference to the local end point to be used when connecting to SMTP MX servers, or a null reference (Nothing in Visual Basic) if the local end point should be assigned automatically. The default value is a null reference.
Remarks
If the computer running MailBee has multiple IP addresses assigned (for instance, it has several network adapters installed), you can set this property to the IP address and port which should be used for outbound connections. See Bind(EndPoint) and LocalEndPoint topics for more information.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Log Property

EmailAddressValidatorLog Property
Gets the object used for logging MailBee activities into a file or memory buffer.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Logger Log { get; }
Public ReadOnly Property Log As Logger
    Get

Property Value

Type: Logger
A reference to the object used for logging MailBee activities into a file or memory buffer.
Remarks
This property is never a null reference (Nothing in Visual Basic) even if logging is not used.
Examples
This sample sets file logging on and sets the filename of the log file. It also configures the format of the log file to include the threading info. It's helpful in multi-threaded mode of bulk verification of e-mail addresses as it makes it possible to track individual verification sequences.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.AddressCheck;

// The actual code (put it into a method of your class)

EmailAddressValidator valid = new EmailAddressValidator();
valid.Log.Enabled = true;
valid.Log.Filename = @"C:\Temp\log.txt";
valid.Log.Format = LogFormatOptions.AddContextInfo;
valid.DnsServers.Autodetect();
Console.WriteLine(valid.Verify("jdoe@company.com").ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.AddressCheck

' The actual code (put it into a method of your class)

Dim valid = New EmailAddressValidator
valid.Log.Enabled = True
valid.Log.Filename = "C:\Temp\log.txt"
valid.Log.Format = LogFormatOptions.AddContextInfo
valid.DnsServers.Autodetect()
Console.WriteLine(valid.Verify("jdoe@company.com").ToString())
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.MailFrom Property

EmailAddressValidatorMailFrom Property
Gets or sets the string to be used as sender when making test connections to SMTP MX servers.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MailFrom { get; set; }
Public Property MailFrom As String
    Get
    Set

Property Value

Type: String
The string MailBee will use as MAIL FROM command argument. The default value is "user@domain.com".
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
This property is only used if ValidationLevel is SendAttempt.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.MaxThreadCount Property

EmailAddressValidatorMaxThreadCount Property
Gets or sets the maximum number of threads MailBee may create during bulk verification of e-mail addresses. operations.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxThreadCount { get; set; }
Public Property MaxThreadCount As Integer
    Get
    Set

Property Value

Type: Int32
An integer value specifying the maximum number of threads MailBee may create during e-mail address verification operations, or -1 which specifies the number of threads is not limited. The default value is 1 (i.e. multi-threading is off).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is zero.
Remarks
Multi-threading greatly increases performance of mass checking of e-mail addresses. The maximum thread count MailBee can utilize is 60.
Note Note
Visual Studio 2010 and earlier may hang if you're running a heavily multi-threaded application under the debugger for a long time. Consider upgrading to Visual Studio 2012 or higher if this happens often. Alternatively, decrease the number of threads when debugging.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Pipelining Property

EmailAddressValidatorPipelining Property
Gets or sets whether to use commands pipelining if it's supported by the SMTP MX server.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Pipelining { get; set; }
Public Property Pipelining As Boolean
    Get
    Set

Property Value

Type: Boolean
A Boolean value which specifies whether to join SMTP commands in batches if the server supports PIPELINING extension. The default value is Pipelining.
Remarks
ESMTP PIPELINING extension may provide a slight performance benefit as both the sender (MAIL FROM command) and recipient (RCPT TO) are submitted within the same data chunk (one round-trip to the server instead of two). If the server does not support pipelining, this value is ignored.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.RaiseEvents Property

EmailAddressValidatorRaiseEvents Property
Gets or sets whether the component will raise any events.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEvents { get; set; }
Public Property RaiseEvents As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will raise any events. The default value is true.
Remarks

If this propery is false, OnEventName methods will also not be called. Also, you'll be unable to check verification statuses of e-mail addresses in the bulk as Verified event will not be called. Setting RaiseEvents to false can make sense only for debugging purposes.

If you get lockups when enabling events in WinForms apps, the message loop of your application may be blocked. If you cannot unblock it for some reason, consider inheriting EmailAddressValidator class and overriding OnVerified(VerifiedEventArgs) method.

See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.RegexPattern Property

EmailAddressValidatorRegexPattern Property
Gets or sets the regular expression to check syntax of e-mail addresses.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RegexPattern { get; set; }
Public Property RegexPattern As String
    Get
    Set

Property Value

Type: String
The string which represents the regular expression. The default value is "^(([\w-]+['\.])+[\w-]+|([\w-]+))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z0-9]+[\w-]*\.)+[a-zA-Z]{2,9})$".
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
This property is used in all modes of e-mail address verification (because RegexCheck is the minimum level of verification, and all other levels include it as well).
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Site Property

EmailAddressValidatorSite Property
Gets or sets the object to be used as a site for the component.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual ISite Site { get; set; }
Public Overridable Property Site As ISite
    Get
    Set

Property Value

Type: ISite
A reference to the object to be used as a site for the component. The default value is a null reference (Nothing in Visual Basic).

Implements

IComponentSite
Remarks
The developer does not need to set this property. It's used by RAD tools such as form designers.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.SmtpTimeout Property

EmailAddressValidatorSmtpTimeout Property
Gets or sets the amount of time (in milliseconds) the component will wait for a response from the SMTP MX server.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int SmtpTimeout { get; set; }
Public Property SmtpTimeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error. The default value is DefaultTimeout.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
If you need to adjust timeouts of DNS MX lookup operations as well, set UdpTimeout value for every DNS server in DnsServers collection.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.SynchronizingObject Property

EmailAddressValidatorSynchronizingObject Property
Gets or sets the object used to marshal the calls of the event handlers.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ISynchronizeInvoke SynchronizingObject { get; set; }
Public Property SynchronizingObject As ISynchronizeInvoke
    Get
    Set

Property Value

Type: ISynchronizeInvoke
A reference to the object on whose thread the events should be raised. The default value is a null reference (Nothing in Visual Basic) which tells MailBee to determine the appropriate marshalling object automatically.
Remarks
Usually, you do not need to set this property because MailBee can automatically marshal events to proper threads.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.TrialDaysLeft Property

EmailAddressValidatorTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value which contains the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.ValidationLevel Property

EmailAddressValidatorValidationLevel Property
Gets or sets the level of deepness of e-mail address verification.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AddressValidationLevel ValidationLevel { get; set; }
Public Property ValidationLevel As AddressValidationLevel
    Get
    Set

Property Value

Type: AddressValidationLevel
The value which tells MailBee which checks to do in order to validate an e-mail address. The default value is SendAttempt (maximum level of verification).
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Version Property

EmailAddressValidatorVersion Property
Gets the version of the MailBee assembly.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator Events

EmailAddressValidator Events

The EmailAddressValidator type exposes the following members.

Events
 | Name | Description
 | DataReceived | Occurs when data is received from the network.
 | DataSent | Occurs when data is sent to the network.
Public event | Disposed | Occurs after the component was disposed.
Public event | ErrorOccurred | Occurs when MailBeeException is thrown internally.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if EmailAddressValidator.Log.MemoryLog is true).
 | Verified | Occurs once an e-mail addresses in a bulk series has been verified.
 | Verifying | Occurs when an e-mail address in a bulk series is about to be verified.
Top
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.DataReceived Event

EmailAddressValidatorDataReceived Event
Occurs when data is received from the network.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataReceived
Public Event DataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

This event is raised when the component receives a response from an SMTP server, or when a DNS response containing MX lookup results is returned. The developer can use Protocol property to determine the protocol of the data just sent.

Note Note
This event is also raised when zero-length data is received from the server. When a server sends zero-length data portion, it means the connection was closed.
Examples
DataReceived sample shows how to use this event for Smtp object. For EmailAddressValidator, usage pattern is the same.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.DataSent Event

EmailAddressValidatorDataSent Event
Occurs when data is sent to the network.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataSent
Public Event DataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks
This event is raised when the component sends a request to an SMTP server or DNS server. The developer can use Protocol property to determine the protocol of the data just sent.
Examples
DataSent sample shows how to use this event for Smtp object. For EmailAddressValidator, usage pattern is the same.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Disposed Event

EmailAddressValidatorDisposed Event
Occurs after the component was disposed.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event EventHandler Disposed
Public Event Disposed As EventHandler

Value

Type: SystemEventHandler

Implements

IComponentDisposed
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.ErrorOccurred Event

EmailAddressValidatorErrorOccurred Event
Occurs when MailBeeException is thrown internally.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ErrorEventHandler ErrorOccurred
Public Event ErrorOccurred As ErrorEventHandler

Value

Type: MailBeeErrorEventHandler
Remarks

When MailBee encounters any error, it throws the MailBeeException. However, in most cases MailBee itself traps this exception. For instance, if connecting to a certain SMTP server or making DNS MX lookup fails for a certain domain, MailBeeException is thrown and then trapped by MailBee itself, but no exception will be thrown to the application code. Instead, MailBee understands that the given e-mail address is invalid, and continues. Such errors are called warnings.

ErrorOccurred event allows the developer to track both warnings and critical errors because it's raised for a particular exception even if MailBee will trap this exception and do not pass it to the application code.

Note that not any occurrence of this event indicates that some e-mail address was considered invalid. For instance, if test SMTP connection to a primary SMTP MX server of some e-mail domain failed, this will raise ErrorOccurred event. But if this domain has secondary SMTP MX, MailBee will then try it too, and it the connection succeeds, the e-mail address will be considered OK.

Thus, ErrorOccurred event is mainly intended for informational and debugging purposes.

See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.LogNewEntry Event

EmailAddressValidatorLogNewEntry Event
Occurs when an entry is written into the log file (or into the memory buffer if EmailAddressValidator.Log.MemoryLog is true).

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LogNewEntryEventHandler LogNewEntry
Public Event LogNewEntry As LogNewEntryEventHandler

Value

Type: MailBeeLogNewEntryEventHandler
Remarks

This event is raised only if logging is turned on (Enabled is true).

MailBee raises this event BEFORE adding the entry into the the log. Since many properties of NewEntry object are editable, the developer can change the data MailBee will put into the log or even cancel logging the current entry at all. This may be useful the developer wishes to log only those entires which meet certain criteria.

Note Note
Entries added by the developer (through WriteLine(String) method call) do not cause this event to be raised. Thus, it's safe to add user-defined log entries even in the LogNewEntry event handler itself. This does not cause endless recursion which would otherwise occur if WriteLine(String) method called in LogNewEntry event handler raised this event again.
Examples
LogNewEntry sample shows how to use this event for Smtp object. For EmailAddressValidator, usage pattern is the same.
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Verified Event

EmailAddressValidatorVerified Event
Occurs once an e-mail addresses in a bulk series has been verified.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event VerifiedEventHandler Verified
Public Event Verified As VerifiedEventHandler

Value

Type: MailBee.AddressCheckVerifiedEventHandler
Remarks
You must subscribe to this event to check verification statuses of e-mail addresses in a bulk series. For addresses which have been skipped from verification in Verifying event, this event is not raised.
Note Note
This event is never raised by Verify(String) overload which processes a single address only (rather than a bulk).
Note Note
This event is not available for .NET Core and UWP.
Examples
This sample verifies a bulk of 3 addresses, using Verified event. Data source is DataTable. To see how to use this event in case of IDataReader, see Verify(IDataReader, String) sample.
C#
VB
Copy
using System;
using MailBee;
using MailBee.AddressCheck;
class Program
{
    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        Console.WriteLine("*** Verified ***");
        Console.WriteLine("Email: " + e.Email);
        Console.WriteLine("Result: " + e.Result.ToString());
        if (e.Reason != null)
        {
            Console.WriteLine("Reason: " + e.Reason.Message);
        }
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to event.
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // Populate an array with some e-mails. You can also use DataTable as a source.
        string[] emails = new string[] { "jdoe@company.com", "bob@example.com", "alice@domain.com" };

        // Run the verification in single-threaded mode.
        valid.Verify(emails);
    }
}
Imports System
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Console.WriteLine("*** Verified ***")
        Console.WriteLine(("Email: " & e.Email))
        Console.WriteLine(("Result: " & e.Result.ToString))
        If (Not (e.Reason) Is Nothing) Then
            Console.WriteLine(("Reason: " & e.Reason.Message))
        End If
        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim valid As EmailAddressValidator = New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to event.
        AddHandler valid.Verified, AddressOf valid_Verified

        ' Populate an array with some e-mails. You can also use DataTable as a source.
        Dim emails() As String = New String() {"jdoe@company.com", "bob@example.com", "alice@domain.com"}

        ' Run the verification in single-threaded mode.
        valid.Verify(emails)
    End Sub
End Class
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


EmailAddressValidator.Verifying Event

EmailAddressValidatorVerifying Event
Occurs when an e-mail address in a bulk series is about to be verified.

Namespace: MailBee.AddressCheck
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event VerifyingEventHandler Verifying
Public Event Verifying As VerifyingEventHandler

Value

Type: MailBee.AddressCheckVerifyingEventHandler
Remarks

You can use this event to filter any e-mail addresses from the bulk of addresses to be verified, such as to implement a whitelist or blacklist. Set VerifyIt to skip the particular address from verification.

Note Note
This event is never raised by Verify(String) overload which processes a single address only (rather than a bulk).
Note Note
This event is not available for .NET Core and UWP.
Examples

This sample demonstrates how to implement blacklist and whitelist. Data source is DataTable. To see how to use this event in case of IDataReader, see Verify(IDataReader, String) sample.

Note Note
For clarity, this sample marks e-mail addresses as bad or good based on a single verification attempt. In real apps, you should use multi-pass approach. See Getting started with Address Validator guide (Examining the results section) for a more accurate and advanced sample.
C#
VB
Copy
using System;
using System.Data;
using MailBee;
using MailBee.AddressCheck;

class Program
{
    const string EmailColumn = "email";
    const string StatusColumn = "good";

    // In real apps, you'll get this data table from your database.
    // In the sample, we build it directly in the code.
    private static DataTable GetDataTable()
    {
        DataTable workTable = new DataTable();
        workTable.Columns.Add(EmailColumn, typeof(string));
        workTable.Columns.Add(StatusColumn, typeof(bool));

        // Populate the data table with several addresses. Some of them
        // (jdoe@good.com, user@local-domain, and alice@bad.com) will later
        // be determined as belonging to whitelist or blacklist.
        string[] emails = new string[] { "jdoe@good.com", "no.dot.in@domain",
            "bob@example.com", "user@local-domain", "alice@bad.com" };
        foreach (string email in emails)
        {
            DataRow row = workTable.NewRow();
            row[EmailColumn] = email;
            row[StatusColumn] = false;
            workTable.Rows.Add(row);
        }

        return workTable;
    }

    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified. Those addresses for which we set VerifyIt
    // to 'false' will be skipped from further verification and Verified
    // event won't occur for them.
    private static void valid_Verifying(object sender, VerifyingEventArgs e)
    {
        try
        {
            Console.WriteLine("*** Verifying ***");
            Console.WriteLine("Email: " + e.Email);

            if (e.Email.EndsWith("@bad.com"))
            {
                // Blacklisting, mark the status of this address as bad
                // and exclude it from address checking by other methods.
                e.VerifyIt = false;
                e.Row[StatusColumn] = false;
            }
            // Note "@local-domain" address. If we didn't exclude it, it would
            // surely have been rejected by syntax check as local domains without
            // dot in their names are not allowed by default (unless you adjust
            // EmailAddressValidator.RegexPattern value to allow such syntax).
            else if (e.Email.EndsWith("@good.com") ||
                e.Email.EndsWith("@local-domain"))
            {
                // Whitelisting, mark the status of this address as good
                // and exclude it from address checking by other methods.
                e.VerifyIt = false;
                e.Row[StatusColumn] = true;
            }

            // If there was whitelist or blacklist hit and we changed the status
            // of the address, we should apply the changes to the database.
            if (!e.VerifyIt)
            {
                Console.WriteLine(
                    string.Format("{0} status detected as {1} without verification.",
                    e.Email, (bool)e.Row[StatusColumn] ? "good" : "bad"));
                // In real app, you may need to do database Commit or Update here.
            }
            else
            {
                Console.WriteLine(
                    string.Format("{0} is neither on blacklist nor on whitelist.", e.Email));
            }
        }
        catch (Exception ex)
        {
            // At least for debug purposes, it makes sense to catch all exceptions in
            // event handlers as uncaught exceptions here don't cause the app to crash.
            Console.WriteLine(ex.ToString());
        }

        Console.WriteLine();
    }

    // This method will be executed for each e-mail address in the bulk,
    // whenever it gets verified, with either positive or negative result.
    private static void valid_Verified(object sender, VerifiedEventArgs e)
    {
        try
        {
            Console.WriteLine("*** Verified ***");
            Console.WriteLine("Email: " + e.Email);
            Console.WriteLine("Result: " + e.Result.ToString());
            if (e.Reason != null)
            {
                Console.WriteLine("Reason: " + e.Reason.Message);
            }
            bool isAddressOK = (e.Result == AddressValidationLevel.OK);
            if ((bool)e.Row[StatusColumn] != isAddressOK)
            {
                // If the new status differs from the previous one, update the database.
                // In real apps, you may also need to do Commit or Update.
                e.Row[StatusColumn] = isAddressOK;
            }

            // Instead of e.Row[StatusColumn] it's better to use isAddressOK below, we use
            // e.Row[StatusColumn] just to keep the code pretty similar to valid_Verifying.
            Console.WriteLine(string.Format("{0} status detected as {1} after verification.",
                e.Email, (bool)e.Row[StatusColumn] ? "good" : "bad"));
        }
        catch (Exception ex)
        {
            // At least for debug purposes, it makes sense to catch all exceptions in
            // event handlers as uncaught exceptions here don't cause the app to crash.
            Console.WriteLine(ex.ToString());
        }

        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        EmailAddressValidator valid = new EmailAddressValidator("MN110-0123456789ABCDEF-0123");

        // To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect();

        // Logging into a file is not required for the component to work
        // but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = true;
        valid.Log.Filename = @"C:\Temp\log.txt";
        valid.Log.Clear();

        // Subscribe to events.
        valid.Verifying += new VerifyingEventHandler(valid_Verifying);
        valid.Verified += new VerifiedEventHandler(valid_Verified);

        // Run the verification in single-threaded mode (for clarity of console output).
        valid.Verify(GetDataTable(), EmailColumn);
    }
}
Imports System.Data
Imports MailBee
Imports MailBee.AddressCheck

Class Program
    Const EmailColumn As String = "email"
    Const StatusColumn As String = "good"

    ' In real apps, you'll get this data table from your database.
    ' In the sample, we build it directly in the code.
    Private Shared Function GetDataTable() As DataTable
        Dim workTable As New DataTable()
        workTable.Columns.Add(EmailColumn, GetType(String))
        workTable.Columns.Add(StatusColumn, GetType(Boolean))

        ' Populate the data table with several addresses. Some of them
        ' (jdoe@good.com, user@local-domain, and alice@bad.com) will later
        ' be determined as belonging to whitelist or blacklist.
        Dim emails As String() = New String() {"jdoe@good.com", "no.dot.in@domain", _
         "bob@example.com", "user@local-domain", "alice@bad.com"}
        For Each email As String In emails
            Dim row As DataRow = workTable.NewRow()
            row(EmailColumn) = email
            row(StatusColumn) = False
            workTable.Rows.Add(row)
        Next

        Return workTable
    End Function

    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified. Those addresses for which we set VerifyIt
    ' to 'False' will be skipped from further verification and Verified
    ' event won't occur for them.
    Private Shared Sub valid_Verifying(ByVal sender As Object, ByVal e As VerifyingEventArgs)
        Try
            Console.WriteLine("*** Verifying ***")
            Console.WriteLine("Email: " & e.Email)

            If e.Email.EndsWith("@bad.com") Then
                ' Blacklisting, mark the status of this address as bad
                ' and exclude it from address checking by other methods.
                e.VerifyIt = False
                e.Row(StatusColumn) = False

                ' Note "@local-domain" address. If we didn't exclude it, it would
                ' surely have been rejected by syntax check as local domains without
                ' dot in their names are not allowed by default (unless you adjust
                ' EmailAddressValidator.RegexPattern value to allow such syntax).
            ElseIf e.Email.EndsWith("@good.com") OrElse e.Email.EndsWith("@local-domain") Then
                ' Whitelisting, mark the status of this address as good
                ' and exclude it from address checking by other methods.
                e.VerifyIt = False
                e.Row(StatusColumn) = True
            End If

            ' If there was whitelist or blacklist hit and we changed the status
            ' of the address, we should apply the changes to the database.
            If Not e.VerifyIt Then
                ' In real app, you may need to do database Commit or Update here.
                Console.WriteLine( _
                 String.Format("{0} status detected as {1} without verification.", _
                 e.Email, If(CBool(e.Row(StatusColumn)), "good", "bad")))
            Else
                Console.WriteLine( _
                 String.Format("{0} is neither on blacklist nor on whitelist.", e.Email))
            End If
        Catch ex As Exception
            ' At least for debug purposes, it makes sense to catch all exceptions in
            ' event handlers as uncaught exceptions here don't cause the app to crash.
            Console.WriteLine(ex.ToString())
        End Try

        Console.WriteLine()
    End Sub

    ' This method will be executed for each e-mail address in the bulk,
    ' whenever it gets verified, with either positive or negative result.
    Private Shared Sub valid_Verified(ByVal sender As Object, ByVal e As VerifiedEventArgs)
        Try
            Console.WriteLine("*** Verified ***")
            Console.WriteLine("Email: " & e.Email)
            Console.WriteLine("Result: " & e.Result.ToString())
            If Not (e.Reason Is Nothing) Then
                Console.WriteLine("Reason: " & e.Reason.Message)
            End If
            Dim isAddressOK As Boolean = (e.Result = AddressValidationLevel.OK)
            If CBool(e.Row(StatusColumn)) <> isAddressOK Then
                ' If the new status differs from the previous one, update the database.
                ' In real apps, you may also need to do Commit or Update.
                e.Row(StatusColumn) = isAddressOK
            End If

            ' Instead of e.Row[StatusColumn] it's better to use isAddressOK below, we use
            ' e.Row[StatusColumn] just to keep the code pretty similar to valid_Verifying.
            Console.WriteLine(String.Format("{0} status detected as {1} after verification.", _
             e.Email, If(CBool(e.Row(StatusColumn)), "good", "bad")))
        Catch ex As Exception
            ' At least for debug purposes, it makes sense to catch all exceptions in
            ' event handlers as uncaught exceptions here don't cause the app to crash.
            Console.WriteLine(ex.ToString())
        End Try

        Console.WriteLine()
    End Sub

    Shared Sub Main(ByVal args As String())
        Dim valid As New EmailAddressValidator("MN110-0123456789ABCDEF-0123")

        ' To perform DNS MX lookup queries, we need some DNS servers for that.
        valid.DnsServers.Autodetect()

        ' Logging into a file is not required for the component to work
        ' but helpful for debugging and understanding things under the hood.
        valid.Log.Enabled = True
        valid.Log.Filename = "C:\Temp\log.txt"
        valid.Log.Clear()

        ' Subscribe to events.
        AddHandler valid.Verifying, AddressOf valid_Verifying
        AddHandler valid.Verified, AddressOf valid_Verified

        ' Run the verification in single-threaded mode (for clarity of console output).
        valid.Verify(GetDataTable(), EmailColumn)
    End Sub
End Class
See Also

Reference

EmailAddressValidator Class
MailBee.AddressCheck Namespace


MailBee.AntiSpam Namespace

MailBee.AntiSpam Namespace

MailBee.AntiSpam namespace provides BayesFilter class which allows applications to detect spam e-mails with self-learning Bayesian filter, and RblFilter class which implements DNS RBL functionality to check if specified IP addresses designate spam sources.

For DomainKeys and DKIM functionality (which is often used as a sort of anti-spam check), refer to MailBee.Security.DomainKeys class.

For reverse DNS functionality (which is also used as a sort of anti-spam check), refer to MailBee.SmtpMail.Smtp.GetPtrData method.

In UWP apps, use async methods. This platform has very limited sync I/O support.

Classes
 | Class | Description
 | BayesFilter | Provides properties and methods for checking e-mails messages for spam probability and learning the filter from proven spam and non-spam messages.
 | RblFilter | Provides methods to filter spam by checking e-mails and IP addresses against DNS RBL databases.
 | RblStatus | Represents a status of an IP address in a DNS RBL database.
Public class | RblStatusCollection | Provides properties and methods for examining the collection of RblStatus objects.
Delegates
 | Delegate | Description
Public delegate | LockedDatabaseDelegate | Defines the signature (the parameters and the return value) of the application-defined method to be called when the Bayesian spam or non-spam database file appears to be locked.
Enumerations
 | Enumeration | Description
Public enumeration | BayesAlgorithm | Defines the available values for BayesFilter.Algorithm property to specify the algorithm which should be used to calculate spam score of e-mail messages.


BayesAlgorithm Enumeration

BayesAlgorithm Enumeration
Defines the available values for BayesFilter.Algorithm property to specify the algorithm which should be used to calculate spam score of e-mail messages.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum BayesAlgorithm
Public Enumeration BayesAlgorithm
Members
Member name | Value | Description
GrahamAlgorithm | 1 | Use Graham algorithm (faster).
ChiSquareAlgorithm | 2 | Use Chi-Square algorithm (more accurate).
See Also

Reference

MailBee.AntiSpam Namespace


BayesFilter Class

BayesFilter Class
Provides properties and methods for checking e-mails messages for spam probability and learning the filter from proven spam and non-spam messages.
Inheritance Hierarchy
SystemObject
MailBee.AntiSpamBayesFilter

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class BayesFilter
Public Class BayesFilter

The BayesFilter type exposes the following members.

Constructors
 | Name | Description
Public method | BayesFilter | Creates an instance of BayesFilter class.
Public method | BayesFilter(String) | Creates and unlocks an instance of BayesFilter class.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | LoadDatabase(Stream, Stream) | Loads Bayesian database from a stream.
 | LoadDatabase(String, String) | Loads Bayesian database from disk.
Public method | LoadDatabaseAsync(Stream, Stream) | async/await version of LoadDatabase(Stream, Stream).
Public method | LoadDatabaseAsync(String, String) | async/await version of LoadDatabase(String, String).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | SaveDatabase(Stream, Stream) | Saves the Bayesian database to stream.
 | SaveDatabase(String, String) | Saves the Bayesian database to disk.
Public method | SaveDatabase(Stream, Stream, Int32, Boolean) | Compacts the database by removing non-significant data and saves the database to stream.
 | SaveDatabase(String, String, Int32, Boolean) | Compacts the database by removing non-significant data and saves the database to disk.
Public method | SaveDatabaseAsync(Stream, Stream) | async/await version of SaveDatabase(Stream, Stream).
Public method | SaveDatabaseAsync(String, String) | async/await version of SaveDatabase(String, String).
Public method | SaveDatabaseAsync(Stream, Stream, Int32, Boolean) | async/await version of SaveDatabase(Stream, Stream, Int32, Boolean).
Public method | SaveDatabaseAsync(String, String, Int32, Boolean) | async/await version of SaveDatabase(String, String, Int32, Boolean).
 | ScoreMessage | Analyses the message and returns the probability of the message being spam.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | TrainFilter | Learns from the specified message as from spam or non-spam source.
Top
Properties
 | Name | Description
Public property | Algorithm | Gets or sets the algorithm to be used for scoring messages.
Public property | AutoLearning | Gets or sets if the filter should automatically learn during scoring messages on the words with the sufficient spam/non-spam weight.
Public property | AutoLearningGradeAbove | Gets or sets the minimum score the message should get so that the filter will treat it as spam and automatically learn this.
Public property | AutoLearningGradeBelow | Gets or sets the maximum score the message should get so that the filter will treat it as non-spam and automatically learn this.
 | LicenseKey | Obsolete. Assigns the license key.
Public property | OnLockedDatabase | Gets or sets the application-supplied method which will be executed if MailBee founds that spam or non-spam database file is locked when it needs to perform I/O operation with it.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
Remarks

The filter uses the existing database of spam and non-spam messages to score new messages in the range of 0-100%. 0% corresponds to absolutely non-spam message, 100% corresponds to absolutely spam message.

The key point is learning the filter: telling the filter which messages are spam or non-spam. This is called training the filter.

Initially, while the database is empty, the filter has no existing messages which to compare with the message in question.

Thus, the first task is to train the filter with several hundreds of typical spam and non-spam messages you usually get. This will increase the filter efficiency from zero to the suitable value. The training should, however, continue in the future to further improve the quality of spam recognition. The larger database is, the better spam/non-spam recognition is.

The filter will operate correctly ONLY if it was trained with a good number of spam AND non-spam messages.

You can train the filter using TrainFilter(MailMessage, Boolean) method.

To score a message (determine if it's spam or not), use ScoreMessage(MailMessage) method.

Note Note
MailBee also supports other technologies which can be used as a sort of antispam check. They include DNS RBL filter (RblFilter class), full support of DomainKeys (signing and verification of e-mails using DomainKeys signatures) and DNX MX/Reverse DNS checks (see GetMXHosts(String) and GetPtrData(String) methods).
Examples

This sample trains the Bayesian filter for spam and for non-spam messages; saves resulting database and scores sample e-mails for spam probability using this database.

It's assumed the spam and non-spam samples are .EML files located in C:\AntiSpam\Spam and C:\AntiSpam\NonSpam folders respectively. The database itself (spam.dat and nonspam.dat) will be saved in C:\AntiSpam folder.

C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        BayesFilter filter = new BayesFilter();
        MailMessage msg = new MailMessage();

        // Train Bayesian filter for spam messages.
        string[] files = Directory.GetFiles(@"C:\AntiSpam\Spam", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            filter.TrainFilter(msg, true); // Mark as spam.
        }

        // Train Bayesian filter for non-spam messages.
        files = Directory.GetFiles(@"C:\AntiSpam\NonSpam", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            filter.TrainFilter(msg, false); // Mark as non-spam.
        }

        // Save Bayesian database to disk.
        filter.SaveDatabase(@"C:\AntiSpam\spam.dat", @"C:\AntiSpam\nonspam.dat");

        // Test our emails for spam.
        files = Directory.GetFiles(@"C:\AntiSpam\Emails", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            Console.WriteLine("Spam probability is: {0}%", filter.ScoreMessage(msg));
        }
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee.Mime
Imports MailBee.AntiSpam

Module Sample
    Sub Main(ByVal args() As String)
        Dim filter As BayesFilter = New BayesFilter()
        Dim msg As MailMessage = New MailMessage()

        ' Train Bayesian filter for spam messages.
        Dim files() As String = Directory.GetFiles("C:\AntiSpam\Spam", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            filter.TrainFilter(msg, True) ' Mark as spam.
        Next

        ' Train Bayesian filter for non-spam messages.
        files = Directory.GetFiles("C:\AntiSpam\NonSpam", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            filter.TrainFilter(msg, False) ' Mark as non-spam.
        Next

        ' Save Bayesian database to disk.
        filter.SaveDatabase("C:\AntiSpam\spam.dat", "C:\AntiSpam\nonspam.dat")

        ' Test our emails for spam.
        files = Directory.GetFiles("C:\AntiSpam\Emails", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            Console.WriteLine("Spam probability is: {0}%", filter.ScoreMessage(msg))
        Next
    End Sub
End Module
See Also

Reference

MailBee.AntiSpam Namespace


BayesFilter Constructor

BayesFilter Constructor
Creates an instance of BayesFilter class.
Overload List
 | Name | Description
Public method | BayesFilter | Creates an instance of BayesFilter class.
Public method | BayesFilter(String) | Creates and unlocks an instance of BayesFilter class.
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter Constructor

BayesFilter Constructor
Creates an instance of BayesFilter class.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public BayesFilter()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET AntiSpam not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

BayesFilter Class
BayesFilter Overload
MailBee.AntiSpam Namespace


BayesFilter Constructor (String)

BayesFilter Constructor (String)
Creates and unlocks an instance of BayesFilter class.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public BayesFilter(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET AntiSpam not licensed and the supplied license key is invalid.
See Also

Reference

BayesFilter Class
BayesFilter Overload
MailBee.AntiSpam Namespace


BayesFilter Methods

BayesFilter Methods

The BayesFilter type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | LoadDatabase(Stream, Stream) | Loads Bayesian database from a stream.
 | LoadDatabase(String, String) | Loads Bayesian database from disk.
Public method | LoadDatabaseAsync(Stream, Stream) | async/await version of LoadDatabase(Stream, Stream).
Public method | LoadDatabaseAsync(String, String) | async/await version of LoadDatabase(String, String).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | SaveDatabase(Stream, Stream) | Saves the Bayesian database to stream.
 | SaveDatabase(String, String) | Saves the Bayesian database to disk.
Public method | SaveDatabase(Stream, Stream, Int32, Boolean) | Compacts the database by removing non-significant data and saves the database to stream.
 | SaveDatabase(String, String, Int32, Boolean) | Compacts the database by removing non-significant data and saves the database to disk.
Public method | SaveDatabaseAsync(Stream, Stream) | async/await version of SaveDatabase(Stream, Stream).
Public method | SaveDatabaseAsync(String, String) | async/await version of SaveDatabase(String, String).
Public method | SaveDatabaseAsync(Stream, Stream, Int32, Boolean) | async/await version of SaveDatabase(Stream, Stream, Int32, Boolean).
Public method | SaveDatabaseAsync(String, String, Int32, Boolean) | async/await version of SaveDatabase(String, String, Int32, Boolean).
 | ScoreMessage | Analyses the message and returns the probability of the message being spam.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | TrainFilter | Learns from the specified message as from spam or non-spam source.
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.LoadDatabase Method

BayesFilterLoadDatabase Method
Loads Bayesian database from file or stream.
Overload List
 | Name | Description
Public method | LoadDatabase(Stream, Stream) | Loads Bayesian database from a stream.
 | LoadDatabase(String, String) | Loads Bayesian database from disk.
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.LoadDatabase Method (Stream, Stream)

BayesFilterLoadDatabase Method (Stream, Stream)
Loads Bayesian database from a stream.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void LoadDatabase(
    Stream spamStream,
    Stream nonSpamStream
)
Public Sub LoadDatabase (
    spamStream As Stream,
    nonSpamStream As Stream
)

Parameters

spamStream
Type: System.IOStream
An input stream containing spam samples.
nonSpamStream
Type: System.IOStream
An input stream containing non-spam samples.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamStream or nonSpamStream is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
Remarks
The data format in the stream is the same that is used for files (and the method behaves identically to LoadDatabase(String, String) with the only difference that streams are used instead of files).
See Also

Reference

BayesFilter Class
LoadDatabase Overload
MailBee.AntiSpam Namespace
BayesFilterLoadDatabase(String, String)


BayesFilter.LoadDatabase Method (String, String)

BayesFilterLoadDatabase Method (String, String)
Loads Bayesian database from disk.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void LoadDatabase(
    string spamFilename,
    string nonSpamFilename
)
Public Sub LoadDatabase (
    spamFilename As String,
    nonSpamFilename As String
)

Parameters

spamFilename
Type: SystemString
The full or relative path to the file containing spam samples.
nonSpamFilename
Type: SystemString
The full or relative path to the file containing non-spam samples.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamFilename or nonSpamFilename is an empty string or a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
Remarks
If you do not already have a database of spam/non-spam samples, you should first train the filter and populate the database by calling TrainFilter(MailMessage, Boolean) method for a significant number of spam and non-spam messages. You can save the resulting database using SaveDatabase(String, String) method.
Examples
The example is available in TrainFilter(MailMessage, Boolean) topic.
See Also

Reference

BayesFilter Class
LoadDatabase Overload
MailBee.AntiSpam Namespace
BayesFilterTrainFilter(MailMessage, Boolean)
BayesFilterSaveDatabase(String, String)


BayesFilter.LoadDatabaseAsync Method

BayesFilterLoadDatabaseAsync Method
Overload List
 | Name | Description
Public method | LoadDatabaseAsync(Stream, Stream) | async/await version of LoadDatabase(Stream, Stream).
Public method | LoadDatabaseAsync(String, String) | async/await version of LoadDatabase(String, String).
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.LoadDatabaseAsync Method (Stream, Stream)

BayesFilterLoadDatabaseAsync Method (Stream, Stream)
async/await version of LoadDatabase(Stream, Stream).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task LoadDatabaseAsync(
    Stream spamStream,
    Stream nonSpamStream
)
Public Function LoadDatabaseAsync (
    spamStream As Stream,
    nonSpamStream As Stream
) As Task

Parameters

spamStream
Type: System.IOStream
An input stream containing spam samples.
nonSpamStream
Type: System.IOStream
An input stream containing non-spam samples.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamStream or nonSpamStream is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
See Also

Reference

BayesFilter Class
LoadDatabaseAsync Overload
MailBee.AntiSpam Namespace


BayesFilter.LoadDatabaseAsync Method (String, String)

BayesFilterLoadDatabaseAsync Method (String, String)
async/await version of LoadDatabase(String, String).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task LoadDatabaseAsync(
    string spamFilename,
    string nonSpamFilename
)
Public Function LoadDatabaseAsync (
    spamFilename As String,
    nonSpamFilename As String
) As Task

Parameters

spamFilename
Type: SystemString
The full or relative path to the file containing spam samples.
nonSpamFilename
Type: SystemString
The full or relative path to the file containing non-spam samples.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamFilename or nonSpamFilename is an empty string or a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
See Also

Reference

BayesFilter Class
LoadDatabaseAsync Overload
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabase Method

BayesFilterSaveDatabase Method
Saves the Bayesian database to file or stream.
Overload List
 | Name | Description
 | SaveDatabase(Stream, Stream) | Saves the Bayesian database to stream.
 | SaveDatabase(String, String) | Saves the Bayesian database to disk.
Public method | SaveDatabase(Stream, Stream, Int32, Boolean) | Compacts the database by removing non-significant data and saves the database to stream.
 | SaveDatabase(String, String, Int32, Boolean) | Compacts the database by removing non-significant data and saves the database to disk.
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabase Method (Stream, Stream)

BayesFilterSaveDatabase Method (Stream, Stream)
Saves the Bayesian database to stream.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SaveDatabase(
    Stream spamStream,
    Stream nonSpamStream
)
Public Sub SaveDatabase (
    spamStream As Stream,
    nonSpamStream As Stream
)

Parameters

spamStream
Type: System.IOStream
An output stream containing spam samples.
nonSpamStream
Type: System.IOStream
An output stream containing non-spam samples.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamStream or nonSpamStream is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
Remarks
The data format in the stream is the same that is used for files (and the method behaves identically to SaveDatabase(String, String) with the only difference that streams are used instead of files).
Examples
The example is available in TrainFilter(MailMessage, Boolean) topic.
See Also

Reference

BayesFilter Class
SaveDatabase Overload
MailBee.AntiSpam Namespace
BayesFilterSaveDatabase(String, String)


BayesFilter.SaveDatabase Method (String, String)

BayesFilterSaveDatabase Method (String, String)
Saves the Bayesian database to disk.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SaveDatabase(
    string spamFilename,
    string nonSpamFilename
)
Public Sub SaveDatabase (
    spamFilename As String,
    nonSpamFilename As String
)

Parameters

spamFilename
Type: SystemString
The full or relative path to the file containing spam samples.
nonSpamFilename
Type: SystemString
The full or relative path to the file containing non-spam samples.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamFilename or nonSpamFilename is an empty string or a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
Remarks

This method always saves the database from memory to disk even if it has not been changed since it had been loaded with LoadDatabase(String, String) method. If you want to save the database only if it had been changed, use another SaveDatabase(String, String, Int32, Boolean) overload.

If you do not have a database yet, you should not call LoadDatabase(String, String). In this case, it's assumed the default empty database is loaded. You can then train it with TrainFilter(MailMessage, Boolean) method and then save the produced database to disk.

Make sure your application has read/write access to the specified database file locations.

Examples
The example is available in TrainFilter(MailMessage, Boolean) topic.
See Also

Reference

BayesFilter Class
SaveDatabase Overload
MailBee.AntiSpam Namespace
BayesFilterLoadDatabase(String, String)


BayesFilter.SaveDatabase Method (Stream, Stream, Int32, Boolean)

BayesFilterSaveDatabase Method (Stream, Stream, Int32, Boolean)
Compacts the database by removing non-significant data and saves the database to stream.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SaveDatabase(
    Stream spamStream,
    Stream nonSpamStream,
    int threshold,
    bool saveAlways
)
Public Sub SaveDatabase (
    spamStream As Stream,
    nonSpamStream As Stream,
    threshold As Integer,
    saveAlways As Boolean
)

Parameters

spamStream
Type: System.IOStream
An output stream containing spam samples.
nonSpamStream
Type: System.IOStream
An output stream containing non-spam samples.
threshold
Type: SystemInt32
Specifies how many times (at least) the word should appear in the database to keep it from removal during compacting the database. If the word appears less times then specified, it will be considered non-significant and thus will be removed. If zero, no words will be removed from the database.
saveAlways
Type: SystemBoolean
If true, the method will save the database even if has not been modified since it had been loaded to memory; if false, the method will save it only if it has been modified.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamStream or nonSpamStream is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
Remarks
The data format in the stream is the same that is used for files (and the method behaves identically to SaveDatabase(String, String, Int32, Boolean) with the only difference that streams are used instead of files).
See Also

Reference

BayesFilter Class
SaveDatabase Overload
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabase Method (String, String, Int32, Boolean)

BayesFilterSaveDatabase Method (String, String, Int32, Boolean)
Compacts the database by removing non-significant data and saves the database to disk.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SaveDatabase(
    string spamFilename,
    string nonSpamFilename,
    int threshold,
    bool saveAlways
)
Public Sub SaveDatabase (
    spamFilename As String,
    nonSpamFilename As String,
    threshold As Integer,
    saveAlways As Boolean
)

Parameters

spamFilename
Type: SystemString
The full or relative path to the file containing spam samples.
nonSpamFilename
Type: SystemString
The full or relative path to the file containing non-spam samples.
threshold
Type: SystemInt32
Specifies how many times (at least) the word should appear in the database to keep it from removal during compacting the database. If the word appears less times then specified, it will be considered non-significant and thus will be removed. If zero, no words will be removed from the database.
saveAlways
Type: SystemBoolean
If true, the method will save the database even if has not been modified since it had been loaded to memory; if false, the method will save it only if it has been modified.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamFilename or nonSpamFilename is an empty string or a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
Remarks

Compacting the database will decrease the file size but will decrease accuracy of spam recognition as well. It makes sense for very large databases populated from many thousands of e-mails. In this case, using a value of 3-5 will significantly decrease the database size but won't have big impact on accuracy. In general, the larger database size is, the larger threshold value can be.

If you save the database to the same location where you already have it, specify saveAlways as false. If you save to a new location, specify saveAlways as true.

Make sure your application has read/write access to the specified database file locations.

Examples

This sample removes all words that appear less than 3 times from the Bayesian database.

It's assumed the spam and non-spam samples are .EML files located in C:\AntiSpam\Spam and C:\AntiSpam\NonSpam folders respectively. The database itself (spam.dat and nonspam.dat) will be saved in C:\AntiSpam folder.

C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        BayesFilter filter = new BayesFilter();
        MailMessage msg = new MailMessage();

        string spamDatabasePath = @"C:\AntiSpam\spam.dat";
        string nonSpamDatabasePath = @"C:\AntiSpam\nonspam.dat";
        filter.LoadDatabase(spamDatabasePath, nonSpamDatabasePath);

        // Train Bayesian filter for spam messages.
        string[] files = Directory.GetFiles(@"C:\AntiSpam\Spam", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            filter.TrainFilter(msg, true); // Mark as spam.
        }

        // Train Bayesian filter for non-spam messages.
        files = Directory.GetFiles(@"C:\AntiSpam\NonSpam", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            filter.TrainFilter(msg, false); // Mark as non-spam.
        }

        // Save Bayesian database to disk without compression.
        filter.SaveDatabase(spamDatabasePath, nonSpamDatabasePath);

        FileInfo fis = new FileInfo(spamDatabasePath);
        FileInfo fins = new FileInfo(nonSpamDatabasePath);
        Console.WriteLine("Size of database before compacting is: {0}", fis.Length + fins.Length);

        // Compress Bayesian database and save it to disk.
        filter.SaveDatabase(spamDatabasePath, nonSpamDatabasePath, 3, false);

        fis = new FileInfo(spamDatabasePath);
        fins = new FileInfo(nonSpamDatabasePath);
        Console.WriteLine("Size of database after compacting is: {0}", fis.Length + fins.Length);
    }
}

// Outputs:
// Size of database before compacting is: 21164
// Size of database after compacting is: 11364 (may differ in your case)
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee.Mime
Imports MailBee.AntiSpam

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim filter As BayesFilter = New BayesFilter()
        Dim msg As MailMessage = New MailMessage()

        Dim spamDatabasePath As String = "C:\AntiSpam\spam.dat"
        Dim nonSpamDatabasePath As String = "C:\AntiSpam\nonspam.dat"
        filter.LoadDatabase(spamDatabasePath, nonSpamDatabasePath)

        ' Train Bayesian filter for spam messages.
        Dim files() As String = Directory.GetFiles("C:\AntiSpam\Spam", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            filter.TrainFilter(msg, True) ' Mark as spam.
        Next

        ' Train Bayesian filter for non-spam messages.
        files = Directory.GetFiles("C:\AntiSpam\NonSpam", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            filter.TrainFilter(msg, False) ' Mark as non-spam.
        Next

        ' Save Bayesian database to disk.
        filter.SaveDatabase(spamDatabasePath, nonSpamDatabasePath)

        Dim fis As FileInfo = New FileInfo(spamDatabasePath)
        Dim fins As FileInfo = New FileInfo(nonSpamDatabasePath)
        Console.WriteLine("Size of database before compacting is: {0}", fis.Length + fins.Length)

        ' Save Bayesian database to disk and compress it.
        filter.SaveDatabase(spamDatabasePath, nonSpamDatabasePath, 3, False)

        fis = New FileInfo(spamDatabasePath)
        fins = New FileInfo(nonSpamDatabasePath)
        Console.WriteLine("Size of database after compacting is: {0}", fis.Length + fins.Length)
    End Sub
End Class

' Outputs:
' Size of database before compacting is: 21164
' Size of database after compacting is: 11364 (may differ in your case)
See Also

Reference

BayesFilter Class
SaveDatabase Overload
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabaseAsync Method

BayesFilterSaveDatabaseAsync Method
Overload List
 | Name | Description
Public method | SaveDatabaseAsync(Stream, Stream) | async/await version of SaveDatabase(Stream, Stream).
Public method | SaveDatabaseAsync(String, String) | async/await version of SaveDatabase(String, String).
Public method | SaveDatabaseAsync(Stream, Stream, Int32, Boolean) | async/await version of SaveDatabase(Stream, Stream, Int32, Boolean).
Public method | SaveDatabaseAsync(String, String, Int32, Boolean) | async/await version of SaveDatabase(String, String, Int32, Boolean).
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabaseAsync Method (Stream, Stream)

BayesFilterSaveDatabaseAsync Method (Stream, Stream)
async/await version of SaveDatabase(Stream, Stream).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task SaveDatabaseAsync(
    Stream spamStream,
    Stream nonSpamStream
)
Public Function SaveDatabaseAsync (
    spamStream As Stream,
    nonSpamStream As Stream
) As Task

Parameters

spamStream
Type: System.IOStream
An output stream containing spam samples.
nonSpamStream
Type: System.IOStream
An output stream containing non-spam samples.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamStream or nonSpamStream is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
See Also

Reference

BayesFilter Class
SaveDatabaseAsync Overload
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabaseAsync Method (String, String)

BayesFilterSaveDatabaseAsync Method (String, String)
async/await version of SaveDatabase(String, String).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task SaveDatabaseAsync(
    string spamFilename,
    string nonSpamFilename
)
Public Function SaveDatabaseAsync (
    spamFilename As String,
    nonSpamFilename As String
) As Task

Parameters

spamFilename
Type: SystemString
The full or relative path to the file containing spam samples.
nonSpamFilename
Type: SystemString
The full or relative path to the file containing non-spam samples.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamFilename or nonSpamFilename is an empty string or a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
See Also

Reference

BayesFilter Class
SaveDatabaseAsync Overload
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabaseAsync Method (Stream, Stream, Int32, Boolean)

BayesFilterSaveDatabaseAsync Method (Stream, Stream, Int32, Boolean)
async/await version of SaveDatabase(Stream, Stream, Int32, Boolean).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task SaveDatabaseAsync(
    Stream spamStream,
    Stream nonSpamStream,
    int threshold,
    bool saveAlways
)
Public Function SaveDatabaseAsync (
    spamStream As Stream,
    nonSpamStream As Stream,
    threshold As Integer,
    saveAlways As Boolean
) As Task

Parameters

spamStream
Type: System.IOStream
An output stream containing spam samples.
nonSpamStream
Type: System.IOStream
An output stream containing non-spam samples.
threshold
Type: SystemInt32
Specifies how many times (at least) the word should appear in the database to keep it from removal during compacting the database. If the word appears less times then specified, it will be considered non-significant and thus will be removed. If zero, no words will be removed from the database.
saveAlways
Type: SystemBoolean
If true, the method will save the database even if has not been modified since it had been loaded to memory; if false, the method will save it only if it has been modified.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamStream or nonSpamStream is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
See Also

Reference

BayesFilter Class
SaveDatabaseAsync Overload
MailBee.AntiSpam Namespace


BayesFilter.SaveDatabaseAsync Method (String, String, Int32, Boolean)

BayesFilterSaveDatabaseAsync Method (String, String, Int32, Boolean)
async/await version of SaveDatabase(String, String, Int32, Boolean).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task SaveDatabaseAsync(
    string spamFilename,
    string nonSpamFilename,
    int threshold,
    bool saveAlways
)
Public Function SaveDatabaseAsync (
    spamFilename As String,
    nonSpamFilename As String,
    threshold As Integer,
    saveAlways As Boolean
) As Task

Parameters

spamFilename
Type: SystemString
The full or relative path to the file containing spam samples.
nonSpamFilename
Type: SystemString
The full or relative path to the file containing non-spam samples.
threshold
Type: SystemInt32
Specifies how many times (at least) the word should appear in the database to keep it from removal during compacting the database. If the word appears less times then specified, it will be considered non-significant and thus will be removed. If zero, no words will be removed from the database.
saveAlways
Type: SystemBoolean
If true, the method will save the database even if has not been modified since it had been loaded to memory; if false, the method will save it only if it has been modified.

Return Value

Type: Task
A task that represents the asynchronous operation.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | spamFilename or nonSpamFilename is an empty string or a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred.
See Also

Reference

BayesFilter Class
SaveDatabaseAsync Overload
MailBee.AntiSpam Namespace


BayesFilter.ScoreMessage Method

BayesFilterScoreMessage Method
Analyses the message and returns the probability of the message being spam.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int ScoreMessage(
    MailMessage message
)
Public Function ScoreMessage (
    message As MailMessage
) As Integer

Parameters

message
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be scored.

Return Value

Type: Int32
An integer value in 0-100 range, where 0 corresponds to "definitely non-spam" (0% spam probability) and 100 corresponds to "definitely spam" (100% spam probability).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
Remarks

ScoreMessage(MailMessage) method will always show 50% result if the database is an empty or absent at all. So, there is no sense to use this method preparatory to the moment when the database has any data (the more the better).

In case of multy-threading AutoLearning property should be set to false.

When the AutoLearning property is set to true, Bayesian database may update itself in memory. It may need to update database on disk. To store database to disk please use SaveDatabase(String, String) method.

Examples
The example is available in BayesFilter topic.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace
BayesFilterAutoLearning


BayesFilter.TrainFilter Method

BayesFilterTrainFilter Method
Learns from the specified message as from spam or non-spam source.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void TrainFilter(
    MailMessage message,
    bool isSpam
)
Public Sub TrainFilter (
    message As MailMessage,
    isSpam As Boolean
)

Parameters

message
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to train the Bayesian filter.
isSpam
Type: SystemBoolean
true if the message is a spam; false if it's a legitimate message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
Remarks

Prior to starting using the Bayesian filter to detect spam messages you should learn it with a number of spam and non-spam messages. The filter becomes effective if the database contains at least hundreds of different spam and non-spam messages.

This method updates the database only in memory. To store the database to disk, use SaveDatabase(String, String) method.

Examples

This sample trains Bayesian database with spam and non-spam messages and saves it to disk.

It's assumed the spam and non-spam samples are .EML files located in C:\AntiSpam\Spam and C:\AntiSpam\NonSpam folders respectively. The database itself (spam.dat and nonspam.dat) will be saved in C:\AntiSpam folder.

C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee.Mime;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        BayesFilter filter = new BayesFilter();
        MailMessage msg = new MailMessage();

        filter.LoadDatabase(@"C:\AntiSpam\spam.dat", @"C:\AntiSpam\nonspam.dat");

        // Train Bayesian filter for spam messages.
        string[] files = Directory.GetFiles(@"C:\AntiSpam\Spam", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            filter.TrainFilter(msg, true); // Mark as spam.
        }

        // Train Bayesian filter for non-spam messages.
        files = Directory.GetFiles(@"C:\AntiSpam\NonSpam", "*.eml");
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            filter.TrainFilter(msg, false); // Mark as non-spam.
        }

        // Save Bayesian database to disk.
        filter.SaveDatabase(@"C:\AntiSpam\spam.dat", @"C:\AntiSpam\nonspam.dat");
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee.Mime
Imports MailBee.AntiSpam

Module Sample
    Sub Main(ByVal args() As String)
        Dim filter As BayesFilter = New BayesFilter()
        Dim msg As MailMessage = New MailMessage()

        filter.LoadDatabase("C:\AntiSpam\spam.dat", "C:\AntiSpam\nonspam.dat")

        ' Train Bayesian filter for spam messages.
        Dim files() As String = Directory.GetFiles("C:\AntiSpam\Spam", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            filter.TrainFilter(msg, True) ' Mark as spam.
        Next

        ' Train Bayesian filter for non-spam messages.
        files = Directory.GetFiles("C:\AntiSpam\NonSpam", "*.eml")
        For Each file As String In files
            msg.LoadMessage(file)
            filter.TrainFilter(msg, False) ' Mark as non-spam.
        Next

        ' Save Bayesian database to disk.
        filter.SaveDatabase("C:\AntiSpam\spam.dat", "C:\AntiSpam\nonspam.dat")
    End Sub
End Module
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter Properties

BayesFilter Properties

The BayesFilter type exposes the following members.

Properties
 | Name | Description
Public property | Algorithm | Gets or sets the algorithm to be used for scoring messages.
Public property | AutoLearning | Gets or sets if the filter should automatically learn during scoring messages on the words with the sufficient spam/non-spam weight.
Public property | AutoLearningGradeAbove | Gets or sets the minimum score the message should get so that the filter will treat it as spam and automatically learn this.
Public property | AutoLearningGradeBelow | Gets or sets the maximum score the message should get so that the filter will treat it as non-spam and automatically learn this.
 | LicenseKey | Obsolete. Assigns the license key.
Public property | OnLockedDatabase | Gets or sets the application-supplied method which will be executed if MailBee founds that spam or non-spam database file is locked when it needs to perform I/O operation with it.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.Algorithm Property

BayesFilterAlgorithm Property
Gets or sets the algorithm to be used for scoring messages.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public BayesAlgorithm Algorithm { get; set; }
Public Property Algorithm As BayesAlgorithm
    Get
    Set

Property Value

Type: BayesAlgorithm
The algorithm to be used for scoring messages.
The default value is ChiSquareAlgorithm.
Remarks
Use GrahamAlgorithm for better speed; use ChiSquareAlgorithm for better accuracy.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.AutoLearning Property

BayesFilterAutoLearning Property
Gets or sets if the filter should automatically learn during scoring messages on the words with the sufficient spam/non-spam weight.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AutoLearning { get; set; }
Public Property AutoLearning As Boolean
    Get
    Set

Property Value

Type: Boolean
true if all the words with the sufficient spam/non-spam weight detected during scoring the message should be added to the Bayesian database; false if no change of the database should take place.
The default value is false.
Remarks
If AutoLearning is true, ScoreMessage(MailMessage) method will be able to update the database during its execution. To save changes, call SaveDatabase(String, String) method prior your application finishes execution.
Note Note
If you score multiple messages simultaneously in multi-threaded application, be aware that AutoLearning option makes ScoreMessage(MailMessage) method thread-unsafe.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace
BayesFilterAutoLearningGradeAbove
BayesFilterAutoLearningGradeBelow


BayesFilter.AutoLearningGradeAbove Property

BayesFilterAutoLearningGradeAbove Property
Gets or sets the minimum score the message should get so that the filter will treat it as spam and automatically learn this.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int AutoLearningGradeAbove { get; set; }
Public Property AutoLearningGradeAbove As Integer
    Get
    Set

Property Value

Type: Int32
The integer value in 0-100 range specifying the minimum score the message should get so that the filter will automatically learn from it as from spam sample.
The default value is 90.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is out of 0-100 range.
Remarks
This property has no effect if AutoLearning is false.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace
BayesFilterAutoLearningGradeBelow
BayesFilterAutoLearning


BayesFilter.AutoLearningGradeBelow Property

BayesFilterAutoLearningGradeBelow Property
Gets or sets the maximum score the message should get so that the filter will treat it as non-spam and automatically learn this.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int AutoLearningGradeBelow { get; set; }
Public Property AutoLearningGradeBelow As Integer
    Get
    Set

Property Value

Type: Int32
The integer value in 0-100 range specifying the maximum score the message should get so that the filter will automatically learn from it as from non-spam sample.
The default value is 5.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is out of 0-100 range.
Remarks
This property has no effect if AutoLearning is false.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace
BayesFilterAutoLearningGradeAbove
BayesFilterAutoLearning


BayesFilter.LicenseKey Property

BayesFilterLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.OnLockedDatabase Property

BayesFilterOnLockedDatabase Property
Gets or sets the application-supplied method which will be executed if MailBee founds that spam or non-spam database file is locked when it needs to perform I/O operation with it.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public LockedDatabaseDelegate OnLockedDatabase { get; set; }
Public Property OnLockedDatabase As LockedDatabaseDelegate
    Get
    Set

Property Value

Type: LockedDatabaseDelegate
The reference to the delegate to be called in case of spam or non-spam database being locked, or a null reference (Nothing in Visual Basic) if the delegate is not set.
Remarks

In most cases, you won't need to write custom handler of locked spam databases and set this property. By default, when MailBee finds out that spam or non-spam database is locked, it sleeps the thread for 10 millisecs, then tries again (up to 100 times). This logic is satisfactory for most applications. But if your case is very special (for instance, you deal with a very slow disk storage), you may need to supply your own custom mechanism for this.

See LockedDatabaseDelegate topic to learn more how to implement to write the delegate handler if you need to.

See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


BayesFilter.TrialDaysLeft Property

BayesFilterTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value indicating the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

BayesFilter Class
MailBee.AntiSpam Namespace


LockedDatabaseDelegate Delegate

LockedDatabaseDelegate Delegate
Defines the signature (the parameters and the return value) of the application-defined method to be called when the Bayesian spam or non-spam database file appears to be locked.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate bool LockedDatabaseDelegate(
    string filename,
    bool isSpamDatabase
)
Public Delegate Function LockedDatabaseDelegate (
    filename As String,
    isSpamDatabase As Boolean
) As Boolean

Parameters

filename
Type: SystemString
The filename of the database file which is locked, as specified by the corresponding parameter of SaveDatabase(String, String) or LoadDatabase(String, String) methods.
isSpamDatabase
Type: SystemBoolean
true if the database being locked is spam database; false if non-spam.

Return Value

Type: Boolean
Must return true if MailBee should immediately make another attempt to open the file. If false, MailBee will throw MailBeeIOException.
Remarks

To set this delegate, use OnLockedDatabase property.

In the delegate handler, you will typically make some delay to let other processes complete saving the database, check if the file is no longer locked, and return true. To avoid deadlocks, it's recommended to have some kind of a counter (if it reaches certain value, consider that another application has hanged and you return false as you can't proceed).

See Also

Reference

MailBee.AntiSpam Namespace
BayesFilterOnLockedDatabase


RblFilter Class

RblFilter Class
Provides methods to filter spam by checking e-mails and IP addresses against DNS RBL databases.
Inheritance Hierarchy
SystemObject
MailBee.AntiSpamRblFilter

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class RblFilter : IComponent, IDisposable
Public Class RblFilter
    Implements IComponent, IDisposable

The RblFilter type exposes the following members.

Constructors
 | Name | Description
 | RblFilter | Creates an instance of RblFilter class.
Public method | RblFilter(String) | Creates and unlocks an instance of RblFilter class.
Top
Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetRblStatusesOfIPAddress | Gets the statuses of the given IPv4 address in the specified RBLs.
Public method | GetRblStatusesOfIPAddressAsync | async/await version of GetRblStatusesOfIPAddress(String, String).
 | GetRblStatusesOfMailOriginatingIPAddress | Gets the statuses of the IP address the given e-mail originated from, in the specified DNS RBL databases.
Public method | GetRblStatusesOfMailOriginatingIPAddressAsync | async/await version of GetRblStatusesOfMailOriginatingIPAddress(MailMessage, Int32, String).
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | IsIPAddressInRbl | Checks if the given IP address is listed in the specified DNS RBL.
Public method | IsIPAddressInRblAsync | async/await version of IsIPAddressInRbl(String, String).
 | IsMailOriginatingIPAddressInRbl | Checks if the IP address the e-mail was received from is present in DNS RBL database.
Public method | IsMailOriginatingIPAddressInRblAsync | async/await version of IsMailOriginatingIPAddressInRbl(MailMessage, Int32, String).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Public method | ResetState | Resets the internal state of the component.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DnsServers | Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS RBL lookup.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MaxThreadCount | Gets or sets the maximum number of threads MailBee may create during RBL verification of IP addresses. operations.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | Site | Gets or sets the object to be used as a site for the component.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
Events
 | Name | Description
 | DataReceived | Occurs when data is received from the network.
 | DataSent | Occurs when data is sent to the network.
Public event | Disposed | Occurs after the component was disposed.
Public event | ErrorOccurred | Occurs when MailBeeException is thrown internally.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if RblFilter.Log.MemoryLog is true).
Top
Remarks

The methods of this class make DNS queries to RBL servers to check if a particular address is in blacklists. Multiple RBLs can be checked simultaneously, greatly improving performance.

If you don't know the IP address but have a mail message you want to check, you can also pass a MailMessage and MailBee will extract the originating IP address from Received headers.

Unlike BayesFilter class, this class doesn't require you to train the filter first, it's always ready for immediate use.

Popular RBLs you can use (although you're free to change or extend this list in any way):

  • zen.spamhaus.org
  • bl.spamcop.net
  • cbl.abuseat.org

Note Note
RBLs are third-party resources, they can block DNS requests from your machine for any reason (for instance, if you make too many queries daily or hourly). Moreover, some RBLs like Barracuda won't let you use them until you create an account in their system. It's recommended to keep volume of DNS queries as low as possible. For instance, you should disable DNS TCP and leave only DNS UDP. Also, MailBee by default caches earlier received results of checking IP addresses in DnsCache so it won't make another request if the given IP address has already been checked during the current session of your program.
Note Note
When passing DNS RBL host name, be sure to make no typos. The nature of DNS is that if you make a typo in RBL name, it will have an effect like there is no IP address in the given RBL but no error may occur. This is because there is no actual connection with any server occurs, RBL is purely DNS thing. Errors usually occur only if for some queries your DNS server time out for some reason.

You can combine using RBLs with Bayesian filter (BayesFilter class) or DKIM checks (e.g. DomainKeysVerify). It's also possible to check reverse DNS (PTR), MX records, SPF. Check "Filter spam with DNS queries (MX, SPF, DKIM, reverse DNS)" tutorial in Developer's Guide for more.

Examples

This sample checks an e-mail against popular RBLs (the e-mail is loaded from a file but could also be received from a mail server, the only requirement is that the message must have Received header from which MailBee will determine the IP address the message originated from).

The sample also fine-tunes DNS checking routine for better performance (at cost of lower accuracy). You can remove "For performance sake" section to return to default DNS settings.

This is multi-threaded (and faster) version of the sample from RblFilter topic.

C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.DnsMX;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        RblFilter rbl = new RblFilter();

        // Logging is helpful for debugging.
        rbl.Log.Enabled = true;
        rbl.Log.Filename = @"C:\Temp\log.txt";
        rbl.Log.Format = LogFormatOptions.AddContextInfo; // Context info is useful in multi-threaded mode.
        rbl.Log.Clear();

        // RBL check needs DNS servers.
        rbl.DnsServers.Autodetect();

        // For performance sake, avoid making redundant TCP queries. UDP is enough with RBL.
        // Also, the default 5000ms timeout can be too long.
        foreach (DnsServer dns in rbl.DnsServers)
        {
            dns.TryTcp = false;
            dns.UdpTimeout = 500;

            // Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            // but the results will be more accurate.
            dns.UdpRetryCount = 1;
        }

        // Multi-threaded mode. This sample will run faster than single-threaded version.
        rbl.MaxThreadCount = -1;

        // Grab some mail message to check. In production, you can get it from IMAP server or elsewhere.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\msg.eml");

        // Ask some popular RBLs about this message.
        RblStatusCollection statuses = rbl.GetRblStatusesOfMailOriginatingIPAddress(msg, 0,
            new string[] { "zen.spamhaus.org", "bl.spamcop.net", "cbl.abuseat.org" });
        if (statuses == null)
        {
            Console.WriteLine("Can't extract originating IP address from the e-mail");
        }
        else
        {
            Console.WriteLine("Is in RBLs: " + statuses.IsInRbls.ToString());
            foreach (RblStatus status in statuses)
            {
                Console.WriteLine(string.Format("RBL: {0}, IP found: {1}, RBL check resulted in error: {2}, RBL reply: {3}",
                    status.RblHost, status.IsIPAddressInRbl, status.IsError, status.RblReplyText));
            }
        }
    }
}
Imports MailBee
Imports MailBee.Mime
Imports MailBee.DnsMX
Imports MailBee.AntiSpam

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim rbl As New RblFilter()

        ' Logging is helpful for debugging.
        rbl.Log.Enabled = True
        rbl.Log.Filename = "C:\Temp\log.txt"
        rbl.Log.Format = LogFormatOptions.AddContextInfo ' Context info is useful in multi-threaded mode.
        rbl.Log.Clear()

        ' RBL check needs DNS servers.
        rbl.DnsServers.Autodetect()

        ' For performance sake, avoid making redundant TCP queries. UDP is enough with RBL.
        ' Also, the default 5000ms timeout can be too long.
        For Each dns As DnsServer In rbl.DnsServers
            dns.TryTcp = False
            dns.UdpTimeout = 500

            ' Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            ' but the results will be more accurate.
            dns.UdpRetryCount = 1
        Next

        ' Multi-threaded mode. This sample will run faster than single-threaded version.
        rbl.MaxThreadCount = -1

        ' Grab some mail message to check. In production, you can get it from IMAP server or elsewhere.
        Dim msg As New MailMessage()
        msg.LoadMessage("C:\Temp\msg.eml")

        ' Ask some popular RBLs about this message.
        Dim statuses As RblStatusCollection = rbl.GetRblStatusesOfMailOriginatingIPAddress(msg, 0, _
         New String() {"zen.spamhaus.org", "bl.spamcop.net", "cbl.abuseat.org"})
        If statuses Is Nothing Then
            Console.WriteLine("Can't extract originating IP address from the e-mail")
        Else
            Console.WriteLine("Is in RBLs: " & statuses.IsInRbls.ToString())
            For Each status As RblStatus In statuses
                Console.WriteLine(String.Format("RBL: {0}, IP found: {1}, RBL check resulted in error: {2}, RBL reply: {3}", _
                 status.RblHost, status.IsIPAddressInRbl, status.IsError, status.RblReplyText))
            Next
        End If

    End Sub
End Class
See Also

Reference

MailBee.AntiSpam Namespace


RblFilter Constructor

RblFilter Constructor
Creates an instance of RblFilter class.
Overload List
 | Name | Description
 | RblFilter | Creates an instance of RblFilter class.
Public method | RblFilter(String) | Creates and unlocks an instance of RblFilter class.
Top
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter Constructor

RblFilter Constructor
Creates an instance of RblFilter class.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RblFilter()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET AntiSpam not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
Examples

This sample checks an e-mail against popular RBLs (the e-mail is loaded from a file but could also be received from a mail server, the only requirement is that the message must have Received header from which MailBee will determine the IP address the message originated from).

The sample also fine-tunes DNS checking routine for better performance (at cost of lower accuracy). You can remove "For performance sake" section to return to default DNS settings.

This is single-threaded version of the sample from RblFilter topic. It will take longer to execute but easier to debug because execution order is simple and determined.

C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.DnsMX;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        RblFilter rbl = new RblFilter();

        // Logging is helpful for debugging.
        rbl.Log.Enabled = true;
        rbl.Log.Filename = @"C:\Temp\log.txt";
        rbl.Log.Clear();

        // RBL check needs DNS servers.
        rbl.DnsServers.Autodetect();

        // For performance sake, avoid making redundant TCP queries. UDP is enough with RBL.
        // Also, the default 5000ms timeout can be too long.
        foreach (DnsServer dns in rbl.DnsServers)
        {
            dns.TryTcp = false;
            dns.UdpTimeout = 500;

            // Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            // but the results will be more accurate.
            dns.UdpRetryCount = 1;
        }

        // Grab some mail message to check. In production, you can get it from IMAP server or elsewhere.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\msg.eml");

        // Ask some popular RBLs about this message.
        RblStatusCollection statuses = rbl.GetRblStatusesOfMailOriginatingIPAddress(msg, 0,
            new string[] { "zen.spamhaus.org", "bl.spamcop.net", "cbl.abuseat.org" });
        if (statuses == null)
        {
            Console.WriteLine("Can't extract originating IP address from the e-mail");
        }
        else
        {
            Console.WriteLine("Is in RBLs: " + statuses.IsInRbls.ToString());
            foreach (RblStatus status in statuses)
            {
                Console.WriteLine(string.Format("RBL: {0}, IP found: {1}, RBL check resulted in error: {2}, RBL reply: {3}",
                    status.RblHost, status.IsIPAddressInRbl, status.IsError, status.RblReplyText));
            }
        }
    }
}
Imports MailBee
Imports MailBee.Mime
Imports MailBee.DnsMX
Imports MailBee.AntiSpam

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim rbl As New RblFilter()

        ' Logging is helpful for debugging.
        rbl.Log.Enabled = True
        rbl.Log.Filename = "C:\Temp\log.txt"
        rbl.Log.Clear()

        ' RBL check needs DNS servers.
        rbl.DnsServers.Autodetect()

        ' For performance sake, avoid making redundant TCP queries. UDP is enough with RBL.
        ' Also, the default 5000ms timeout can be too long.
        For Each dns As DnsServer In rbl.DnsServers
            dns.TryTcp = False
            dns.UdpTimeout = 500

            ' Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            ' but the results will be more accurate.
            dns.UdpRetryCount = 1
        Next

        ' Grab some mail message to check. In production, you can get it from IMAP server or elsewhere.
        Dim msg As New MailMessage()
        msg.LoadMessage("C:\Temp\msg.eml")

        ' Ask some popular RBLs about this message.
        Dim statuses As RblStatusCollection = rbl.GetRblStatusesOfMailOriginatingIPAddress(msg, 0, _
         New String() {"zen.spamhaus.org", "bl.spamcop.net", "cbl.abuseat.org"})
        If statuses Is Nothing Then
            Console.WriteLine("Can't extract originating IP address from the e-mail")
        Else
            Console.WriteLine("Is in RBLs: " & statuses.IsInRbls.ToString())
            For Each status As RblStatus In statuses
                Console.WriteLine(String.Format("RBL: {0}, IP found: {1}, RBL check resulted in error: {2}, RBL reply: {3}", _
                 status.RblHost, status.IsIPAddressInRbl, status.IsError, status.RblReplyText))
            Next
        End If

    End Sub
End Class
See Also

Reference

RblFilter Class
RblFilter Overload
MailBee.AntiSpam Namespace


RblFilter Constructor (String)

RblFilter Constructor (String)
Creates and unlocks an instance of RblFilter class.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RblFilter(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET AntiSpam not licensed and the supplied license key is invalid.
See Also

Reference

RblFilter Class
RblFilter Overload
MailBee.AntiSpam Namespace


RblFilter Methods

RblFilter Methods

The RblFilter type exposes the following members.

Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetRblStatusesOfIPAddress | Gets the statuses of the given IPv4 address in the specified RBLs.
Public method | GetRblStatusesOfIPAddressAsync | async/await version of GetRblStatusesOfIPAddress(String, String).
 | GetRblStatusesOfMailOriginatingIPAddress | Gets the statuses of the IP address the given e-mail originated from, in the specified DNS RBL databases.
Public method | GetRblStatusesOfMailOriginatingIPAddressAsync | async/await version of GetRblStatusesOfMailOriginatingIPAddress(MailMessage, Int32, String).
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | IsIPAddressInRbl | Checks if the given IP address is listed in the specified DNS RBL.
Public method | IsIPAddressInRblAsync | async/await version of IsIPAddressInRbl(String, String).
 | IsMailOriginatingIPAddressInRbl | Checks if the IP address the e-mail was received from is present in DNS RBL database.
Public method | IsMailOriginatingIPAddressInRblAsync | async/await version of IsMailOriginatingIPAddressInRbl(MailMessage, Int32, String).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Public method | ResetState | Resets the internal state of the component.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.Abort Method

RblFilterAbort Method
Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Abort()
Public Sub Abort
Remarks

A method which was in progress when Abort method has been called will throw MailBeeUserAbortException.

Note Note
No events will be raised after this method has been called.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace
RblFilterIsAborted


RblFilter.Dispose Method

RblFilterDispose Method
Overload List
 | Name | Description
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Top
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.Dispose Method

RblFilterDispose Method
Closes opened network connections (if any) and releases any used system resources.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
Usually, the developer does not need to call this method as the object can free its resources automatically.
See Also

Reference

RblFilter Class
Dispose Overload
MailBee.AntiSpam Namespace


RblFilter.Dispose Method (Boolean)

RblFilterDispose Method (Boolean)
When overridden in a derived class, must release unmananged and optionally managed resources used by the component.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Remarks
If the derived class does not use any additional resources, this method does not need to be overridden. If, however, it's overridden, the developer must also call Dispose method of the base class.
See Also

Reference

RblFilter Class
Dispose Overload
MailBee.AntiSpam Namespace


RblFilter.GetRblStatusesOfIPAddress Method

RblFilterGetRblStatusesOfIPAddress Method
Gets the statuses of the given IPv4 address in the specified RBLs.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RblStatusCollection GetRblStatusesOfIPAddress(
    string ipString,
    string[] rblHosts
)
Public Function GetRblStatusesOfIPAddress (
    ipString As String,
    rblHosts As String()
) As RblStatusCollection

Parameters

ipString
Type: SystemString
The IPv4 address to check, as "11.22.33.44" string.
rblHosts
Type: SystemString
The array of DNS RBLs' host names.

Return Value

Type: RblStatusCollection
The collection of statuses of the given IPv4 address in the specified RBLs.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | ipString is a null reference (Nothing in Visual Basic) or an empty string or does not denote a valid IPv4 address or rblHosts is a null reference or contains at least one value which is a null reference or an empty string.
MailBeeException | Another error occurred (e.g. timeout from DNS server) for all RBLs in the list.
Remarks

This method supports multi-threading to check multiple RBLs at once. To enable multi-threading, set MaxThreadCount to -1.

For each RBL, its own status is set. Unlike Boolean-returning methods like IsIPAddressInRbl(String, String), this method provides more extensive info for an IP address. In particular, RblReplyText property of each RblStatus object in the resulting collection may contain the exact reason of the IP addresses being blacklisted. You need to refer to the documentation of the corresponding RBL to find out how to treat the return codes.

For instance, return codes of the popular Spamhaus Zen RBL can be found at https://www.spamhaus.org/zen/.

Note Note
This method won't throw an exception if only certain RBLs in the list failed to be checked. If at least one DNS query succeeded, the method will return normally. For RBLs which failed, IsError will be true. To monitor errors during this method's execution, subscribe to ErrorOccurred event.
Examples
C#
VB
Copy
using System;
using MailBee;
using MailBee.DnsMX;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        RblFilter rbl = new RblFilter();

        // Logging is helpful for debugging.
        rbl.Log.Enabled = true;
        rbl.Log.Filename = @"C:\Temp\log.txt";
        rbl.Log.Format = LogFormatOptions.AddContextInfo;
        rbl.Log.Clear();

        // RBL check needs DNS servers.
        rbl.DnsServers.Autodetect();

        // For performance sake, avoid making redundant queries. UDP is enough with RBL.
        // Also, the default 5000ms timeout can be too long.
        foreach (DnsServer dns in rbl.DnsServers)
        {
            dns.TryTcp = false;
            dns.UdpTimeout = 500;

            // Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            // but the results will be more accurate.
            dns.UdpRetryCount = 1;
        }

        // Multi-threading lets us check all RBLs at once.
        rbl.MaxThreadCount = -1;

        // Ask some popular RBLs about some IP address.
        RblStatusCollection statuses = rbl.GetRblStatusesOfIPAddress("11.22.33.44",
            new string[] { "zen.spamhaus.org", "bl.spamcop.net", "cbl.abuseat.org" });
        if (statuses == null)
        {
            Console.WriteLine("Can't extract originating IP address from the e-mail");
        }
        else
        {
            Console.WriteLine("Is in RBLs: " + statuses.IsInRbls.ToString());
            foreach (RblStatus status in statuses)
            {
                Console.WriteLine(string.Format("RBL: {0}, IP found: {1}, RBL check resulted in error: {2}, RBL reply: {3}",
                    status.RblHost, status.IsIPAddressInRbl, status.IsError, status.RblReplyText));
            }
        }
    }
}
Imports MailBee
Imports MailBee.DnsMX
Imports MailBee.AntiSpam

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim rbl As New RblFilter()

        ' Logging is helpful for debugging.
        rbl.Log.Enabled = True
        rbl.Log.Filename = "C:\Temp\log.txt"
        rbl.Log.Format = LogFormatOptions.AddContextInfo
        rbl.Log.Clear()

        ' RBL check needs DNS servers.
        rbl.DnsServers.Autodetect()

        ' For performance sake, avoid making redundant queries. UDP is enough with RBL.
        ' Also, the default 5000ms timeout can be too long.
        For Each dns As DnsServer In rbl.DnsServers
            dns.TryTcp = False
            dns.UdpTimeout = 500

            ' Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            ' but the results will be more accurate.
            dns.UdpRetryCount = 1
        Next

        ' Multi-threading lets us check all RBLs at once.
        rbl.MaxThreadCount = -1

        ' Ask some popular RBLs about some IP address.
        Dim statuses As RblStatusCollection = rbl.GetRblStatusesOfIPAddress("11.22.33.44", _
         New String() {"zen.spamhaus.org", "bl.spamcop.net", "cbl.abuseat.org"})
        If statuses Is Nothing Then
            Console.WriteLine("Can't extract originating IP address from the e-mail")
        Else
            Console.WriteLine("Is in RBLs: " & statuses.IsInRbls.ToString())
            For Each status As RblStatus In statuses
                Console.WriteLine(String.Format("RBL: {0}, IP found: {1}, RBL check resulted in error: {2}, RBL reply: {3}", _
                 status.RblHost, status.IsIPAddressInRbl, status.IsError, status.RblReplyText))
            Next
        End If
    End Sub
End Class
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.GetRblStatusesOfIPAddressAsync Method

RblFilterGetRblStatusesOfIPAddressAsync Method
async/await version of GetRblStatusesOfIPAddress(String, String).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<RblStatusCollection> GetRblStatusesOfIPAddressAsync(
    string ipString,
    string[] rblHosts
)
Public Function GetRblStatusesOfIPAddressAsync (
    ipString As String,
    rblHosts As String()
) As Task(Of RblStatusCollection)

Parameters

ipString
Type: SystemString
The IPv4 address to check, as "11.22.33.44" string.
rblHosts
Type: SystemString
The array of DNS RBLs' host names.

Return Value

Type: Task RblStatusCollection
A task that represents the asynchronous operation. The value of TResult parameter is a reference to the collection of statuses of the given IPv4 address in the specified RBLs.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | ipString is a null reference (Nothing in Visual Basic) or an empty string or does not denote a valid IPv4 address or rblHosts is a null reference or contains at least one value which is a null reference or an empty string.
MailBeeException | Another error occurred (e.g. timeout from DNS server) for all RBLs in the list.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.GetRblStatusesOfMailOriginatingIPAddress Method

RblFilterGetRblStatusesOfMailOriginatingIPAddress Method
Gets the statuses of the IP address the given e-mail originated from, in the specified DNS RBL databases.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RblStatusCollection GetRblStatusesOfMailOriginatingIPAddress(
    MailMessage msg,
    int receivedIndex,
    string[] rblHosts
)
Public Function GetRblStatusesOfMailOriginatingIPAddress (
    msg As MailMessage,
    receivedIndex As Integer,
    rblHosts As String()
) As RblStatusCollection

Parameters

msg
Type: MailBee.MimeMailMessage
A mail message with at least one Received header which contains the IP address the message came from.
receivedIndex
Type: SystemInt32
The zero-based index of Received header to examine. Usually, zero (denotes the most recent header).
rblHosts
Type: SystemString
The RBLs' host names.

Return Value

Type: RblStatusCollection
The collection of statuses of the e-mail originating IPv4 address in the specified RBLs, or a null reference (Nothing in Visual Basic) if no matching IPv4 address was found in the specified Received header.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg is a null reference (Nothing in Visual Basic), or rblHosts is a null reference or contains at least one value which is a null reference or an empty string, or receivedIndex is negative or does not denote a valid index in msg's TimeStamps collection.
MailBeeException | Another error occurred (e.g. timeout from DNS server) for all RBLs in the list.
Remarks

This method extracts the originating IPv4 address from Received header and then uses GetRblStatusesOfIPAddress(String, String) method to get the statuses of this IP address in the specified RBLs.

Usually, the most recent Received header must be examined (receivedIndex must be zero). However, in case if mail flow in your network is more complex (e.g. all mail is forwarded through some gateway), you may need to analyze not the most recent Received but next to it. In this case, receivedIndex must be 1.

The header may look like Received: from [19.43.20.143] (helo=zebra.domain.com) by mx.afterlogic.com with esmtp (Exim 4.85) id 1ctx6r-119Hei-S8 for support@afterlogic.com; Fri, 31 Mar 2017 07:01:03 -0700.

In the above, 19.43.20.143 denotes the originating IP address.

This method supports multi-threading to check multiple RBLs at once. To enable multi-threading, set MaxThreadCount to -1.

For each RBL, its own status is set. Unlike Boolean-returning methods like IsMailOriginatingIPAddressInRbl(MailMessage, Int32, String), this method provides more extensive info for an IP address. In particular, RblReplyText property of each RblStatus object in the resulting collection may contain the exact reason of the IP addresses being blacklisted. You need to refer to the documentation of the corresponding RBL to find out how to treat the return codes.

For instance, return codes of the popular Spamhaus Zen RBL can be found at https://www.spamhaus.org/zen/.

Note Note
This method won't throw an exception if only certain RBLs in the list failed to be checked. If at least one DNS query succeeded, the method will return normally. For RBLs which failed, IsError will be true. To monitor errors during this method's execution, subscribe to ErrorOccurred event.
Examples
See multi-threaded sample in RblFilter topic, single-threaded sample - in RblFilter topic.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.GetRblStatusesOfMailOriginatingIPAddressAsync Method

RblFilterGetRblStatusesOfMailOriginatingIPAddressAsync Method
async/await version of GetRblStatusesOfMailOriginatingIPAddress(MailMessage, Int32, String).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<RblStatusCollection> GetRblStatusesOfMailOriginatingIPAddressAsync(
    MailMessage msg,
    int receivedIndex,
    string[] rblHosts
)
Public Function GetRblStatusesOfMailOriginatingIPAddressAsync (
    msg As MailMessage,
    receivedIndex As Integer,
    rblHosts As String()
) As Task(Of RblStatusCollection)

Parameters

msg
Type: MailBee.MimeMailMessage
A mail message with at least one Received header which contains the IP address the message came from.
receivedIndex
Type: SystemInt32
The zero-based index of Received header to examine. Usually, zero (denotes the most recent header).
rblHosts
Type: SystemString
The RBLs' host names.

Return Value

Type: Task RblStatusCollection
A task that represents the asynchronous operation. The value of TResult parameter is a reference to the collection of statuses of the e-mail originating IPv4 address in the specified RBLs, or a null reference (Nothing in Visual Basic) if no matching IPv4 address was found in the specified Received header.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg is a null reference (Nothing in Visual Basic), or rblHosts is a null reference or contains at least one value which is a null reference or an empty string, or receivedIndex is negative or does not denote a valid index in msg's TimeStamps collection.
MailBeeException | Another error occurred (e.g. timeout from DNS server) for all RBLs in the list.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.IsIPAddressInRbl Method

RblFilterIsIPAddressInRbl Method
Checks if the given IP address is listed in the specified DNS RBL.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsIPAddressInRbl(
    string ipString,
    string rblHost
)
Public Function IsIPAddressInRbl (
    ipString As String,
    rblHost As String
) As Boolean

Parameters

ipString
Type: SystemString
The IPv4 address to check, as "11.22.33.44" string.
rblHost
Type: SystemString
The DNS RBL host name.

Return Value

Type: Boolean
true if this IP address is black-listed; othwerwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | ipString or rblHost is a null reference (Nothing in Visual Basic) or an empty string, or ipString does not denote a valid IPv4 address.
MailBeeException | Another error occurred (e.g. timeout from DNS server).
Remarks

To check against multiple RBLs at once, use GetRblStatusesOfIPAddress(String, String) method (it can utilize multi-threading).

To fine-tune tradeoff between performance and accuracy, you can use different number of DNS servers (more servers tried - less performance but more accuracy), increase timeouts or retry count (the same effect), add option to try DNS via TCP, not just UDP (some DNS servers don't deliver meaningful replies via TCP although it's not common for DNS RBL servers).

Note Note
Be sure to specify the correct name for the RBL host. If you make a typo, it will have effect of RBL returning "not blacklisted" status for any IP address. No error will occur.
Examples

This sample checks an IP address against "zen.spamhaus.org" RBL. The most interesting line of code is the last one.

The sample also fine-tunes DNS checking routine for better performance (at cost of lower accuracy). You can remove "For performance sake" section to return to default DNS settings.

C#
VB
Copy
using System;
using MailBee;
using MailBee.DnsMX;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        RblFilter rbl = new RblFilter();

        // Logging is helpful for debugging.
        rbl.Log.Enabled = true;
        rbl.Log.Filename = @"C:\Temp\log.txt";
        rbl.Log.Clear();

        // RBL check needs DNS servers.
        rbl.DnsServers.Autodetect();

        // For performance sake, avoid making redundant TCP queries. UDP is enough with RBL.
        // Also, the default 5000ms timeout can be too long.
        foreach (DnsServer dns in rbl.DnsServers)
        {
            dns.TryTcp = false;
            dns.UdpTimeout = 500;

            // Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            // but the results will be more accurate.
            dns.UdpRetryCount = 1;
        }

        Console.WriteLine("Is in RBL: " + rbl.IsIPAddressInRbl("11.22.33.44", "zen.spamhaus.org").ToString());
    }
}
Imports MailBee
Imports MailBee.DnsMX
Imports MailBee.AntiSpam

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim rbl As New RblFilter()

        ' Logging is helpful for debugging.
        rbl.Log.Enabled = True
        rbl.Log.Filename = "C:\Temp\log.txt"
        rbl.Log.Clear()

        ' RBL check needs DNS servers.
        rbl.DnsServers.Autodetect()

        ' For performance sake, avoid making redundant TCP queries. UDP is enough with RBL.
        ' Also, the default 5000ms timeout can be too long.
        For Each dns As DnsServer In rbl.DnsServers
            dns.TryTcp = False
            dns.UdpTimeout = 500

            ' Or you can leave UdpRetryCount=2 (default), it will end up in increased times to check against dead/slow RBLs
            ' but the results will be more accurate.
            dns.UdpRetryCount = 1
        Next

        Console.WriteLine("Is in RBL: " & rbl.IsIPAddressInRbl("11.22.33.44", "zen.spamhaus.org").ToString())
    End Sub
End Class
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.IsIPAddressInRblAsync Method

RblFilterIsIPAddressInRblAsync Method
async/await version of IsIPAddressInRbl(String, String).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> IsIPAddressInRblAsync(
    string ipString,
    string rblHost
)
Public Function IsIPAddressInRblAsync (
    ipString As String,
    rblHost As String
) As Task(Of Boolean)

Parameters

ipString
Type: SystemString
The IPv4 address to check, as "11.22.33.44" string.
rblHost
Type: SystemString
The DNS RBL host name.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if this IP address is black-listed; othwerwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | ipString or rblHost is a null reference (Nothing in Visual Basic) or an empty string, or ipString does not denote a valid IPv4 address.
MailBeeException | Another error occurred (e.g. timeout from DNS server).
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.IsMailOriginatingIPAddressInRbl Method

RblFilterIsMailOriginatingIPAddressInRbl Method
Checks if the IP address the e-mail was received from is present in DNS RBL database.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsMailOriginatingIPAddressInRbl(
    MailMessage msg,
    int receivedIndex,
    string rblHost
)
Public Function IsMailOriginatingIPAddressInRbl (
    msg As MailMessage,
    receivedIndex As Integer,
    rblHost As String
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
A mail message with at least one Received header which contains the IP address the message came from.
receivedIndex
Type: SystemInt32
The zero-based index of Received header to examine. Usually, zero (denotes the most recent header).
rblHost
Type: SystemString
The RBL host name.

Return Value

Type: Boolean
true if the originating IP address is black-listed; othwerwise, false. false is also returned if no matching IPv4 address was found in the specified Received header.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg is a null reference (Nothing in Visual Basic), or rblHost is a null reference or an empty string, or receivedIndex is negative or does not denote a valid index in msg's TimeStamps collection.
MailBeeException | Another error occurred (e.g. timeout from DNS server).
Remarks

This method extracts the originating IP address from Received header and then uses IsIPAddressInRbl(String, String) method to check if this IP address is black-listed in the specified RBL.

Usually, the most recent Received header must be examined (receivedIndex must be zero). However, in case if mail flow in your network is more complex (e.g. all mail is forwarded through some gateway), you may need to analyze not the most recent Received but next to it. In this case, receivedIndex must be 1.

The header may look like Received: from [19.43.20.143] (helo=zebra.domain.com) by mx.afterlogic.com with esmtp (Exim 4.85) id 1ctx6r-119Hei-S8 for support@afterlogic.com; Fri, 31 Mar 2017 07:01:03 -0700.

In the above, 19.43.20.143 denotes the originating IP address.

To check against multiple RBLs or to get more details about the reason of black-listing of the IP address in question, use GetRblStatusesOfMailOriginatingIPAddress(MailMessage, Int32, String) method.

Examples
This example loads an e-mail from a file (you can also get it from a mail server) and checks if it's present in "zen.spamhaus.org" RBL blacklist. Default DNS performance settings are used. It's assumed the message has at least one Received header which contains the IP address the message originated from.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.DnsMX;
using MailBee.AntiSpam;

class Sample
{
    static void Main(string[] args)
    {
        RblFilter rbl = new RblFilter();

        // Logging is helpful for debugging.
        rbl.Log.Enabled = true;
        rbl.Log.Filename = @"C:\Temp\log.txt";
        rbl.Log.Clear();

        // RBL check needs DNS servers.
        rbl.DnsServers.Autodetect();

        // Grab some mail message to check. In production, you can get it from IMAP server or elsewhere.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\msg.eml");

        Console.WriteLine("Is in RBL: " + rbl.IsMailOriginatingIPAddressInRbl(msg, 0, "zen.spamhaus.org").ToString());
    }
}
Imports MailBee
Imports MailBee.Mime
Imports MailBee.DnsMX
Imports MailBee.AntiSpam

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim rbl As New RblFilter()

        ' Logging is helpful for debugging.
        rbl.Log.Enabled = True
        rbl.Log.Filename = "C:\Temp\log.txt"
        rbl.Log.Clear()

        ' RBL check needs DNS servers.
        rbl.DnsServers.Autodetect()

        ' Grab some mail message to check. In production, you can get it from IMAP server or elsewhere.
        Dim msg As New MailMessage()
        msg.LoadMessage("C:\Temp\msg.eml")

        Console.WriteLine("Is in RBL: " & rbl.IsMailOriginatingIPAddressInRbl(msg, 0, "zen.spamhaus.org").ToString())
    End Sub
End Class
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.IsMailOriginatingIPAddressInRblAsync Method

RblFilterIsMailOriginatingIPAddressInRblAsync Method
async/await version of IsMailOriginatingIPAddressInRbl(MailMessage, Int32, String).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> IsMailOriginatingIPAddressInRblAsync(
    MailMessage msg,
    int receivedIndex,
    string rblHost
)
Public Function IsMailOriginatingIPAddressInRblAsync (
    msg As MailMessage,
    receivedIndex As Integer,
    rblHost As String
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
A mail message with at least one Received header which contains the IP address the message came from.
receivedIndex
Type: SystemInt32
The zero-based index of Received header to examine. Usually, zero (denotes the most recent header).
rblHost
Type: SystemString
The RBL host name.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the originating IP address is black-listed; othwerwise, false. false is also set if no matching IPv4 address was found in the specified Received header.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg is a null reference (Nothing in Visual Basic), or rblHost is a null reference or an empty string, or receivedIndex is negative or does not denote a valid index in msg's TimeStamps collection.
MailBeeException | Another error occurred (e.g. timeout from DNS server).
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.OnDataReceived Method

RblFilterOnDataReceived Method
Used by MailBee to raise DataReceived event.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace
RblFilterDataReceived
SmtpOnConnected(ConnectedEventArgs)


RblFilter.OnDataSent Method

RblFilterOnDataSent Method
Used by MailBee to raise DataSent event.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataSent(
    DataTransferEventArgs args
)
Protected Sub OnDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace
RblFilterDataSent
SmtpOnConnected(ConnectedEventArgs)


RblFilter.OnErrorOccurred Method

RblFilterOnErrorOccurred Method
Used by MailBee to raise ErrorOccurred event.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnErrorOccurred(
    ErrorEventArgs args
)
Protected Sub OnErrorOccurred (
    args As ErrorEventArgs
)

Parameters

args
Type: MailBeeErrorEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace
RblFilterErrorOccurred


RblFilter.OnLogNewEntry Method

RblFilterOnLogNewEntry Method
Used by MailBee to raise LogNewEntry event.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLogNewEntry(
    LogNewEntryEventArgs args
)
Protected Sub OnLogNewEntry (
    args As LogNewEntryEventArgs
)

Parameters

args
Type: MailBeeLogNewEntryEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace
RblFilterLogNewEntry


RblFilter.ResetState Method

RblFilterResetState Method
Resets the internal state of the component.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ResetState()
Public Sub ResetState
Exceptions
Exception | Condition
MailBeeInvalidStateException | The component is busy. If you need to abort the currently performed operation, call Abort instead.
Remarks
This method will close any opened connections, and will remove IsAborted status if Abort method was previously called. Typically, the developer may use this method to reuse the component after it went into aborted state due to Abort method call.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter Properties

RblFilter Properties

The RblFilter type exposes the following members.

Properties
 | Name | Description
Public property | DnsServers | Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS RBL lookup.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MaxThreadCount | Gets or sets the maximum number of threads MailBee may create during RBL verification of IP addresses. operations.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | Site | Gets or sets the object to be used as a site for the component.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.DnsServers Property

RblFilterDnsServers Property
Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS RBL lookup.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServerCollection DnsServers { get; }
Public ReadOnly Property DnsServers As DnsServerCollection
    Get

Property Value

Type: DnsServerCollection
The DnsServerCollection object containing the list of DNS servers to be used for DNS RBL lookup.
Remarks

MailBee can auto-detect which DNS servers are available in the system. The developer can use Autodetect method to retrieve DNS settings from OS or from the config file.

If multiple DNS servers specified, MailBee will distribute load between the available DNS servers to improve performance (provided that multiple RBLs are requested). However, if some servers have lower Priority than others, they will not be tried unless primary servers fail.

See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace
MailBee.DnsMXDnsServer


RblFilter.IsAborted Property

RblFilterIsAborted Property
Indicates whether Abort method has been called for the component.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsAborted { get; }
Public ReadOnly Property IsAborted As Boolean
    Get

Property Value

Type: Boolean
true if Abort method has already been called; otherwise, false. The default value is false.
Remarks

In aborted state, the component does not raise any events, and most methods, if called, will immediately return an error or throw an exception.

See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.IsBusy Property

RblFilterIsBusy Property
Indicates whether the component is performing a lengthy operation.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBusy { get; }
Public ReadOnly Property IsBusy As Boolean
    Get

Property Value

Type: Boolean
A bool value indicating whether the component is busy because it's doing some work.
Remarks
When the component is busy, it's not possible to start another lengthy operation. For instance, if the component connects to the server or transfers data over the network, no other network operation can be started at this time. Any attempt to do so will result in MailBeeInvalidStateException.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.Log Property

RblFilterLog Property
Gets the object used for logging MailBee activities into a file or memory buffer.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Logger Log { get; }
Public ReadOnly Property Log As Logger
    Get

Property Value

Type: Logger
A reference to the object used for logging MailBee activities into a file or memory buffer.
Remarks

This property is never a null reference (Nothing in Visual Basic) even if logging is not used.

Note Note
In log files, IP addresses being checked appear in reversed form. E.g. if you check "11.22.33.44" against "rbl.org" RBL, the entry in the log file will look like "44.33.22.11.rbl.org". This is how RBL checking works.
Examples
This sample sets file logging on and sets the filename of the log file. It also configures the format of the log file to include the threading info. It's helpful in multi-threaded mode.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.AntiSpam;

// The actual code (put it into a method of your class)
RblFilter rbl = new RblFilter();
rbl.Log.Enabled = true;
rbl.Log.Filename = @"C:\Temp\log.txt";
rbl.Log.Format = LogFormatOptions.AddContextInfo;
rbl.Log.Clear();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.AntiSpam

' The actual code (put it into a method of your class)
Dim rbl As New RblFilter()
rbl.Log.Enabled = True
rbl.Log.Filename = "C:\Temp\log.txt"
rbl.Log.Format = LogFormatOptions.AddContextInfo
rbl.Log.Clear()
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.MaxThreadCount Property

RblFilterMaxThreadCount Property
Gets or sets the maximum number of threads MailBee may create during RBL verification of IP addresses. operations.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxThreadCount { get; set; }
Public Property MaxThreadCount As Integer
    Get
    Set

Property Value

Type: Int32
An integer value specifying the maximum number of threads MailBee may create during e-mail address verification operations, or -1 which specifies the number of threads is not limited. The default value is 1 (i.e. multi-threading is off).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is zero.
Remarks
Multi-threading greatly increases performance of validating IP addresses against multiple RBLs. The maximum thread count MailBee can utilize is 60 (although it's unlikely that you'll use so many RBLs).
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.RaiseEvents Property

RblFilterRaiseEvents Property
Gets or sets whether the component will raise any events.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEvents { get; set; }
Public Property RaiseEvents As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will raise any events. The default value is true.
Remarks
If this property is false, OnEventName methods will also not be called.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.Site Property

RblFilterSite Property
Gets or sets the object to be used as a site for the component.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual ISite Site { get; set; }
Public Overridable Property Site As ISite
    Get
    Set

Property Value

Type: ISite
A reference to the object to be used as a site for the component. The default value is a null reference (Nothing in Visual Basic).

Implements

IComponentSite
Remarks
The developer does not need to set this property. It's used by RAD tools such as form designers.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.SynchronizingObject Property

RblFilterSynchronizingObject Property
Gets or sets the object used to marshal the calls of the event handlers.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ISynchronizeInvoke SynchronizingObject { get; set; }
Public Property SynchronizingObject As ISynchronizeInvoke
    Get
    Set

Property Value

Type: ISynchronizeInvoke
A reference to the object on whose thread the events should be raised. The default value is a null reference (Nothing in Visual Basic) which tells MailBee to determine the appropriate marshalling object automatically.
Remarks
Usually, you do not need to set this property because MailBee can automatically marshal events to proper threads.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.TrialDaysLeft Property

RblFilterTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value which contains the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.Version Property

RblFilterVersion Property
Gets the version of the MailBee assembly.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter Events

RblFilter Events

The RblFilter type exposes the following members.

Events
 | Name | Description
 | DataReceived | Occurs when data is received from the network.
 | DataSent | Occurs when data is sent to the network.
Public event | Disposed | Occurs after the component was disposed.
Public event | ErrorOccurred | Occurs when MailBeeException is thrown internally.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if RblFilter.Log.MemoryLog is true).
Top
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.DataReceived Event

RblFilterDataReceived Event
Occurs when data is received from the network.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataReceived
Public Event DataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

This event is raised when the component receives a response a DNS server. The developer can use Protocol property to determine the protocol of the data just sent.

Note Note
This event is also raised when zero-length data is received from the server (for DNS TCP queries only). When a server sends zero-length data portion, it means the connection was closed.
Examples
DataReceived sample shows how to use this event for Smtp object. For RblFilter, usage pattern is the same.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.DataSent Event

RblFilterDataSent Event
Occurs when data is sent to the network.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataSent
Public Event DataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks
This event is raised when the component sends a request to a DNS server.
Examples
DataSent sample shows how to use this event for Smtp object. For RblFilter, usage pattern is the same.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.Disposed Event

RblFilterDisposed Event
Occurs after the component was disposed.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event EventHandler Disposed
Public Event Disposed As EventHandler

Value

Type: SystemEventHandler

Implements

IComponentDisposed
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.ErrorOccurred Event

RblFilterErrorOccurred Event
Occurs when MailBeeException is thrown internally.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ErrorEventHandler ErrorOccurred
Public Event ErrorOccurred As ErrorEventHandler

Value

Type: MailBeeErrorEventHandler
Remarks

When MailBee encounters any error, it throws the MailBeeException. However, in most cases MailBee itself traps this exception. For instance, if connecting to a certain SMTP server or making DNS MX lookup fails for a certain domain, MailBeeException is thrown and then trapped by MailBee itself, but no exception will be thrown to the application code. Instead, MailBee understands that the given e-mail address is invalid, and continues. Such errors are called warnings.

ErrorOccurred event allows the developer to track both warnings and critical errors because it's raised for a particular exception even if MailBee will trap this exception and do not pass it to the application code.

Note that not any occurrence of this event indicates that some e-mail address was considered invalid. For instance, if test SMTP connection to a primary SMTP MX server of some e-mail domain failed, this will raise ErrorOccurred event. But if this domain has secondary SMTP MX, MailBee will then try it too, and it the connection succeeds, the e-mail address will be considered OK.

Thus, ErrorOccurred event is mainly intended for informational and debugging purposes.

See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblFilter.LogNewEntry Event

RblFilterLogNewEntry Event
Occurs when an entry is written into the log file (or into the memory buffer if RblFilter.Log.MemoryLog is true).

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LogNewEntryEventHandler LogNewEntry
Public Event LogNewEntry As LogNewEntryEventHandler

Value

Type: MailBeeLogNewEntryEventHandler
Remarks

This event is raised only if logging is turned on (Enabled is true).

MailBee raises this event BEFORE adding the entry into the the log. Since many properties of NewEntry object are editable, the developer can change the data MailBee will put into the log or even cancel logging the current entry at all. This may be useful the developer wishes to log only those entires which meet certain criteria.

Note Note
Entries added by the developer (through WriteLine(String) method call) do not cause this event to be raised. Thus, it's safe to add user-defined log entries even in the LogNewEntry event handler itself. This does not cause endless recursion which would otherwise occur if WriteLine(String) method called in LogNewEntry event handler raised this event again.
Examples
LogNewEntry sample shows how to use this event for Smtp object. For RblFilter, usage pattern is the same.
See Also

Reference

RblFilter Class
MailBee.AntiSpam Namespace


RblStatus Class

RblStatus Class
Represents a status of an IP address in a DNS RBL database.
Inheritance Hierarchy
SystemObject
MailBee.AntiSpamRblStatus

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class RblStatus
Public Class RblStatus

The RblStatus type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | IsError | Denotes if an error occurred when making the DNS query to the RBL server.
Public property | IsIPAddressInRbl | Denotes if the IP address is blacklisted by the given DNS RBL.
Public property | RblHost | Gets the DNS RBL host name.
Public property | RblReplyText | Gets the reply from the DNS RBL with extra details regarding the reason of the IP address being blacklisted.
Top
Remarks

Methods like GetRblStatusesOfIPAddress(String, String) which query a number of RBLs regarding an IP address return a collection of RblStatus objects where each object represents a status for each RBL.

Examples
See example in GetRblStatusesOfMailOriginatingIPAddress(MailMessage, Int32, String) topic.
See Also

Reference

MailBee.AntiSpam Namespace


RblStatus Methods

RblStatus Methods

The RblStatus type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

RblStatus Class
MailBee.AntiSpam Namespace


RblStatus Properties

RblStatus Properties

The RblStatus type exposes the following members.

Properties
 | Name | Description
Public property | IsError | Denotes if an error occurred when making the DNS query to the RBL server.
Public property | IsIPAddressInRbl | Denotes if the IP address is blacklisted by the given DNS RBL.
Public property | RblHost | Gets the DNS RBL host name.
Public property | RblReplyText | Gets the reply from the DNS RBL with extra details regarding the reason of the IP address being blacklisted.
Top
See Also

Reference

RblStatus Class
MailBee.AntiSpam Namespace


RblStatus.IsError Property

RblStatusIsError Property
Denotes if an error occurred when making the DNS query to the RBL server.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsError { get; }
Public ReadOnly Property IsError As Boolean
    Get

Property Value

Type: Boolean
true if all attempts to make a DNS query to the RBL server failed; othwerwise, false.
Remarks

MailBee can make multiple attempts to request A record for the given IP address from the specified RBL (this involves UdpRetryCount, TryTcp, having multiple DNS servers in DnsServers collection). However, if all of the attempts failed, MailBee will give up and set IsError to true.

Note Note
In case if all RBLs failed (or only one RBL was requested), MailBee will throw an exception rather than return collection with all RblStatus objects in "error" state.
See Also

Reference

RblStatus Class
MailBee.AntiSpam Namespace


RblStatus.IsIPAddressInRbl Property

RblStatusIsIPAddressInRbl Property
Denotes if the IP address is blacklisted by the given DNS RBL.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsIPAddressInRbl { get; }
Public ReadOnly Property IsIPAddressInRbl As Boolean
    Get

Property Value

Type: Boolean
true if the given IP address is blacklisted, false if the IP address is not on the blacklist or there was an error during the DNS query.
See Also

Reference

RblStatus Class
MailBee.AntiSpam Namespace


RblStatus.RblHost Property

RblStatusRblHost Property
Gets the DNS RBL host name.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RblHost { get; }
Public ReadOnly Property RblHost As String
    Get

Property Value

Type: String
The DNS RBL database host name. Cannot be a null reference (Nothing in Visual Basic) or an empty string.
See Also

Reference

RblStatus Class
MailBee.AntiSpam Namespace


RblStatus.RblReplyText Property

RblStatusRblReplyText Property
Gets the reply from the DNS RBL with extra details regarding the reason of the IP address being blacklisted.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RblReplyText { get; }
Public ReadOnly Property RblReplyText As String
    Get

Property Value

Type: String
The contents of A record which is associated with the given IP address in the specified RBL, or a null reference (Nothing in Visual Basic) if not available.
Remarks

This value can only be available if IsIPAddressInRbl is true (the IP address is blacklisted). If the IP is blacklisted, this means the corresponding A record does exist for the given IP address. This property returns the contents of this record (in the form of an IPv4 address, usually something like "127.0.0.3", etc).

The exact meaning of these records depends on each particular RBL. Refer to your RBL documentation to find out more. For instance, return codes of the popular Spamhaus Zen RBL can be found at https://www.spamhaus.org/zen/.

Note Note
The IP address string returned by this property does not denote any real IP address. It's just the requirement that A records must represent IP addresses. So treat them just like error codes.
See Also

Reference

RblStatus Class
MailBee.AntiSpam Namespace


RblStatusCollection Class

RblStatusCollection Class
Provides properties and methods for examining the collection of RblStatus objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.AntiSpamRblStatusCollection

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class RblStatusCollection : CollectionBase
Public Class RblStatusCollection
    Inherits CollectionBase

The RblStatusCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | IsInRbls | Returns true if at least one IsIPAddressInRbl value in the collection is true.
Public property | Item | Gets the RblStatus object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.AntiSpam Namespace


RblStatusCollection Methods

RblStatusCollection Methods

The RblStatusCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

RblStatusCollection Class
MailBee.AntiSpam Namespace


RblStatusCollection Properties

RblStatusCollection Properties

The RblStatusCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | IsInRbls | Returns true if at least one IsIPAddressInRbl value in the collection is true.
Public property | Item | Gets the RblStatus object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

RblStatusCollection Class
MailBee.AntiSpam Namespace


RblStatusCollection.IsInRbls Property

RblStatusCollectionIsInRbls Property
Returns true if at least one IsIPAddressInRbl value in the collection is true.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsInRbls { get; }
Public ReadOnly Property IsInRbls As Boolean
    Get

Property Value

Type: Boolean
true if the collection contains at least one item whose IsIPAddressInRbl is true; otherwise, false.
Remarks
You can use this property to quickly check if the IP address in question was found in at least one RBL.
See Also

Reference

RblStatusCollection Class
MailBee.AntiSpam Namespace


RblStatusCollection.Item Property

RblStatusCollectionItem Property
Gets the RblStatus object at the specified zero-based index in the collection.

Namespace: MailBee.AntiSpam
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RblStatus this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As RblStatus
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the RblStatus object in the collection.

Property Value

Type: RblStatus
An RblStatus object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

RblStatusCollection Class
MailBee.AntiSpam Namespace


MailBee.BounceMail Namespace

MailBee.BounceMail Namespace

MailBee.BounceMail namespace provides classes and enumerations which can be used to process bounce e-mails, delivery confirmations and any other Delivery Status Notification (DSN) messages.

BounceMail feature is only supported in classic .NET Framework and .NET Standard 2.0 compatible environments (.NET Core 2.0 and newer, UWP for Windows 10 Fall Creators Update and newer) . It's not available for .NET Core 1.0/1.1 and older UWP versions.

DSN messages come in different formats and may contain information about the status of delivery of certain e-mail sent in the past (the original message) to certain recipients of that e-mail. MailBee can extract this information and present it to you in easy-to-use object model form.

Typical usage is to download e-mails from a mailbox using Pop3 or Imap component and then examine these e-mails using DeliveryStatusParser.Process method to find delivery or non-delivery reports.

Result object returned by DeliveryStatusParser.Process method contains all the DSN-related information extracted from the e-mail message. In particular, Result.Recipients collection returns the delivery statuses for all recipients listed in the DSN message.

Classes
 | Class | Description
 | DeliveryStatusParser | Provides a method for examining e-mail messages for delivery or non-delivery notifications.
 | DsnAttachment | Represents a Delivery Status Notification attachment in RFC 1894 format.
 | DsnRecipient | Contains the delivery status and other details for a single recipient listed in the DSN attachment.
Public class | DsnRecipientCollection | Represents a collection of delivery status information objects for all recipients listed in the DSN attachment.
 | RecipientStatus | Represents the delivery results for a particular recipient's e-mail address.
Public class | RecipientStatusCollection | Represents a collection of delivery status information objects for all recipients listed in the DSN message.
 | Result | Represents the result checking an e-mail message for delivery status notification (DSN) entries.
Enumerations
 | Enumeration | Description
Public enumeration | CommonType | Defines the general types of delivery statuses in delivery notification messages.
Public enumeration | DetailedType | Defines the extended types of delivery notification messages.
Public enumeration | DsnAction | Defines actions which have been performed by the Reporting-MTA as a result of its attempt to deliver the message to the recipient.
Public enumeration | RecipientStatusSource | Defines from which parts of the DSN message MailBee should load RecipientStatus object.


CommonType Enumeration

CommonType Enumeration
Defines the general types of delivery statuses in delivery notification messages.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum CommonType
Public Enumeration CommonType
Members
Member name | Value | Description
Undeliverable | 0 | The message was not delivered to the recipient.
Blocked | 1 | The message was blocked by the client side.
Information | 2 | An informational notification was issued to the sender.
Warning | 3 | Mail transfer software issued a warning while delivering the message.
Receipt | 4 | The receipt generated after delivering the message.
UserDefined | 5 | You can find the type of the delivery notification message using ResultItem.UserDefined property.
Unknown | 6 | An unknown notification message.
Remarks

Since a delivery status notification (DSN) message may contain delivery reports for multiple recipients of the original e-mail message, the delivery status might be available for each recipient separately.

To determine if an e-mail is a bounce (non-delivery report) for the given recipient, use Common or IsBounced properties if you have RecipientStatus object for that recipient.

Process(MailMessage) method returns the collection of RecipientStatus objects in Recipients property. This collection contains delivery statuses for all recipients in the DSN message. To get the e-mail address of the particular recipient, use EmailAddress property of the RecipientStatus object. For autoreply messages, it can be not available and you'll need to use From property.

If, for some reason, you are using DsnRecipient class instead of RecipientStatus, you can use Action property to learn the delivery status. Action property uses values of DsnAction type which provides DSN statuses exactly as they are specified in the DSN attachment of the DSN message. Action property value won't be available in the case if the DSN message does not have a DSN attachment (see DsnAttachment topic for details). Common property is more general. If Action is available, MailBee initializes Common from it. If the message does not have a DSN attachment (and Action is not available), MailBee extracts this information from the message body.

See Also

Reference

MailBee.BounceMail Namespace
RecipientStatusCommon
RecipientStatusIsBounced
DsnRecipientAction


DeliveryStatusParser Class

DeliveryStatusParser Class
Provides a method for examining e-mail messages for delivery or non-delivery notifications.
Inheritance Hierarchy
SystemObject
MailBee.BounceMailDeliveryStatusParser

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DeliveryStatusParser
Public Class DeliveryStatusParser

The DeliveryStatusParser type exposes the following members.

Constructors
Name | Description
DeliveryStatusParser(Byte) | Loads DSN XML templates database from XML data and creates DeliveryStatusParser object.
DeliveryStatusParser(String, Boolean) | Loads DSN XML templates database from a set of XML files and creates DeliveryStatusParser object.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Process | Examines the specified MailMessage for delivery status notification (DSN) and returns its details.
Public method | ProcessWithTimeout | Examines the specified MailMessage for delivery status notification (DSN) and returns its details, limiting the amount of time to process each bounce format.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Remarks

This is the main class in the namespace. It provides facilities for extracting DSN information from e-mails.

Note Note
This class is not supported in .NET Core and UWP apps yet.

The delivery status notification (DSN) is a reply from the recipient's mail software to the original message sender. This reply contains the mail delivery status of the original message: delivered successfully or bounced (failed, temporary undelivered, virus found or message treated as SPAM, etc).

Typical usage of this class if for mass mailing: you can easily detect e-mail addresses which could not receive e-mails and remove such addresses from your database to prevent further sending to these addresses. You can also track delivery (or non-deivery) of important e-mails.

To test whether the e-mail message is a delivery notification and examine its details, use Process(MailMessage) method.

If you send e-mails with Smtp component and then process bounces with DeliveryStatusParser, you can tune how destination mail servers should return bounces back to you by setting properties of DeliveryNotification object prior to sending an e-mail. For instance, you can set TrackingID for outgoing messages and then look for this ID in bounced messages using OriginalEnvelopeID property.

Note Note
There is no single standard of DSN messages. Instead, there are many hundreds of them, and new ones appear all the time. MailBee stores DSN formats as XML database where each entry is a template of a DSN message. By default, DSN templates database is installed in BounceDatabase folder of MailBee.NET Objects installation (for instance, C:\Program Files\MailBee.NET Objects\BounceDatabase). If you encounter a format which is not supported by the current database, contact us so that we would be able to update the database.

MailBee supports two formats of bounce database: folder tree of .XML files (where all.xml is root) and a single .xdb file. Single file is easier to use while "folder tree" version is easier to modify. .xdb version also supports loading from other storage, not just file. See DeliveryStatusParser(Byte) for details. "Folder tree" version, on other hand, supports loading multiple databases (e.g. standard and custom databases) at once. In most cases, .xdb is more convenient.

Examples

This sample tests all e-mails in the folder whether they are bounced messages and extracts all failed e-mail addresses contained in each bounced message.

It's assumed the e-mail samples are .EML files located in C:\Temp\IncomingMail folder. The DSN formats database resides in C:\Temp\BounceDatabase\bouncedatabase.xdb file.

This sample focuses on bounced messages. Autoreply messages is a special case, see notes in EmailAddress topic on how to extract email address for out-of-office replies.

C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.BounceMail;

class Sample
{
    static void Main(string[] args)
    {
        // Load the templates database from file(s).
        DeliveryStatusParser parser = new DeliveryStatusParser(File.ReadAllBytes(@"C:\Temp\BounceDatabase\bouncedatabase.xdb"));

        string[] files = Directory.GetFiles(@"C:\Temp\IncomingMail", "*.eml");
        MailMessage msg = new MailMessage();

        // Check if e-mails are DSNs.
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            Result result = parser.Process(msg);

            Console.WriteLine("\r\nProcessed e-mail: " + file);

            if (result == null)
            {
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("This message is not a bounce.");
                Console.WriteLine("------------------------------------------------------");
            }
            else
            {
                // Get header params from the original e-mail message (for which this bounced message was sent).
                if (result.OriginalMessage != null)
                {
                    Console.WriteLine("-------------- Original message headers ------------");
                    Console.WriteLine("\tTo:     \t" + result.OriginalMessage.To.AsString);
                    Console.WriteLine("\tFrom:   \t" + result.OriginalMessage.From.AsString);
                    Console.WriteLine("\tSubject:\t" + result.OriginalMessage.Subject);
                    Console.WriteLine("----------------------------------------------------");
                }

                // Get the details for each e-mail address listed in the bounce.
                foreach (RecipientStatus res in result.Recipients)
                {
                    Console.WriteLine("E-mail address: \t" + res.EmailAddress);
                    Console.WriteLine("Status:         \tis " + (res.IsBounced ? "bounced" : "delivered successfully"));

                    Console.WriteLine("Common reason:  \t" + res.Common.ToString());
                    Console.WriteLine("Detailed reason:\t" + res.Detailed.ToString());
                    Console.WriteLine("Description:    \t" + res.Description);
                }
            }
        }
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports Microsoft.VisualBasic
Imports MailBee.Mime
Imports MailBee.BounceMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Load the templates database from file(s).
        Dim parser As DeliveryStatusParser = New DeliveryStatusParser(File.ReadAllBytes("C:\Temp\BounceDatabase\bouncedatabase.xdb"))

        Dim files() As String = Directory.GetFiles("C:\Temp\IncomingMail", "*.eml")
        Dim msg As MailMessage = New MailMessage

        ' Check if e-mails are DSNs.
        For Each file As String In files
            msg.LoadMessage(file)
            Dim result As Result = parser.Process(msg)

            Console.WriteLine(ControlChars.CrLf & "Processed e-mail: " & file)

            If result Is Nothing Then
                Console.WriteLine("------------------------------------------------------")
                Console.WriteLine("This message is not a bounce.")
                Console.WriteLine("------------------------------------------------------")
            Else
                ' Get header params from the original e-mail message (for which this bounced message was sent).
                If Not result.OriginalMessage Is Nothing Then
                    Console.WriteLine("-------------- Original message headers ------------")
                    Console.WriteLine(ControlChars.Tab & "To:     " & ControlChars.Tab & result.OriginalMessage.To.AsString)
                    Console.WriteLine(ControlChars.Tab & "From:   " & ControlChars.Tab & result.OriginalMessage.From.AsString)
                    Console.WriteLine(ControlChars.Tab & "Subject:" & ControlChars.Tab & result.OriginalMessage.Subject)
                    Console.WriteLine("----------------------------------------------------")
                End If

                ' Get the details for each e-mail address listed in the bounce.
                For Each res As RecipientStatus In result.Recipients
                    Console.WriteLine("E-mail address: " & ControlChars.Tab & res.EmailAddress)
                    Console.Write("Status:         " & ControlChars.Tab & "is ")
                    If res.IsBounced Then Console.WriteLine("bounced") Else Console.WriteLine("delivered successfully")

                    Console.WriteLine("Common reason:  " & ControlChars.Tab & res.Common.ToString())
                    Console.WriteLine("Detailed reason:" & ControlChars.Tab & res.Detailed.ToString())
                    Console.WriteLine("Description:    " & ControlChars.Tab & res.Description)
                Next
            End If
        Next
    End Sub
End Class
See Also

Reference

MailBee.BounceMail Namespace


DeliveryStatusParser Constructor

DeliveryStatusParser Constructor
Overload List
Name | Description
DeliveryStatusParser(Byte) | Loads DSN XML templates database from XML data and creates DeliveryStatusParser object.
DeliveryStatusParser(String, Boolean) | Loads DSN XML templates database from a set of XML files and creates DeliveryStatusParser object.
Top
See Also

Reference

DeliveryStatusParser Class
MailBee.BounceMail Namespace


DeliveryStatusParser Constructor (Byte[])

DeliveryStatusParser Constructor (Byte)
Loads DSN XML templates database from XML data and creates DeliveryStatusParser object.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryStatusParser(
    byte[] xmlDatabase
)
Public Sub New (
    xmlDatabase As Byte()
)

Parameters

xmlDatabase
Type: SystemByte
Byte array in .xdb format.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | xmlDatabase is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
.xdb file joins the contents of multiple XML files into one. This overload lets you use a single .xdb file as bounce database or load it from the resources of your application. Also, you can load the file asynchronously.
Examples
This code snippet reads the .xdb file and initializes the DeliveryStatusParser.
C#
VB
Copy
DeliveryStatusParser parser = new DeliveryStatusParser(File.ReadAllBytes(@"C:\Program Files\MailBee.NET Objects\BounceDatabase\bouncedatabase.xdb"));
Dim parser As New DeliveryStatusParser(File.ReadAllBytes("C:\Program Files\MailBee.NET Objects\BounceDatabase\bouncedatabase.xdb"))
See Also

Reference

DeliveryStatusParser Class
DeliveryStatusParser Overload
MailBee.BounceMail Namespace


DeliveryStatusParser Constructor (String, Boolean)

DeliveryStatusParser Constructor (String, Boolean)
Loads DSN XML templates database from a set of XML files and creates DeliveryStatusParser object.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryStatusParser(
    string databaseLocations,
    bool allowFailedDatabases
)
Public Sub New (
    databaseLocations As String,
    allowFailedDatabases As Boolean
)

Parameters

databaseLocations
Type: SystemString
The semicolon-separated list of full or relative paths to the database files.
allowFailedDatabases
Type: SystemBoolean
If false, this method will throw MailBeeIOException when at least one database could not be loaded; otherwise, the exception will be thrown only if all databases failed to load. Has no effect if only one database file was specified in databaseLocations.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | databaseLocations is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | Could not load the database file(s).
Remarks

MailBee is shipped with a set of database files located in BounceDatabase folder of MailBee.NET Objects installation. "all.xml" file is the root file of this database and therefore should be specified as databaseLocations value. Thus, the typical databaseLocations path is somewhat like C:\Program Files\MailBee.NET Objects\BounceDatabase\all.xml.

It's also possible to create user-defined databases and use multiple databases. databaseLocations format is the same as Microsoft Windows environment PATH variable. (i.e. "Path1;Path2;...;PathN"). You can change the order of processing templates from different databases by changing the order in which databases are listed in databaseLocations value.

Note Note
If you're using the default bounce templates database in your application which will be redistributed, you should include all the contents of BounceDatabase folder with your application. Redistributing all.xml file is not enough as it contains references to other files and sub-folders in BounceDatabase folder.
Examples
The example is available in DeliveryStatusParser topic.
See Also

Reference

DeliveryStatusParser Class
DeliveryStatusParser Overload
MailBee.BounceMail Namespace
DeliveryStatusParserProcess(MailMessage)


DeliveryStatusParser Methods

DeliveryStatusParser Methods

The DeliveryStatusParser type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Process | Examines the specified MailMessage for delivery status notification (DSN) and returns its details.
Public method | ProcessWithTimeout | Examines the specified MailMessage for delivery status notification (DSN) and returns its details, limiting the amount of time to process each bounce format.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DeliveryStatusParser Class
MailBee.BounceMail Namespace


DeliveryStatusParser.Process Method

DeliveryStatusParserProcess Method
Examines the specified MailMessage for delivery status notification (DSN) and returns its details.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Result Process(
    MailMessage message
)
Public Function Process (
    message As MailMessage
) As Result

Parameters

message
Type: MailBee.MimeMailMessage
The MailMessage object to be examined.

Return Value

Type: Result
DSN details extracted from the specified e-mail message, or a null reference (Nothing in Visual Basic) if the message does not contain any DSN.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic)
Remarks
It's possible that the message is DSN of rare format which is not yet known to MailBee. In this case, contact us so that we would be able to add this format into DSN template database.
Examples
The example is available in DeliveryStatusParser topic.
See Also

Reference

DeliveryStatusParser Class
MailBee.BounceMail Namespace


DeliveryStatusParser.ProcessWithTimeout Method

DeliveryStatusParserProcessWithTimeout Method
Examines the specified MailMessage for delivery status notification (DSN) and returns its details, limiting the amount of time to process each bounce format.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Result ProcessWithTimeout(
    MailMessage message,
    int timeout
)
Public Function ProcessWithTimeout (
    message As MailMessage,
    timeout As Integer
) As Result

Parameters

message
Type: MailBee.MimeMailMessage
The MailMessage object to be examined.
timeout
Type: SystemInt32
Maximum timeout in milliseconds to get response for one template. In most cases, value of 300 is enough. You may increase it for very slow systems.

Return Value

Type: Result
DSN details extracted from the specified e-mail message, or a null reference (Nothing in Visual Basic) if the message does not contain any DSN.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic) or timeout is less than 0.
Remarks
This is a workaround method can be used in rare cases when the standard method Process(MailMessage) takes too long time if it encounters a specific bounce e-mail which is hard to process with the current regular expression (each bounce format is represented by a regular expression). In such cases, the method simply aborts the current regular expression check and continues to the next one. No exception is thrown.
See Also

Reference

DeliveryStatusParser Class
MailBee.BounceMail Namespace


DetailedType Enumeration

DetailedType Enumeration
Defines the extended types of delivery notification messages.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum DetailedType
Public Enumeration DetailedType
Members
Member name | Value | Description
Hard | 0 | Hard bounce. The message could not be delivered to the recipient and it's not worth trying to resend it later.
Soft | 1 | Soft bounce. The message was not delivered to the recipient this time, but you can retry to deliver it later.
Spam | 2 | The message is treated as spam.
Virus | 3 | The message contains a virus.
ChallengeResponse | 4 | A challenge response was issued to check whether the original message was sent by a human rather than by a spam robot. You should follow the instructions in the bounce message to confirm delivery of the original message.
OtherBlocked | 5 | The message was blocked for undefined reason.
AutoReply | 6 | This notification contains auto-reply to the original message.
AddressChanged | 7 | The recepient address was changed. Please update your address book.
Modified | 8 | The message was modified.
Forwarded | 9 | The message was forwarded.
Subscribe | 10 | The notification on subscription event.
Unsubscribe | 11 | The notification on unsubscription event.
Temporary | 12 | The message is still not delivered to the recipient but you should not yet attempt to resend it because the mail server will retry to resend it later.
Delivered | 13 | The message was successfully delivered to the recepient.
Read | 14 | The message was read by the recepient.
UserDefined | 15 | You can find the type of the delivery notification message using ResultItem.UserDefined property.
Unknown | 16 | An unknown notification message.
Remarks
This is more detailed version of CommonType. To obtain the extended status of the delivery to certain recipient, use Detailed property of RecipientStatus object which corresponds to the given recipient. See CommonType topic for more information on how to obtain RecipientStatus object for the given recipient.
See Also

Reference

MailBee.BounceMail Namespace
MailBee.BounceMailCommonType
MailBee.BounceMailDsnAction


DsnAction Enumeration

DsnAction Enumeration
Defines actions which have been performed by the Reporting-MTA as a result of its attempt to deliver the message to the recipient.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum DsnAction
Public Enumeration DsnAction
Members
Member name | Value | Description
Failed | 0 | The message could not be delivered to the recipient.
Delayed | 1 | The Reporting MTA has so far been unable to deliver or relay the message, but it will continue attempting to do that.
Delivered | 2 | The message was successfully delivered to the recipient.
Relayed | 3 | The message has been relayed or gatewayed.
Expanded | 4 | The recipient list has been expanded.
Unknown | 5 | An unknown DSN action has occurred.
Remarks
Reporting MTA is the one which is reporting the results of delivery attempts described in this DSN. See ReportingMtaType topic for details.
See Also

Reference

MailBee.BounceMail Namespace


DsnAttachment Class

DsnAttachment Class
Represents a Delivery Status Notification attachment in RFC 1894 format.
Inheritance Hierarchy
SystemObject
MailBee.BounceMailDsnAttachment

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DsnAttachment
Public Class DsnAttachment

The DsnAttachment type exposes the following members.

Constructors
 | Name | Description
Public method | DsnAttachment | Creates a new instance of DsnAttachment class from the specified attachment.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns the DSN attachment contents as a string. (Overrides ObjectToString.)
Top
Properties
 | Name | Description
Public property | ArrivalDate | Gets the message arrival date.
Public property | ArrivalDateAsString | Gets the message arrival date as string.
Public property | DsnGatewayName | Gets the DSN gateway name.
Public property | DsnGatewayType | Gets the DSN gateway type.
 | Items | Gets the list of all fields in the DSN attachment.
Public property | OriginalEnvelopeID | Gets the original envelope ID.
Public property | ReceivedFromMtaName | Gets the name of the MTA from which the message was received.
Public property | ReceivedFromMtaType | Gets the type of the MTA from which the message was received.
Public property | Recipients | Gets the list of the delivery statuses of the original e-mail message to its recipients.
Public property | ReportingMtaName | Gets the reporting MTA name.
Public property | ReportingMtaType | Gets the reporting MTA type.
Top
Remarks

Although there is no single standard for Delivery Status Notification (DSN), the format described in RFC 1894 is the most popular. Also, many bounced messages of proprietary formats include RFC 1894 DSN as attachment. This means a bounced message can contain duplicated information: in the main body and in RFC 1894 DSN attachment.

Thus, a DSN message may include or not include DSN attachment. DsnAttachment object deals with DSN attachments only.

In most cases, there is no need to create DsnAttachment directly. You can use Process(MailMessage) method and examine each RecipientStatus of Recipients collection of the returned Result object.

RecipientStatus object provides DsnInfo property which returns DsnAttachment object (if the message includes a DSN attachment). For instance, you can use it to get OriginalEnvelopeID of the message.

You may, however, need to create DsnAttachment object manually if you got RFC 1894 DSN data from another source, not from MailMessage object.

The most important properties are Recipients (which contains delivery status and other details for each recipient listed in the DSN) and Items which provides direct access to all fields of the DSN.

Examples
This sample converts a MimePart into DsnAttachment object and displays some of its properties. For brevity, we assume MimePart object is already available to the application. For instance, you can create it from byte array using Parse(Byte) method.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.BounceMail;

class Sample
{
    static void Main(string[] args)
    {
        // Assume that MimePart object is already set.
        MimePart part = ...;

        DsnAttachment dsnAttach = new DsnAttachment(new Attachment(part), null);

        Console.WriteLine("------------------ DSN attachment as text ------------------");
        Console.WriteLine(dsnAttach.ToString());
        Console.WriteLine("--------------- DSN headers as StringDictionary ------------");
        foreach (string key in dsnAttach.Items.Keys)
        {
            Console.WriteLine("DSN item: {0} = {1}", key, dsnAttach.Items[key]);
        }
        Console.WriteLine("------------------------------------------------------------");
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports System.IO
Imports MailBee.Mime
Imports MailBee.BounceMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Assume that MimePart object is already set.
        Dim part As MimePart = ...

        Dim dsnAttach As DsnAttachment = New DsnAttachment(New Attachment(part), Nothing)

        Console.WriteLine("------------------ DSN attachment as text ------------------")
        Console.WriteLine(dsnAttach.ToString())
        Console.WriteLine("--------------- DSN headers as StringDictionary ------------")
        For Each key As String In dsnAttach.Items.Keys
            Console.WriteLine("Dsn item: {0} = {1}", key, dsnAttach.Items(key))
        Next
        Console.WriteLine("------------------------------------------------------------")
    End Sub
End Class
See Also

Reference

MailBee.BounceMail Namespace
MailBee.BounceMailDsnRecipient


DsnAttachment Constructor

DsnAttachment Constructor
Creates a new instance of DsnAttachment class from the specified attachment.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnAttachment(
    Attachment dsnAttach,
    Encoding enc
)
Public Sub New (
    dsnAttach As Attachment,
    enc As Encoding
)

Parameters

dsnAttach
Type: MailBee.MimeAttachment
The attachment containing DSN data.
enc
Type: System.TextEncoding
The encoding to use for decoding the attachment data from bytes to strings. If a null reference (Nothing in Visual Basic), the encoding will be determined from the attachment header (Attachment.AsMimePart.Charset).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | dsnAttach is a null reference or its Content-Type is not "message/delivery-status" (not a DSN).
Remarks
This constructor is useful if you need to create DsnAttachment object from arbitrary data, not from MailMessage object. See DsnAttachment class description for details.
See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment Methods

DsnAttachment Methods

The DsnAttachment type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns the DSN attachment contents as a string. (Overrides ObjectToString.)
Top
See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment.ToString Method

DsnAttachmentToString Method
Returns the DSN attachment contents as a string.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
A string containing the DSN attachment body.
See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment Properties

DsnAttachment Properties

The DsnAttachment type exposes the following members.

Properties
 | Name | Description
Public property | ArrivalDate | Gets the message arrival date.
Public property | ArrivalDateAsString | Gets the message arrival date as string.
Public property | DsnGatewayName | Gets the DSN gateway name.
Public property | DsnGatewayType | Gets the DSN gateway type.
 | Items | Gets the list of all fields in the DSN attachment.
Public property | OriginalEnvelopeID | Gets the original envelope ID.
Public property | ReceivedFromMtaName | Gets the name of the MTA from which the message was received.
Public property | ReceivedFromMtaType | Gets the type of the MTA from which the message was received.
Public property | Recipients | Gets the list of the delivery statuses of the original e-mail message to its recipients.
Public property | ReportingMtaName | Gets the reporting MTA name.
Public property | ReportingMtaType | Gets the reporting MTA type.
Top
See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment.ArrivalDate Property

DsnAttachmentArrivalDate Property
Gets the message arrival date.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime ArrivalDate { get; }
Public ReadOnly Property ArrivalDate As DateTime
    Get

Property Value

Type: DateTime
A DateTime value of the message arrival moment from "Arrival-Date" DSN field, or MinValue if no such field contained in the DSN.
Remarks

This field indicates the date and time at which the message arrived at the Reporting MTA.

In this example, DSN field is:
Arrival-Date: Wed, 8 Feb 2010 20:01:10 +0000
The return value will be defined from the text marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentArrivalDateAsString


DsnAttachment.ArrivalDateAsString Property

DsnAttachmentArrivalDateAsString Property
Gets the message arrival date as string.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ArrivalDateAsString { get; }
Public ReadOnly Property ArrivalDateAsString As String
    Get

Property Value

Type: String
A string value of the message arrival moment from "Arrival-Date" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field contains string with the date and time at which the message arrived at the Reporting MTA.

In this example, DSN field is:
Arrival-Date: Wed, 8 Feb 2010 20:01:10 +0000
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentArrivalDate


DsnAttachment.DsnGatewayName Property

DsnAttachmentDsnGatewayName Property
Gets the DSN gateway name.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DsnGatewayName { get; }
Public ReadOnly Property DsnGatewayName As String
    Get

Property Value

Type: String
A string representaion of the message gateway name from "DSN-Gateway" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field indicates the name of the gateway or MTA which translated a foreign (non-Internet) delivery status notification into this DSN. This field MUST appear in any DSN which was translated by a gateway from a foreign system into DSN format, and MUST NOT appear otherwise.

In this example, DSN field is:
DSN-Gateway: dns; gateway.home.local
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentDsnGatewayType


DsnAttachment.DsnGatewayType Property

DsnAttachmentDsnGatewayType Property
Gets the DSN gateway type.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DsnGatewayType { get; }
Public ReadOnly Property DsnGatewayType As String
    Get

Property Value

Type: String
A string representaion of the message gateway type from "DSN-Gateway" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field indicates the type of the gateway or MTA which translated a foreign (non-Internet) delivery status notification into this DSN. This field MUST appear in any DSN which was translated by a gateway from a foreign system into DSN format, and MUST NOT appear otherwise.

In this example, DSN field is:
DSN-Gateway: dns; gateway.home.local
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentDsnGatewayName


DsnAttachment.Items Property

DsnAttachmentItems Property
Gets the list of all fields in the DSN attachment.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary Items { get; }
Public ReadOnly Property Items As StringDictionary
    Get

Property Value

Type: StringDictionary
The key-value string collection of all the fields in the DSN attachment.
Remarks
This collection is alternative to other properties of DsnAttachment class. Other properties (like ArrivalDate) return the corresponding value in parsed form. Items property provides access to all the fields as they are specified in the DSN source. It can also be used to extract those values which are not available through other properties (for instance, vendor-specific properties which are not defined by RFC 1894).
Examples
This code sample shows how to operate with parsed DSN data.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.BounceMail;

class Sample
{
    static void Main(string[] args)
    {
        // Load DSN templates database from file.
        DeliveryStatusParser parser = new DeliveryStatusParser(@"C:\Temp\BounceDatabase\all.xml", true);

        string[] files = Directory.GetFiles(@"C:\Temp\IncomingMail", "*.eml");
        MailMessage msg = new MailMessage();

        // Process all .EML files in the folder.
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            Result result = parser.Process(msg);

            Console.WriteLine("\r\nProcessed e-mail: " + file);

            if (result == null || result.DsnStructure == null)
            {
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("This message doesn't have DSN message part.");
                Console.WriteLine("------------------------------------------------------");
            }
            else
            {
                Console.WriteLine("------------------ DSN part as text ------------------");
                Console.WriteLine(result.DsnStructure.ToString());
                Console.WriteLine("------------- DSN header as StringDictionary ---------");
                foreach (string key in result.DsnStructure.Items.Keys)
                {
                    Console.WriteLine("DSN item: {0} = {1}", key, result.DsnStructure.Items[key]);
                }
                Console.WriteLine("------------------------------------------------------");

                foreach (RecipientStatus res in result.Recipients)
                {
                    if (res.DsnInfo != null)
                    {
                        Console.WriteLine("DSN subpart for: {0} e-mail", res.EmailAddress);
                        Console.WriteLine("---------------- DSN subpart as text -----------------");
                        Console.WriteLine(res.DsnInfo.ToString());
                        Console.WriteLine("------------- DSN header as StringDictionary ---------");
                        foreach (string key in res.DsnInfo.Items.Keys)
                        {
                            Console.WriteLine("DSN subpart item: {0} = {1}", key, res.DsnInfo.Items[key]);
                        }
                        Console.WriteLine("------------------------------------------------------");
                    }
                }
            }
        }
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports Microsoft.VisualBasic
Imports MailBee.Mime
Imports MailBee.BounceMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Load DSN templates database from file.
        Dim parser As DeliveryStatusParser = New DeliveryStatusParser("C:\Temp\BounceDatabase\all.xml", True)

        Dim files() As String = Directory.GetFiles("C:\Temp\IncomingMail", "*.eml")
        Dim msg As MailMessage = New MailMessage

        ' Process all .EML files in the folder.
        For Each file As String In files
            msg.LoadMessage(file)
            Dim result As Result = parser.Process(msg)

            Console.WriteLine(ControlChars.CrLf & "Processed e-mail: " & file)

            If result Is Nothing Or result.DsnStructure Is Nothing Then
                Console.WriteLine("------------------------------------------------------")
                Console.WriteLine("This message doesn't have DSN message part.")
                Console.WriteLine("------------------------------------------------------")
            Else
                Console.WriteLine("------------------ DSN part as text ------------------")
                Console.WriteLine(result.DsnStructure.ToString())
                Console.WriteLine("------------- DSN header as StringDictionary ---------")
                For Each key As String In result.DsnStructure.Items.Keys
                    Console.WriteLine("DSN item: {0} = {1}", key, result.DsnStructure.Items(key))
                Next
                Console.WriteLine("------------------------------------------------------")

                For Each res As RecipientStatus In result.Recipients
                    If Not res.DsnInfo Is Nothing Then
                        Console.WriteLine("DSN subpart for: {0} e-mail", res.EmailAddress)
                        Console.WriteLine("---------------- DSN subpart as text -----------------")
                        Console.WriteLine(res.DsnInfo.ToString())
                        Console.WriteLine("------------- DSN header as StringDictionary ---------")
                        For Each key As String In res.DsnInfo.Items.Keys
                            Console.WriteLine("DSN subpart item: {0} = {1}", key, res.DsnInfo.Items(key))
                        Next
                        Console.WriteLine("------------------------------------------------------")
                    End If
                Next
            End If
        Next
    End Sub
End Class
See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment.OriginalEnvelopeID Property

DsnAttachmentOriginalEnvelopeID Property
Gets the original envelope ID.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OriginalEnvelopeID { get; }
Public ReadOnly Property OriginalEnvelopeID As String
    Get

Property Value

Type: String
A string containing the original envelope ID taken from "Original-Envelope-Id" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field contains an "envelope identifier" which uniquely identifies the transaction during which the message was submitted by sender. When sending the original e-mail message, you can specify this ID using Smtp.DeliveryNotification.TrackingID property (the sending mail server, however, must support DSN extension).

In this example, DSN field is:
Original-Envelope-Id: A406980DD7D140DCAD796DDCE62EF673.MAI@afterlogic.com
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment.ReceivedFromMtaName Property

DsnAttachmentReceivedFromMtaName Property
Gets the name of the MTA from which the message was received.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ReceivedFromMtaName { get; }
Public ReadOnly Property ReceivedFromMtaName As String
    Get

Property Value

Type: String
A string representaion of the message transfer agent name from "Received-From-MTA" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

The Received-From MTA is the MTA from which the Reporting MTA received the message, and accepted responsibility for delivery of the message.

In this example, DSN field is:
Received-From-MTA: dns; host.home.local
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentReceivedFromMtaType


DsnAttachment.ReceivedFromMtaType Property

DsnAttachmentReceivedFromMtaType Property
Gets the type of the MTA from which the message was received.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ReceivedFromMtaType { get; }
Public ReadOnly Property ReceivedFromMtaType As String
    Get

Property Value

Type: String
A string representaion of the message transfer agent type from "Received-From-MTA" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

The Received-From MTA is the MTA from which the Reporting MTA received the message, and accepted responsibility for delivery of the message.

In this example, DSN field is:
Received-From-MTA: dns; host.home.local
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentReceivedFromMtaName


DsnAttachment.Recipients Property

DsnAttachmentRecipients Property
Gets the list of the delivery statuses of the original e-mail message to its recipients.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnRecipientCollection Recipients { get; }
Public ReadOnly Property Recipients As DsnRecipientCollection
    Get

Property Value

Type: DsnRecipientCollection
The list containing the delivery status details of the original e-mail message to those of its recipients which have been handled by the mail server which sent this DSN e-mail.
Remarks

The returned collection contains the delivery status, the e-mail address and other details for the recipients of the original e-mail message. The original e-mail message is a message for which this DSN was issued upon delivery (or not delivery) by the mail server which sent this DSN e-mail.

Note Note
The returned collection does not necessarily contain all the recipients of the original message. If the message is addressed to e-mail addresses at different domains (i.e. user@domain1.com and user@domain2.com), their destination mail servers may be different. Thus, each of these servers can send its own DSN regarding the delivery to the recipient belonging to its own domain.
See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace


DsnAttachment.ReportingMtaName Property

DsnAttachmentReportingMtaName Property
Gets the reporting MTA name.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ReportingMtaName { get; }
Public ReadOnly Property ReportingMtaName As String
    Get

Property Value

Type: String
A string representaion of the message transfer agent name from "Reporting-MTA" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

Reporting MTA is the one which is reporting the results of delivery attempts described in this DSN. See ReportingMtaType topic for details.

In this example, DSN field is:
Reporting-MTA: dns; host.home.local
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentReportingMtaType


DsnAttachment.ReportingMtaType Property

DsnAttachmentReportingMtaType Property
Gets the reporting MTA type.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ReportingMtaType { get; }
Public ReadOnly Property ReportingMtaType As String
    Get

Property Value

Type: String
A string representaion of the message transfer agent type from "Reporting-MTA" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

Reporting MTA is the one which is reporting the results of delivery attempts described in this DSN. Usually, it's either the destination mail server (the SMTP MX server which accepts mail for the domain of the recipient e-mail address) or the sending e-mail server if the destination mail server could not be contacted (for instance, the recipient domain is invalid).

In this example, DSN field is:
Reporting-MTA: dns; host.home.local
The return value is marked bold.

See Also

Reference

DsnAttachment Class
MailBee.BounceMail Namespace
DsnAttachmentReportingMtaName


DsnRecipient Class

DsnRecipient Class
Contains the delivery status and other details for a single recipient listed in the DSN attachment.
Inheritance Hierarchy
SystemObject
MailBee.BounceMailDsnRecipient

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DsnRecipient
Public Class DsnRecipient

The DsnRecipient type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns all DSN fields as a string. (Overrides ObjectToString.)
Top
Properties
 | Name | Description
Public property | Action | Gets the DSN action type for the e-mail address.
Public property | DiagnosticCode | Gets the diagnostic code.
Public property | DiagnosticCodeType | Gets the diagnostic code type.
Public property | FinalRecipientAddress | Gets the e-mail address of the final recipient.
Public property | FinalRecipientType | Gets the type of the final recipient e-mail address as string.
Public property | IsLinked | Indicates if the DSN is linked to a certain RecipientStatus object.
 | Items | Gets a StringDictionary collection of the DSN fields.
Public property | LastAttemptDate | Gets the last attempt date of sending.
Public property | LastAttemptDateAsString | Gets the string representation of the last attempt date of sending.
Public property | OriginalRecipientAddress | Gets the e-mail address of the original recipient.
Public property | OriginalRecipientType | Gets the type of the original recipient e-mail address as string.
Public property | RemoteMtaName | Gets the remote MTA name.
Public property | RemoteMtaType | Gets the remote MTA type.
Public property | Status | Gets the string description of the status and the dot-numeric status code.
Public property | WillRetryUntil | Gets the date of "will retry until date".
Public property | WillRetryUntilAsString | Gets the string representation of "will retry until date".
Top
Remarks

In most cases, it's easier to use RecipientStatus object instead of DsnRecipient because RecipientStatus is more general. Use DsnRecipient object only if you need to examine particular fields of the DSN attachment. For general tasks (find the e-mail address for which your e-mail was not delivered), use RecipientStatus object.

To get DsnRecipient, use DsnInfo property. Or, if you have DsnAttachment object, use Recipients property to get the collection of DsnRecipient objects representing all recipients listed in the DSN attachment.

Examples
The example is available in Items topic.
See Also

Reference

MailBee.BounceMail Namespace
MailBee.BounceMailRecipientStatus
MailBee.BounceMailDsnAttachment


DsnRecipient Methods

DsnRecipient Methods

The DsnRecipient type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns all DSN fields as a string. (Overrides ObjectToString.)
Top
See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient.ToString Method

DsnRecipientToString Method
Returns all DSN fields as a string.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
A string containing the DSN recipient info as it appears in the DSN source.
See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient Properties

DsnRecipient Properties

The DsnRecipient type exposes the following members.

Properties
 | Name | Description
Public property | Action | Gets the DSN action type for the e-mail address.
Public property | DiagnosticCode | Gets the diagnostic code.
Public property | DiagnosticCodeType | Gets the diagnostic code type.
Public property | FinalRecipientAddress | Gets the e-mail address of the final recipient.
Public property | FinalRecipientType | Gets the type of the final recipient e-mail address as string.
Public property | IsLinked | Indicates if the DSN is linked to a certain RecipientStatus object.
 | Items | Gets a StringDictionary collection of the DSN fields.
Public property | LastAttemptDate | Gets the last attempt date of sending.
Public property | LastAttemptDateAsString | Gets the string representation of the last attempt date of sending.
Public property | OriginalRecipientAddress | Gets the e-mail address of the original recipient.
Public property | OriginalRecipientType | Gets the type of the original recipient e-mail address as string.
Public property | RemoteMtaName | Gets the remote MTA name.
Public property | RemoteMtaType | Gets the remote MTA type.
Public property | Status | Gets the string description of the status and the dot-numeric status code.
Public property | WillRetryUntil | Gets the date of "will retry until date".
Public property | WillRetryUntilAsString | Gets the string representation of "will retry until date".
Top
See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient.Action Property

DsnRecipientAction Property
Gets the DSN action type for the e-mail address.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnAction Action { get; }
Public ReadOnly Property Action As DsnAction
    Get

Property Value

Type: DsnAction
The action performed by the Reporting-MTA taken from "Action" DSN field as a result of its attempt to deliver the message to this recipient address.
Remarks

This field MUST be present for each recipient named in the DSN.

In this example, DSN field is:
Action: failed
The return value will be defined from the text marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient.DiagnosticCode Property

DsnRecipientDiagnosticCode Property
Gets the diagnostic code.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DiagnosticCode { get; }
Public ReadOnly Property DiagnosticCode As String
    Get

Property Value

Type: String
A string value with the diagnostic code from "Diagnostic-Code" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks
When Action is Failed or Delayed for the given recipient, this field contains the actual diagnostic code issued by the mail transport. Since such codes vary from one mail transport to another, the diagnostic-type subfield is needed to specify which type of diagnostic code is represented.

In this example, DSN field is:
Diagnostic-Code: smtp; Permanent Failure: Other undefined Status
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientDiagnosticCodeType


DsnRecipient.DiagnosticCodeType Property

DsnRecipientDiagnosticCodeType Property
Gets the diagnostic code type.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DiagnosticCodeType { get; }
Public ReadOnly Property DiagnosticCodeType As String
    Get

Property Value

Type: String
A string value with the diagnostic code type from "Diagnostic-Code" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks
When Action is Failed or Delayed for the given recipient, this field contains the actual diagnostic code type issued by the mail transport.

In this example, DSN field is:
Diagnostic-Code: smtp; Permanent Failure: Other address status
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientDiagnosticCode


DsnRecipient.FinalRecipientAddress Property

DsnRecipientFinalRecipientAddress Property
Gets the e-mail address of the final recipient.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string FinalRecipientAddress { get; }
Public ReadOnly Property FinalRecipientAddress As String
    Get

Property Value

Type: String
A string value with the e-mail address of the final recipient from "Final-Recipient" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field may differ from the e-mail address originally provided by the sender, because it may have been transformed during forwarding or gatewaying.

In this example, DSN field is:
Final-Recipient: rfc822; test@test.com
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientFinalRecipientType


DsnRecipient.FinalRecipientType Property

DsnRecipientFinalRecipientType Property
Gets the type of the final recipient e-mail address as string.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string FinalRecipientType { get; }
Public ReadOnly Property FinalRecipientType As String
    Get

Property Value

Type: String
A string value with the type of the final recipient e-mail address taken from "Final-Recipient" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This address type may differ from the address type originally provided by the sender, because it may have been transformed during forwarding or gatewaying.

In this example, DSN field is:
Final-Recipient: rfc822; test@test.com
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientFinalRecipientAddress


DsnRecipient.IsLinked Property

DsnRecipientIsLinked Property
Indicates if the DSN is linked to a certain RecipientStatus object.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsLinked { get; }
Public ReadOnly Property IsLinked As Boolean
    Get

Property Value

Type: Boolean
true if DSN is linked to a certain RecipientStatus object; otherwise, false.
Remarks
If this flag is false, there is no RecipientStatus object in Recipients collection which corresponds to this DSN. Usually, this flag is true and some RecipientStatus object holds the reference to this DSN via DsnInfo property.
See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient.Items Property

DsnRecipientItems Property
Gets a StringDictionary collection of the DSN fields.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary Items { get; }
Public ReadOnly Property Items As StringDictionary
    Get

Property Value

Type: StringDictionary
A StringDictionary object with all the fields in the DSN for the given recipient e-mail address.
Examples
This code sample scans a folder of .EML files and shows their DSN data in different ways.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.BounceMail;

class Sample
{
    static void Main(string[] args)
    {
        // Load the templates database from file(s).
        DeliveryStatusParser parser = new DeliveryStatusParser(@"C:\Temp\BounceDatabase\all.xml", true);
        string[] files = Directory.GetFiles(@"C:\Temp\IncomingMail", "*.eml");
        MailMessage msg = new MailMessage();

        // Process every message in the folder.
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            Result result = parser.Process(msg);

            Console.WriteLine("\r\nProcessing of message with filename: " + file);

            if (result == null || result.DsnStructure == null)
            {
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("This message doesn't have DSN MIME part.");
                Console.WriteLine("------------------------------------------------------");
            }
            else
            {
                Console.WriteLine("------------------ DSN part as text ------------------");
                Console.WriteLine(result.DsnStructure.ToString());
                Console.WriteLine("------------- DSN header as StringDictionary ---------");
                foreach (string key in result.DsnStructure.Items.Keys)
                {
                    Console.WriteLine("DSN item: {0} = {1}", key, result.DsnStructure.Items[key]);
                }
                Console.WriteLine("------------------------------------------------------");

                foreach (RecipientStatus res in result.Recipients)
                {
                    if (res.DsnInfo != null)
                    {
                        Console.WriteLine("DSN subpart for: {0} e-mail", res.EmailAddress);
                        Console.WriteLine("---------------- DSN subpart as text -----------------");
                        Console.WriteLine(res.DsnInfo.ToString());
                        Console.WriteLine("------------- DSN header as StringDictionary ---------");
                        foreach (string key in res.DsnInfo.Items.Keys)
                        {
                            Console.WriteLine("DSN subpart item: {0} = {1}", key, res.DsnInfo.Items[key]);
                        }
                        Console.WriteLine("------------------------------------------------------");
                    }
                }
            }
        }
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports Microsoft.VisualBasic
Imports MailBee.Mime
Imports MailBee.BounceMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Load the templates database from file(s).
        Dim parser As DeliveryStatusParser = New DeliveryStatusParser("C:\Temp\BounceDatabase\all.xml", True)
        Dim files() As String = Directory.GetFiles("C:\Temp\IncomingMail", "*.eml")
        Dim msg As MailMessage = New MailMessage

        ' Process every message in the folder.
        For Each file As String In files
            msg.LoadMessage(file)
            Dim result As Result = parser.Process(msg)

            Console.WriteLine(ControlChars.CrLf & "Processing of message with filename: " & file)

            If result Is Nothing Or result.DsnStructure Is Nothing Then
                Console.WriteLine("------------------------------------------------------")
                Console.WriteLine("This message doesn't have DSN MIME part.")
                Console.WriteLine("------------------------------------------------------")
            Else
                Console.WriteLine("------------------ DSN part as text ------------------")
                Console.WriteLine(result.DsnStructure.ToString())
                Console.WriteLine("------------- DSN header as StringDictionary ---------")
                For Each key As String In result.DsnStructure.Items.Keys
                    Console.WriteLine("Dsn item: {0} = {1}", key, result.DsnStructure.Items(key))
                Next
                Console.WriteLine("------------------------------------------------------")

                For Each res As RecipientStatus In result.Recipients
                    If Not res.DsnInfo Is Nothing Then
                        Console.WriteLine("DSN subpart for: {0} e-mail", res.EmailAddress)
                        Console.WriteLine("---------------- DSN subpart as text -----------------")
                        Console.WriteLine(res.DsnInfo.ToString())
                        Console.WriteLine("------------- DSN header as StringDictionary ---------")
                        For Each key As String In res.DsnInfo.Items.Keys
                            Console.WriteLine("Dsn subpart item: {0} = {1}", key, res.DsnInfo.Items(key))
                        Next
                        Console.WriteLine("------------------------------------------------------")
                    End If
                Next
            End If
        Next
    End Sub
End Class
See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient.LastAttemptDate Property

DsnRecipientLastAttemptDate Property
Gets the last attempt date of sending.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime LastAttemptDate { get; }
Public ReadOnly Property LastAttemptDate As DateTime
    Get

Property Value

Type: DateTime
A DateTime value with the datetime of the last attempt of sending (taken from "Last-Attempt-Date" DSN field), or MinValue if no such field contained in the DSN.
Remarks

This field gives the date and time of the last attempt to relay, gateway, or deliver the message (whether successful or unsuccessful) by the Reporting MTA.

In this example, DSN field is:
Last-Attempt-Date: Wed, 8 Feb 2010 21:01:10 +0000
The return value will be defined from the text marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientLastAttemptDateAsString


DsnRecipient.LastAttemptDateAsString Property

DsnRecipientLastAttemptDateAsString Property
Gets the string representation of the last attempt date of sending.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string LastAttemptDateAsString { get; }
Public ReadOnly Property LastAttemptDateAsString As String
    Get

Property Value

Type: String
A string value with the datetime of the last attempt of sending (taken from "Last-Attempt-Date" DSN field), or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field gives the date and time of the last attempt to relay, gateway, or deliver the message (whether successful or unsuccessful) by the Reporting MTA. This field can be an empty string.

In this example, DSN field is:
Last-Attempt-Date: Wed, 8 Feb 2010 21:01:10 +0000
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientLastAttemptDate


DsnRecipient.OriginalRecipientAddress Property

DsnRecipientOriginalRecipientAddress Property
Gets the e-mail address of the original recipient.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OriginalRecipientAddress { get; }
Public ReadOnly Property OriginalRecipientAddress As String
    Get

Property Value

Type: String
A string value with the e-mail address of the original recipient from "Original-Recipient" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field indicates the original recipient address as specified by the sender of the original message (for which this DSN was issued).

In this example, DSN field is:
Original-Recipient: rfc822; user@test.com
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientOriginalRecipientType


DsnRecipient.OriginalRecipientType Property

DsnRecipientOriginalRecipientType Property
Gets the type of the original recipient e-mail address as string.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OriginalRecipientType { get; }
Public ReadOnly Property OriginalRecipientType As String
    Get

Property Value

Type: String
A string value with the type of the original recipient e-mail address from "Original-Recipient" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

This field indicates the original recipient address type as specified by the sender of the original message (for which this DSN was issued).

In this example, DSN field is:
Original-Recipient: rfc822; user@test.com
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientOriginalRecipientAddress


DsnRecipient.RemoteMtaName Property

DsnRecipientRemoteMtaName Property
Gets the remote MTA name.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteMtaName { get; }
Public ReadOnly Property RemoteMtaName As String
    Get

Property Value

Type: String
A string value with printable ASCII representation of the Remote-MTA name from "Remote-MTA" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

The value associated with this field is a printable ASCII representation of the name of the "remote" MTA that reported delivery status to the "reporting" MTA.

In this example, DSN field is:
Remote-MTA: dns; remote.host.net
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientRemoteMtaType


DsnRecipient.RemoteMtaType Property

DsnRecipientRemoteMtaType Property
Gets the remote MTA type.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RemoteMtaType { get; }
Public ReadOnly Property RemoteMtaType As String
    Get

Property Value

Type: String
A string value with the remote MTA type from "Remote-MTA" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

The value associated with this field is a printable ASCII representation of the type of the "remote" MTA that reported delivery status to the "reporting" MTA.

In this example, DSN field is:
Remote-MTA: dns; remote.host.net
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientRemoteMtaName


DsnRecipient.Status Property

DsnRecipientStatus Property
Gets the string description of the status and the dot-numeric status code.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Status { get; }
Public ReadOnly Property Status As String
    Get

Property Value

Type: String
A string value with the description of the status and the dot-numeric status code taken from "Status" DSN field.
Remarks

The per-recipient Status field contains a transport-independent status code which indicates the delivery status of the message to that recipient. This field MUST be present for each delivery attempt which is described by a DSN.

Status codes thus consist of three numerical fields separated by dot ("."). The first sub-field indicates whether the delivery attempt was successful (2 = success, 4 = persistent temporary failure, 5 = permanent failure). The second sub-field indicates the probable source of any delivery anomalies, and the third sub-field denotes a precise error condition, if known.

In this example, DSN field is:
Status: 5.1.1
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace


DsnRecipient.WillRetryUntil Property

DsnRecipientWillRetryUntil Property
Gets the date of "will retry until date".

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime WillRetryUntil { get; }
Public ReadOnly Property WillRetryUntil As DateTime
    Get

Property Value

Type: DateTime
A DateTime taken from "Will-Retry-Until" DSN field, or MinValue if no such field contained in the DSN.
Remarks

For DSNs of type "delayed", the WillRetryUntil field gives the date after which the Reporting MTA expects to abandon all attempts to deliver the message to that recipient. The WillRetryUntil field is optional for "delay" DSNs, and MUST NOT appear in other DSNs.

In this example, DSN field is:
Last-Attempt-Date: Wed, 8 Feb 2010 21:01:10 +0000
The return value will be defined from the text marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientWillRetryUntilAsString


DsnRecipient.WillRetryUntilAsString Property

DsnRecipientWillRetryUntilAsString Property
Gets the string representation of "will retry until date".

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string WillRetryUntilAsString { get; }
Public ReadOnly Property WillRetryUntilAsString As String
    Get

Property Value

Type: String
A string value taken from "Will-Retry-Until" DSN field, or a null reference (Nothing in Visual Basic) if no such field contained in the DSN.
Remarks

For DSNs of type "delayed", the WillRetryUntilAsString field gives the date after which the Reporting MTA expects to abandon all attempts to deliver the message to that recipient. The WillRetryUntilAsString field is optional for "delay" DSNs, and MUST NOT appear in other DSNs.

In this example, DSN field is:
Last-Attempt-Date: Wed, 8 Feb 2010 23:01:10 +0000
The return value is marked bold.

See Also

Reference

DsnRecipient Class
MailBee.BounceMail Namespace
DsnRecipientWillRetryUntil


DsnRecipientCollection Class

DsnRecipientCollection Class
Represents a collection of delivery status information objects for all recipients listed in the DSN attachment.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.BounceMailDsnRecipientCollection

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DsnRecipientCollection : CollectionBase
Public Class DsnRecipientCollection
    Inherits CollectionBase

The DsnRecipientCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the DsnRecipient object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

Because an e-mail message can be addressed to multiple recipients, a DSN attachment may contain more than one delivery status notification.

Because some DSN messages do not contain any DSN attachment, it's more reliable to use RecipientStatusCollection as the list of the recipients in the DSN.

See Also

Reference

MailBee.BounceMail Namespace
MailBee.BounceMailDsnRecipient


DsnRecipientCollection Methods

DsnRecipientCollection Methods

The DsnRecipientCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DsnRecipientCollection Class
MailBee.BounceMail Namespace


DsnRecipientCollection Properties

DsnRecipientCollection Properties

The DsnRecipientCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the DsnRecipient object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

DsnRecipientCollection Class
MailBee.BounceMail Namespace


DsnRecipientCollection.Item Property

DsnRecipientCollectionItem Property
Gets the DsnRecipient object at the specified zero-based index in the collection.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnRecipient this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As DsnRecipient
    Get

Parameters

index
Type: SystemInt32
The zero-based index number of the element in the collection.

Return Value

Type: DsnRecipient
An DsnRecipient object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

DsnRecipientCollection Class
MailBee.BounceMail Namespace


RecipientStatus Class

RecipientStatus Class
Represents the delivery results for a particular recipient's e-mail address.
Inheritance Hierarchy
SystemObject
MailBee.BounceMailRecipientStatus

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class RecipientStatus
Public Class RecipientStatus

The RecipientStatus type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Common | Gets the delivery status.
Public property | Description | Gets the description string from the DSN message.
Public property | Detailed | Gets the detailed delivery status.
 | DsnInfo | A reference to DsnRecipient object which provides Delivery Status Notification data for the recipient.
Public property | EmailAddress | Gets the e-mail address of the recipient for which this RecipientStatus object applies.
Public property | IsBounced | Indicates whether this DSN message can be treated as a bounce e-mail.
Public property | Source | Gets or sets from which data the RecipientStatus object should return the recipient delivery status information.
Public property | UserDefined | Gets the delivery status as a string.
Top
Remarks

You can use this object to examine the delivery status for a particular recipient. This information includes the e-mail address, the type of the status (e.g. not delivered, delivered, etc), and other information.

To obtain this object for every recipient listed in the DSN message, call Process(MailMessage) method and iterate through the Recipients collection of the returned Result object.

To obtain information which is not specific to a particular recipient but is the same for all recipients (such as the header of the original message or its unique tracking id assigned by the sending software), use other properties of Result object. For instance, if you previously set Smtp.DeliveryNotification.TrackingID for e-mails you sent out and now want to find this tracking ID in the bounced messages, you will need to use Result.DsnStructure.OriginalEnvelopeID property.

Examples
The example is available in DeliveryStatusParser topic.
See Also

Reference

MailBee.BounceMail Namespace


RecipientStatus Methods

RecipientStatus Methods

The RecipientStatus type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace


RecipientStatus Properties

RecipientStatus Properties

The RecipientStatus type exposes the following members.

Properties
 | Name | Description
Public property | Common | Gets the delivery status.
Public property | Description | Gets the description string from the DSN message.
Public property | Detailed | Gets the detailed delivery status.
 | DsnInfo | A reference to DsnRecipient object which provides Delivery Status Notification data for the recipient.
Public property | EmailAddress | Gets the e-mail address of the recipient for which this RecipientStatus object applies.
Public property | IsBounced | Indicates whether this DSN message can be treated as a bounce e-mail.
Public property | Source | Gets or sets from which data the RecipientStatus object should return the recipient delivery status information.
Public property | UserDefined | Gets the delivery status as a string.
Top
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace


RecipientStatus.Common Property

RecipientStatusCommon Property
Gets the delivery status.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CommonType Common { get; }
Public ReadOnly Property Common As CommonType
    Get

Property Value

Type: CommonType
The common status of delivery of the original message to certain recipient.
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace
RecipientStatusDetailed
RecipientStatusEmailAddress


RecipientStatus.Description Property

RecipientStatusDescription Property
Gets the description string from the DSN message.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Description { get; }
Public ReadOnly Property Description As String
    Get

Property Value

Type: String
A string containing the description for the DSN for certain recipient, or a null reference (Nothing in Visual Basic) if not available.
Remarks

Description is a human-readable text which usually contains the reason why the original message was bounced.

MailBee can take this description either from the DSN message body text of from the DSN attachment (see Source property for details).

See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace
RecipientStatusEmailAddress


RecipientStatus.Detailed Property

RecipientStatusDetailed Property
Gets the detailed delivery status.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DetailedType Detailed { get; }
Public ReadOnly Property Detailed As DetailedType
    Get

Property Value

Type: DetailedType
The detailed status of delivery of the original message to certain recipient.
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace
RecipientStatusCommon
RecipientStatusEmailAddress


RecipientStatus.DsnInfo Property

RecipientStatusDsnInfo Property
A reference to DsnRecipient object which provides Delivery Status Notification data for the recipient.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnRecipient DsnInfo { get; }
Public ReadOnly Property DsnInfo As DsnRecipient
    Get

Property Value

Type: DsnRecipient
A DsnRecipient object which contains parsed DSN attachment data, or a null reference (Nothing in Visual Basic) if the DSN attachment is missing in the DSN message.
Remarks
MailBee sets this property even if Source is set not to use DSN attachments.
Examples
The example is available in DsnRecipientFields.Items topic.
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace
RecipientStatusEmailAddress


RecipientStatus.EmailAddress Property

RecipientStatusEmailAddress Property
Gets the e-mail address of the recipient for which this RecipientStatus object applies.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string EmailAddress { get; }
Public ReadOnly Property EmailAddress As String
    Get

Property Value

Type: String
A string value with the e-mail address, or empty string or a null reference (Nothing in Visual Basic) if not available.
Remarks
If IsBounced is true, that means that the original e-mail message was not delivered to EmailAddress recipient. You may consider exclusion of this e-mail address from your mailing list.
Note Note
For out-of-office autoreply messages, this property can be not set because it's often not available in the autoreply message body. However, you can use From address of the MailMessage for which you're running this bounce check. This is because out-of-office replies are usually sent from the address in question (while "real" bounces are usually sent from "postmaster"-like account and specify the email address in question somewhere in the message body).
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace


RecipientStatus.IsBounced Property

RecipientStatusIsBounced Property
Indicates whether this DSN message can be treated as a bounce e-mail.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBounced { get; }
Public ReadOnly Property IsBounced As Boolean
    Get

Property Value

Type: Boolean
true if the message is bounced; otherwise, false.
Remarks

true means that Common property is CommonType.Undeliverable or CommonType.Blocked, or Detailed property is DetailedType.AddressChanged.

If the message is not bounce, it can be informational or warning message (or it was not recognized).

See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace


RecipientStatus.Source Property

RecipientStatusSource Property
Gets or sets from which data the RecipientStatus object should return the recipient delivery status information.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RecipientStatusSource Source { get; set; }
Public Property Source As RecipientStatusSource
    Get
    Set

Property Value

Type: RecipientStatusSource
A RecipientStatusSource value. The default value is DsnThenText.
Remarks
This property controls whether to take DSN information (such as EmailAddress, Description, etc) from the DSN attachment or from the text body. Changing this property value has immediate effect (i.e. it's not required to reparse or reprocess the DSN message in order to apply the changes).
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace


RecipientStatus.UserDefined Property

RecipientStatusUserDefined Property
Gets the delivery status as a string.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string UserDefined { get; }
Public ReadOnly Property UserDefined As String
    Get

Property Value

Type: String
The string status of delivery of the original message to certain recipient.
Remarks
You can use this property if Common property is CommonType.UserDefined or Detailed property is DetailedType.UserDefined.
See Also

Reference

RecipientStatus Class
MailBee.BounceMail Namespace
RecipientStatusEmailAddress


RecipientStatusCollection Class

RecipientStatusCollection Class
Represents a collection of delivery status information objects for all recipients listed in the DSN message.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.BounceMailRecipientStatusCollection

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class RecipientStatusCollection : CollectionBase
Public Class RecipientStatusCollection
    Inherits CollectionBase

The RecipientStatusCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | Item | Gets the RecipientStatus object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

Because an e-mail message can can be addressed to multiple recipients, a DSN message may contain more than one delivery status notification.

To get this collection, use Notification.Process method to obtain Result object and then examine Recipients property.

See Also

Reference

MailBee.BounceMail Namespace
MailBee.BounceMailRecipientStatus


RecipientStatusCollection Methods

RecipientStatusCollection Methods

The RecipientStatusCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

RecipientStatusCollection Class
MailBee.BounceMail Namespace


RecipientStatusCollection Properties

RecipientStatusCollection Properties

The RecipientStatusCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | Item | Gets the RecipientStatus object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

RecipientStatusCollection Class
MailBee.BounceMail Namespace


RecipientStatusCollection.Item Property

RecipientStatusCollectionItem Property
Gets the RecipientStatus object at the specified zero-based index in the collection.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RecipientStatus this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As RecipientStatus
    Get

Parameters

index
Type: SystemInt32
The zero-based index number of the RecipientStatus object in the collection.

Return Value

Type: RecipientStatus
An RecipientStatus object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
The example is available in DeliveryStatusParser topic.
See Also

Reference

RecipientStatusCollection Class
MailBee.BounceMail Namespace
MailBee.BounceMailRecipientStatus


RecipientStatusSource Enumeration

RecipientStatusSource Enumeration
Defines from which parts of the DSN message MailBee should load RecipientStatus object.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum RecipientStatusSource
Public Enumeration RecipientStatusSource
Members
Member name | Value | Description
DsnThenText | 0 | Loads RecipientStatus object from the DSN attachment if available; otherwise, from the message body text.
Dsn | 1 | Always loads RecipientStatus object only from the DSN attachment. If the DSN attachment is missing in the notification message, most RecipientStatus properties will return a null reference.
TextThenDsn | 2 | Loads RecipientStatus object from the message body text if available; otherwise, from the DSN attachment.
Text | 3 | Always loads RecipientStatus object only from the message body text. If the message body text is missing in the notification message, most RecipientStatus properties will return a null reference.
Remarks

Because DSN messages may contain duplicated information in different formats, you can tell MailBee the exact order of obtaining such information. Usually, more detailed and precise data is contained in DSN attachment while text description is less formal and less reliable.

You can set this mode using Source property.

See Also

Reference

MailBee.BounceMail Namespace
RecipientStatusSource


Result Class

Result Class
Represents the result checking an e-mail message for delivery status notification (DSN) entries.
Inheritance Hierarchy
SystemObject
MailBee.BounceMailResult

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Result
Public Class Result

The Result type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
DsnStructure | DsnAttachment object representing RFC 1894 DSN attachment to this DSN message.
OriginalMessage | A reference to the original mail message for which this DSN message was sent.
Recipients | The list of delivery status information objects representing each recipient in the DSN message.
Top
Remarks

Use Process(MailMessage) method to get Result object for a DSN message.

Result object provides access to the Recipients collection of RecipientStatus objects which represent all recipients listed in the DSN message. Iterate through this collection to examine the delivery status for every recipient's e-mail address.

You can also use OriginalMessage property to get the e-mail message (usually, only its header) for which this DSN message was sent (i.e. you sent a message, it was not delivered to certain recipients and you got a DSN telling you that; the header of the original message you sent may be available in OriginalMessage property).

Use DsnStructure property to examine the DSN attachment (if available). This is alternative approach to examining Recipients collection, it should only be used in special cases when you need to extract specific information from the DSN attachment (for instance, you can use OriginalEnvelopeID property of DsnStructure object to match it to Smtp.DeliveryNotification.TrackingID of the e-mails you sent earlier).

Examples
The example is available in DeliveryStatusParser topic.
See Also

Reference

MailBee.BounceMail Namespace
DeliveryStatusParserProcess(MailMessage)


Result Methods

Result Methods

The Result type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Result Class
MailBee.BounceMail Namespace


Result Properties

Result Properties

The Result type exposes the following members.

Properties
Name | Description
DsnStructure | DsnAttachment object representing RFC 1894 DSN attachment to this DSN message.
OriginalMessage | A reference to the original mail message for which this DSN message was sent.
Recipients | The list of delivery status information objects representing each recipient in the DSN message.
Top
See Also

Reference

Result Class
MailBee.BounceMail Namespace


Result.DsnStructure Property

ResultDsnStructure Property
DsnAttachment object representing RFC 1894 DSN attachment to this DSN message.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnAttachment DsnStructure { get; }
Public ReadOnly Property DsnStructure As DsnAttachment
    Get

Property Value

Type: DsnAttachment
A reference to the DsnAttachment object containing the DSN attachment for the given DSN message, or a null reference (Nothing in Visual Basic) if the DSN attachment is missing in the DSN message.
Remarks
Most frequently used property of DsnAttachment object is OriginalEnvelopeID which allows you to get the tracking ID of the original e-mail message. You can assign tracking ID to outgoing messages using Smtp.DeliveryNotification.TrackingID property. Then, when a bounce message arrives, you can easily match it to the original message you sent earlier using tracking ID provided that you create unique tracking ID for every message sent.
Examples

This sample displays the DSN attachment and the original message part of the message.

It's assumed the e-mail samples are .EML files located in C:\Temp\IncomingMail folder. The template database is stored in C:\Temp\BounceDatabase\all.xml file.

C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Mime;
using MailBee.BounceMail;

class Sample
{
    static void Main(string[] args)
    {
        // Load the templates database from file(s).
        DeliveryStatusParser parser = new DeliveryStatusParser (@"C:\Temp\BounceDatabase\all.xml", true);
        string[] files = Directory.GetFiles(@"C:\Temp\IncomingMail", "*.eml");
        MailMessage msg = new MailMessage();

        // Iterate through all messages in the folder.
        foreach (string file in files)
        {
            msg.LoadMessage(file);
            Result result = parser.Process(msg);

            Console.WriteLine("\r\nProcessing of message with filename: " + file);

            if (result == null || (result.OriginalMessage == null && result.DsnStructure == null))
            {
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("This message doesn't have DSN & original message part.");
                Console.WriteLine("------------------------------------------------------");
            }
            else
            {
                // Get original e-mail message part.
                if (result.OriginalMessage != null)
                {
                    Console.WriteLine("----------------- Original message part --------------");
                    Console.WriteLine(result.OriginalMessage.RawHeader);
                    Console.WriteLine(result.OriginalMessage.BodyPlainText);
                    Console.WriteLine("------------------------------------------------------");
                }

                // Get DSN attachment part.
                if (result.DsnStructure != null)
                {
                    Console.WriteLine("---------------------- DSN part ----------------------");
                    Console.WriteLine(result.DsnStructure.ToString());
                    Console.WriteLine("------------------------------------------------------");
                }
            }
        }
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports Microsoft.VisualBasic
Imports MailBee.Mime
Imports MailBee.BounceMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Load the templates database from file(s).
        Dim parser As DeliveryStatusParser = New DeliveryStatusParser("C:\Temp\BounceDatabase\all.xml", True)
        Dim files() As String = Directory.GetFiles("C:\Temp\IncomingMail", "*.eml")
        Dim msg As MailMessage = New MailMessage

        ' Iterate through all messages in the folder.
        For Each file As String In files
            msg.LoadMessage(file)
            Dim result As Result = parser.Process(msg)

            Console.WriteLine(ControlChars.CrLf & "Processing of message with filename: " & file)

            If result Is Nothing Or (result.OriginalMessage Is Nothing And result.DsnStructure Is Nothing) Then
                Console.WriteLine("------------------------------------------------------")
                Console.WriteLine("This message doesn't have DSN & original message part.")
                Console.WriteLine("------------------------------------------------------")
            Else
                ' Get original e-mail message part.
                If Not result.OriginalMessage Is Nothing Then
                    Console.WriteLine("----------------- Original message part --------------")
                    Console.WriteLine(result.OriginalMessage.RawHeader)
                    Console.WriteLine(result.OriginalMessage.BodyPlainText)
                    Console.WriteLine("------------------------------------------------------")
                End If

                ' Get DSN attachment part.
                If Not result.DsnStructure Is Nothing Then
                    Console.WriteLine("---------------------- DSN part ----------------------")
                    Console.WriteLine(result.DsnStructure.ToString())
                    Console.WriteLine("------------------------------------------------------")
                End If
            End If
        Next
    End Sub
End Class
See Also

Reference

Result Class
MailBee.BounceMail Namespace


Result.OriginalMessage Property

ResultOriginalMessage Property
A reference to the original mail message for which this DSN message was sent.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage OriginalMessage { get; }
Public ReadOnly Property OriginalMessage As MailMessage
    Get

Property Value

Type: MailMessage
A MailMessage object containing the part of the original e-mail message which was attached to the DSN message, or a null reference (Nothing in Visual Basic) if the original e-mail message was not attached.
Remarks

Some mail servers may attach the original message (usually, only the header) to the DSN, others don't. The default behavior is not defined. During sending the original message, you may request the mail server (to which you're sending your message) to include the entire message or its header in the bounce in case of non-delivery. You can use properties of DeliveryNotification object to tune this behavior prior to sending the original message.

Examples
The example is available in DsnStructure topic.
See Also

Reference

Result Class
MailBee.BounceMail Namespace


Result.Recipients Property

ResultRecipients Property
The list of delivery status information objects representing each recipient in the DSN message.

Namespace: MailBee.BounceMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RecipientStatusCollection Recipients { get; }
Public ReadOnly Property Recipients As RecipientStatusCollection
    Get

Property Value

Type: RecipientStatusCollection
The collection of the delivery status details for every recipient's e-mail address listed ih the DSN message. Never a null reference and never empty.
Examples
The example is available in DeliveryStatusParser topic.
See Also

Reference

Result Class
MailBee.BounceMail Namespace


MailBee.DnsMX Namespace

MailBee.DnsMX Namespace

MailBee.DnsMX namespace contains classes, interfaces and enumerations related to performing DNS MX lookup queries (and other sorts of special queries like DNS TXT for DomainKeys, reverse DNS, RBL-specific A queries for spam filtering purposes). For instance, MailBee.SmtpMail.Smtp class can take advantage of DNS MX lookup functions to send e-mails directly to mail servers of end recipients (without an SMTP relay server) and provides means to get DNS records of different types for any domain.

MailBee supports caching DNS records which greatly improves DNS MX lookup performance.

MailBee.DnsMX namespace, however, contains no classes which can be used on their own. All application-level methods reside in Smtp class.

Classes
 | Class | Description
Public class | DnsCache | Provides properties and methods which allow the developer to control whether and how MailBee will cache DNS MX (and some other) records when performing DNS MX lookup and TXT queries.
Public class | DnsServer | Represents a DNS server to be queried about domain names of the Internet hosts.
Public class | DnsServerCollection | Represents a sorted collection of DnsServer objects.
Public class | MailBeeDnsLackOfRecursionException | The exception that is thrown if the DNS server returned no records of A type for the given host name.
Public class | MailBeeDnsNameErrorException | The exception that is thrown when the DNS server cannot find the queried domain name in the domains database.
Public class | MailBeeDnsProtocolException | The exception that is thrown when either MailBee or a DNS server encounter DNS protocol error.
Public class | MailBeeDnsProtocolNegativeResponseException | The exception that is thrown when the DNS server replied with non-successful (non-zero) response code.
Public class | MailBeeDnsQueryMismatchException | The exception that is thrown when the response got from the DNS server does not match the original query to the DNS server.
Public class | MailBeeDnsServerDisabledException | The exception that is thrown when there was an attempt to connect to the DNS server banned by MailBee because this server is down.
Public class | MailBeeInvalidBinaryResponseException | The exception that is thrown when the binary response from the server cannot be parsed.
Interfaces
 | Interface | Description
Public interface | IMailBeeNegativeDnsResponseException | Defines properties which provide additional information regarding the negative response from the DNS server.
Enumerations
 | Enumeration | Description
 | DnsAutodetectOptions | Provides options for selecting methods of automatic detection of the DNS servers registered in the system.
Public enumeration | DnsReplyCode | Lists DNS server known reply codes.


IMailBeeNegativeDnsResponseException Interface

IMailBeeNegativeDnsResponseException Interface
Defines properties which provide additional information regarding the negative response from the DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeNegativeDnsResponseException : IMailBeeNegativeResponseException
Public Interface IMailBeeNegativeDnsResponseException
    Inherits IMailBeeNegativeResponseException

The IMailBeeNegativeDnsResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ID | Gets a value of the DNS response ID as returned by the DNS server.
Public property | ResponseCode | Gets a value of the DNS response code.
Public property | ResponseData | Gets a value of the entire DNS response data.
Top
See Also

Reference

MailBee.DnsMX Namespace


IMailBeeNegativeDnsResponseException Properties

IMailBeeNegativeDnsResponseException Properties

The IMailBeeNegativeDnsResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ID | Gets a value of the DNS response ID as returned by the DNS server.
Public property | ResponseCode | Gets a value of the DNS response code.
Public property | ResponseData | Gets a value of the entire DNS response data.
Top
See Also

Reference

IMailBeeNegativeDnsResponseException Interface
MailBee.DnsMX Namespace


IMailBeeNegativeDnsResponseException.ID Property

IMailBeeNegativeDnsResponseExceptionID Property
Gets a value of the DNS response ID as returned by the DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
short ID { get; }
ReadOnly Property ID As Short
    Get

Property Value

Type: Int16
ID of the DNS response.
See Also

Reference

IMailBeeNegativeDnsResponseException Interface
MailBee.DnsMX Namespace


IMailBeeNegativeDnsResponseException.ResponseCode Property

IMailBeeNegativeDnsResponseExceptionResponseCode Property
Gets a value of the DNS response code.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
DnsReplyCode ResponseCode { get; }
ReadOnly Property ResponseCode As DnsReplyCode
    Get

Property Value

Type: DnsReplyCode
DNS response code.
See Also

Reference

IMailBeeNegativeDnsResponseException Interface
MailBee.DnsMX Namespace


IMailBeeNegativeDnsResponseException.ResponseData Property

IMailBeeNegativeDnsResponseExceptionResponseData Property
Gets a value of the entire DNS response data.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
byte[] ResponseData { get; }
ReadOnly Property ResponseData As Byte()
    Get

Property Value

Type: Byte
DNS response data.
See Also

Reference

IMailBeeNegativeDnsResponseException Interface
MailBee.DnsMX Namespace


MailBeeDnsLackOfRecursionException Class

MailBeeDnsLackOfRecursionException Class
The exception that is thrown if the DNS server returned no records of A type for the given host name.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBee.DnsMXMailBeeDnsProtocolException
MailBee.DnsMXMailBeeDnsLackOfRecursionException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsLackOfRecursionException : MailBeeDnsProtocolException
<SerializableAttribute>
Public Class MailBeeDnsLackOfRecursionException
    Inherits MailBeeDnsProtocolException

The MailBeeDnsLackOfRecursionException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsLackOfRecursionException | Initializes a new instance of the MailBeeDnsLackOfRecursionException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Due to distributed nature of Internet domains database, DNS servers are usually capable of immediate lookup of DNS records only for a limited subset of Internet domains. In order to lookup DNS records for domains belonging to external networks, a DNS server must be capable of DNS recursion which is a process of querying DNS server of higher level in the case when the current DNS server cannot find the requested resource in its local database. If the DNS server does not support recursion, it's practically useless since such server can serve only very restricted set of domains.
See Also

Reference

MailBee.DnsMX Namespace


MailBeeDnsLackOfRecursionException Constructor

MailBeeDnsLackOfRecursionException Constructor
Initializes a new instance of the MailBeeDnsLackOfRecursionException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsLackOfRecursionException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsLackOfRecursionException Class
MailBee.DnsMX Namespace


MailBeeDnsLackOfRecursionException Methods

MailBeeDnsLackOfRecursionException Methods

The MailBeeDnsLackOfRecursionException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsLackOfRecursionException Class
MailBee.DnsMX Namespace


MailBeeDnsLackOfRecursionException Properties

MailBeeDnsLackOfRecursionException Properties

The MailBeeDnsLackOfRecursionException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeDnsLackOfRecursionException Class
MailBee.DnsMX Namespace


MailBeeDnsLackOfRecursionException Events

MailBeeDnsLackOfRecursionException Events

The MailBeeDnsLackOfRecursionException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsLackOfRecursionException Class
MailBee.DnsMX Namespace


MailBeeDnsNameErrorException Class

MailBeeDnsNameErrorException Class
The exception that is thrown when the DNS server cannot find the queried domain name in the domains database.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBee.DnsMXMailBeeDnsProtocolException
MailBee.DnsMXMailBeeDnsProtocolNegativeResponseException
MailBee.DnsMXMailBeeDnsNameErrorException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsNameErrorException : MailBeeDnsProtocolNegativeResponseException
<SerializableAttribute>
Public Class MailBeeDnsNameErrorException
    Inherits MailBeeDnsProtocolNegativeResponseException

The MailBeeDnsNameErrorException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsNameErrorException | Initializes a new instance of the MailBeeDnsNameErrorException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | ID | Gets a value of the DNS response ID as returned by the DNS server. (Inherited from MailBeeDnsProtocolNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a value of the DNS response code. (Inherited from MailBeeDnsProtocolNegativeResponseException.)
Public property | ResponseData | Gets a value of the entire DNS response data. (Inherited from MailBeeDnsProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.DnsMX Namespace


MailBeeDnsNameErrorException Constructor

MailBeeDnsNameErrorException Constructor
Initializes a new instance of the MailBeeDnsNameErrorException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsNameErrorException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsNameErrorException Class
MailBee.DnsMX Namespace


MailBeeDnsNameErrorException Methods

MailBeeDnsNameErrorException Methods

The MailBeeDnsNameErrorException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsNameErrorException Class
MailBee.DnsMX Namespace


MailBeeDnsNameErrorException Properties

MailBeeDnsNameErrorException Properties

The MailBeeDnsNameErrorException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | ID | Gets a value of the DNS response ID as returned by the DNS server. (Inherited from MailBeeDnsProtocolNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a value of the DNS response code. (Inherited from MailBeeDnsProtocolNegativeResponseException.)
Public property | ResponseData | Gets a value of the entire DNS response data. (Inherited from MailBeeDnsProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeDnsNameErrorException Class
MailBee.DnsMX Namespace


MailBeeDnsNameErrorException Events

MailBeeDnsNameErrorException Events

The MailBeeDnsNameErrorException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsNameErrorException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolException Class

MailBeeDnsProtocolException Class
The exception that is thrown when either MailBee or a DNS server encounter DNS protocol error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBee.DnsMXMailBeeDnsProtocolException
MailBee.DnsMXMailBeeDnsLackOfRecursionException
MailBee.DnsMXMailBeeDnsProtocolNegativeResponseException
MailBee.DnsMXMailBeeDnsQueryMismatchException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsProtocolException : MailBeeProtocolException
<SerializableAttribute>
Public Class MailBeeDnsProtocolException
    Inherits MailBeeProtocolException

The MailBeeDnsProtocolException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsProtocolException | Initializes a new instance of the MailBeeDnsProtocolException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about.
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.DnsMX Namespace


MailBeeDnsProtocolException Constructor

MailBeeDnsProtocolException Constructor
Initializes a new instance of the MailBeeDnsProtocolException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsProtocolException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsProtocolException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolException Methods

MailBeeDnsProtocolException Methods

The MailBeeDnsProtocolException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsProtocolException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolException Properties

MailBeeDnsProtocolException Properties

The MailBeeDnsProtocolException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about.
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeDnsProtocolException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolException.HostName Property

MailBeeDnsProtocolExceptionHostName Property
Gets a value of a host name the DNS server was queried about.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HostName { get; }
Public ReadOnly Property HostName As String
    Get

Property Value

Type: String
A host name the DNS server was expected to resolve or lookup.
See Also

Reference

MailBeeDnsProtocolException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolException Events

MailBeeDnsProtocolException Events

The MailBeeDnsProtocolException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsProtocolException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException Class

MailBeeDnsProtocolNegativeResponseException Class
The exception that is thrown when the DNS server replied with non-successful (non-zero) response code.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBee.DnsMXMailBeeDnsProtocolException
MailBee.DnsMXMailBeeDnsProtocolNegativeResponseException
MailBee.DnsMXMailBeeDnsNameErrorException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsProtocolNegativeResponseException : MailBeeDnsProtocolException,
    IMailBeeNegativeDnsResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeeDnsProtocolNegativeResponseException
    Inherits MailBeeDnsProtocolException
    Implements IMailBeeNegativeDnsResponseException, IMailBeeNegativeResponseException

The MailBeeDnsProtocolNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsProtocolNegativeResponseException | Initializes a new instance of the MailBeeDnsProtocolNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | ID | Gets a value of the DNS response ID as returned by the DNS server.
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a value of the DNS response code.
Public property | ResponseData | Gets a value of the entire DNS response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException Constructor

MailBeeDnsProtocolNegativeResponseException Constructor
Initializes a new instance of the MailBeeDnsProtocolNegativeResponseException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsProtocolNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException Methods

MailBeeDnsProtocolNegativeResponseException Methods

The MailBeeDnsProtocolNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException Properties

MailBeeDnsProtocolNegativeResponseException Properties

The MailBeeDnsProtocolNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | ID | Gets a value of the DNS response ID as returned by the DNS server.
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a value of the DNS response code.
Public property | ResponseData | Gets a value of the entire DNS response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException.ID Property

MailBeeDnsProtocolNegativeResponseExceptionID Property
Gets a value of the DNS response ID as returned by the DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public short ID { get; }
Public ReadOnly Property ID As Short
    Get

Property Value

Type: Int16
ID of the DNS response.

Implements

IMailBeeNegativeDnsResponseExceptionID
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException.ResponseCode Property

MailBeeDnsProtocolNegativeResponseExceptionResponseCode Property
Gets a value of the DNS response code.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsReplyCode ResponseCode { get; }
Public ReadOnly Property ResponseCode As DnsReplyCode
    Get

Property Value

Type: DnsReplyCode
DNS response code.

Implements

IMailBeeNegativeDnsResponseExceptionResponseCode
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException.ResponseData Property

MailBeeDnsProtocolNegativeResponseExceptionResponseData Property
Gets a value of the entire DNS response data.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] ResponseData { get; }
Public ReadOnly Property ResponseData As Byte()
    Get

Property Value

Type: Byte
DNS response data.

Implements

IMailBeeNegativeDnsResponseExceptionResponseData
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsProtocolNegativeResponseException Events

MailBeeDnsProtocolNegativeResponseException Events

The MailBeeDnsProtocolNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsProtocolNegativeResponseException Class
MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException Class

MailBeeDnsQueryMismatchException Class
The exception that is thrown when the response got from the DNS server does not match the original query to the DNS server.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBee.DnsMXMailBeeDnsProtocolException
MailBee.DnsMXMailBeeDnsQueryMismatchException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsQueryMismatchException : MailBeeDnsProtocolException
<SerializableAttribute>
Public Class MailBeeDnsQueryMismatchException
    Inherits MailBeeDnsProtocolException

The MailBeeDnsQueryMismatchException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsQueryMismatchException | Initializes a new instance of the MailBeeDnsQueryMismatchException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualID | Gets a value of the DNS response ID as returned by the DNS server.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | ExpectedID | Gets an ID value of the DNS query originally sent to the DNS server.
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException Constructor

MailBeeDnsQueryMismatchException Constructor
Initializes a new instance of the MailBeeDnsQueryMismatchException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsQueryMismatchException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsQueryMismatchException Class
MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException Methods

MailBeeDnsQueryMismatchException Methods

The MailBeeDnsQueryMismatchException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsQueryMismatchException Class
MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException Properties

MailBeeDnsQueryMismatchException Properties

The MailBeeDnsQueryMismatchException type exposes the following members.

Properties
 | Name | Description
Public property | ActualID | Gets a value of the DNS response ID as returned by the DNS server.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | ExpectedID | Gets an ID value of the DNS query originally sent to the DNS server.
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HostName | Gets a value of a host name the DNS server was queried about. (Inherited from MailBeeDnsProtocolException.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeDnsQueryMismatchException Class
MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException.ActualID Property

MailBeeDnsQueryMismatchExceptionActualID Property
Gets a value of the DNS response ID as returned by the DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public short ActualID { get; }
Public ReadOnly Property ActualID As Short
    Get

Property Value

Type: Int16
ID of the DNS response.
See Also

Reference

MailBeeDnsQueryMismatchException Class
MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException.ExpectedID Property

MailBeeDnsQueryMismatchExceptionExpectedID Property
Gets an ID value of the DNS query originally sent to the DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public short ExpectedID { get; }
Public ReadOnly Property ExpectedID As Short
    Get

Property Value

Type: Int16
ID of the original DNS query.
See Also

Reference

MailBeeDnsQueryMismatchException Class
MailBee.DnsMX Namespace


MailBeeDnsQueryMismatchException Events

MailBeeDnsQueryMismatchException Events

The MailBeeDnsQueryMismatchException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsQueryMismatchException Class
MailBee.DnsMX Namespace


MailBeeDnsServerDisabledException Class

MailBeeDnsServerDisabledException Class
The exception that is thrown when there was an attempt to connect to the DNS server banned by MailBee because this server is down.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.DnsMXMailBeeDnsServerDisabledException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsServerDisabledException : MailBeeLocalException
<SerializableAttribute>
Public Class MailBeeDnsServerDisabledException
    Inherits MailBeeLocalException

The MailBeeDnsServerDisabledException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsServerDisabledException | Initializes a new instance of the MailBeeDnsServerDisabledException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Server | Gets a reference to the banned DNS server.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
MailBee keeps track of DNS servers failures. If certain server fails, MailBee bans it for DnsNextAttemptInterval amount of time, and MailBee switches to the next server in turn. If all the available servers become banned, this exception is thrown for the last server.
See Also

Reference

MailBee.DnsMX Namespace


MailBeeDnsServerDisabledException Constructor

MailBeeDnsServerDisabledException Constructor
Initializes a new instance of the MailBeeDnsServerDisabledException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsServerDisabledException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsServerDisabledException Class
MailBee.DnsMX Namespace


MailBeeDnsServerDisabledException Methods

MailBeeDnsServerDisabledException Methods

The MailBeeDnsServerDisabledException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsServerDisabledException Class
MailBee.DnsMX Namespace


MailBeeDnsServerDisabledException Properties

MailBeeDnsServerDisabledException Properties

The MailBeeDnsServerDisabledException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Server | Gets a reference to the banned DNS server.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsServerDisabledException Class
MailBee.DnsMX Namespace


MailBeeDnsServerDisabledException.Server Property

MailBeeDnsServerDisabledExceptionServer Property
Gets a reference to the banned DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer Server { get; }
Public ReadOnly Property Server As DnsServer
    Get

Property Value

Type: DnsServer
A reference to the banned DNS server.
See Also

Reference

MailBeeDnsServerDisabledException Class
MailBee.DnsMX Namespace


MailBeeDnsServerDisabledException Events

MailBeeDnsServerDisabledException Events

The MailBeeDnsServerDisabledException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsServerDisabledException Class
MailBee.DnsMX Namespace


MailBeeInvalidBinaryResponseException Class

MailBeeInvalidBinaryResponseException Class
The exception that is thrown when the binary response from the server cannot be parsed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBeeMailBeeInvalidResponseException
MailBee.DnsMXMailBeeInvalidBinaryResponseException

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeInvalidBinaryResponseException : MailBeeInvalidResponseException
<SerializableAttribute>
Public Class MailBeeInvalidBinaryResponseException
    Inherits MailBeeInvalidResponseException

The MailBeeInvalidBinaryResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeInvalidBinaryResponseException | Initializes a new instance of the MailBeeInvalidBinaryResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseData | Gets a value of the entire DNS response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.DnsMX Namespace


MailBeeInvalidBinaryResponseException Constructor

MailBeeInvalidBinaryResponseException Constructor
Initializes a new instance of the MailBeeInvalidBinaryResponseException class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeInvalidBinaryResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeInvalidBinaryResponseException Class
MailBee.DnsMX Namespace


MailBeeInvalidBinaryResponseException Methods

MailBeeInvalidBinaryResponseException Methods

The MailBeeInvalidBinaryResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidBinaryResponseException Class
MailBee.DnsMX Namespace


MailBeeInvalidBinaryResponseException Properties

MailBeeInvalidBinaryResponseException Properties

The MailBeeInvalidBinaryResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseData | Gets a value of the entire DNS response data.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeInvalidBinaryResponseException Class
MailBee.DnsMX Namespace


MailBeeInvalidBinaryResponseException.ResponseData Property

MailBeeInvalidBinaryResponseExceptionResponseData Property
Gets a value of the entire DNS response data.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] ResponseData { get; }
Public ReadOnly Property ResponseData As Byte()
    Get

Property Value

Type: Byte
DNS response data.
See Also

Reference

MailBeeInvalidBinaryResponseException Class
MailBee.DnsMX Namespace


MailBeeInvalidBinaryResponseException Events

MailBeeInvalidBinaryResponseException Events

The MailBeeInvalidBinaryResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeInvalidBinaryResponseException Class
MailBee.DnsMX Namespace


DnsAutodetectOptions Enumeration

DnsAutodetectOptions Enumeration
Provides options for selecting methods of automatic detection of the DNS servers registered in the system.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum DnsAutodetectOptions
<FlagsAttribute>
Public Enumeration DnsAutodetectOptions
Members
Member name | Value | Description
None | 0 | Do nothing.
ConfigFiles | 1 | Search DNS server definitions in "MailBee.DnsMX.DnsServerCollection" key of "appSettings" section of the config files (such as app.config, web.config, or machine.config), where the key value contains ";"-separated list of DNS servers in "IP Address,Priority" format. If the priority is omitted, the top (0) priority will be assigned to the DNS server. If DnsServers is not empty, its entries are added too.
NetInterface | 2 | Use System.Net.NetworkInformation.NetworkInterface class (not supported in .NET Core and UWP, requires UnmanagedCode permission). The most accurate method, however.
Registry | 4 | Search DNS server definitions in Windows registry. Usually, the last resort. Requires less permissions than NetInterface but less accurate.
Wmi | 8 | Search DNS server definitions in WMI database.
RootServers | 16 | Use DNS servers with addresses "8.8.8.8" and "8.8.4.4". These servers are always available but they belong to Google, not to your company or your ISP. They might not work well for some scenarios like DNS RBL checks.
AllowIPv6Servers | 32 | If set, IPv6 entries (if present) will appear in the list of autodetected servers. If not set, only IPv4 servers will be added. Has no effect for adding DnsServers (servers from there are added regardless of their type).
Remarks

If multiple methods are specified, they are tried in the order their values increase until at least one DNS server definition is found.

To search WMI database (Wmi option), the application must have appropriate permissions to use System.Management.dll (which encapsulates System.Management namespace). For instance, web applications configured to run on "High" trust level have no permissions to access this assembly. In this case, Autodetect method will not find any DNS server records in WMI database. Changing trust level to "Full" eliminates the problem.

To use System.Net.NetworkInformation.NetworkInterface class (the best method available), "High" trust level might also require "Full" level.

Note Note
DNS auto-detection may not work well on Xamarin (https://forums.xamarin.com/discussion/6386/how-to-get-the-dns-servers-ip-address), you may have to add DNS server manually with Add(String) method. You can also register them globally with DnsServers property (this will let Autodetect method succeed).
Examples
This sample populates the collection of DNS servers with the servers defined in the config files (such as app.config, web.config, or machine.config). If it does not find any DNS server definitions in the config files, then Windows registry is searched. IPv6 servers are not allowed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.SmtpMail;
using MailBee.DnsMX;

// The actual code
Smtp smtp = new Smtp();
smtp.DnsServers.Autodetect(DnsAutodetectOptions.ConfigFiles | DnsAutodetectOptions.Registry);

// Example of XML config file settings which must be placed into <appSettings> section of the file
// (<appSettings> can also appear as <applicationSettings> in .NET 2.0).
// It defines 2 DNS servers with top (0) priority and 1 backup server with lower (1) priority
// (for 192.168.0.2 server, the priority is not specified and thus defaults to the top priority):

<add key="MailBee.DnsMX.DnsServerCollection" value="192.168.0.1,0;192.168.0.2;192.168.0.100,1"/>
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.DnsMX

' The actual code
Dim smtp As New Smtp
smtp.DnsServers.Autodetect(DnsAutodetectOptions.ConfigFiles Or DnsAutodetectOptions.Registry)

' Example of XML config file settings which must be placed into <appSettings> section of the file
' (<appSettings> can also appear as <applicationSettings> in .NET 2.0).
' It defines 2 DNS servers with top (0) priority and 1 backup server with lower (1) priority
' (for 192.168.0.2 server, the priority is not specified and thus defaults to the top priority):

<add key="MailBee.DnsMX.DnsServerCollection" value="192.168.0.1,0;192.168.0.2;192.168.0.100,1"/>
See Also

Reference

MailBee.DnsMX Namespace
MailBee.SmtpMailSmtp


DnsCache Class

DnsCache Class
Provides properties and methods which allow the developer to control whether and how MailBee will cache DNS MX (and some other) records when performing DNS MX lookup and TXT queries.
Inheritance Hierarchy
SystemObject
MailBee.DnsMXDnsCache

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DnsCache
Public Class DnsCache

The DnsCache type exposes the following members.

Methods
 | Name | Description
 | Clear | Removes all existing entries from the DNS cache.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
Count | Gets the number of DNS records already in the cache.
Enabled | Gets or sets whether DNS records caching should be used.
SmtpMXMaxFailureCount | Gets or sets the maximum number of seriated failures of the SMTP MX server required in order to consider the SMTP MX server down.
SmtpMXNextAttemptInterval | Gets or sets the amount of time (in milliseconds) the failed SMTP MX server spends in quarantine.
Timeout | Gets or sets the interval which specifies for how long DNS records in the cache remain actual.
Top
Remarks

By default, DNS MX caching is enabled which may greatly increase performance of "direct send" operations which involve sending large amounts of e-mails directly to end recipients mail servers (without using SMTP relay server).

MailBee also maintains TXT and PTR records cache. TXT records are used for DomainKeys sender verification (a sort of antispam technology). Checking PTR records (reverse DNS) of the IP address from which the e-mail came (extracted from MailMessage.TimeStamps[0].From) is another method of sender verification.

Note Note
DNS cache maintained by DnsCache class is shared by all instances of Smtp objects within the application domain.
See Also

Reference

MailBee.DnsMX Namespace
SmtpDnsServers


DnsCache Methods

DnsCache Methods

The DnsCache type exposes the following members.

Methods
 | Name | Description
 | Clear | Removes all existing entries from the DNS cache.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache.Clear Method

DnsCacheClear Method
Removes all existing entries from the DNS cache.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static void Clear()
Public Shared Sub Clear
Remarks
This method is thread-safe.
See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache Properties

DnsCache Properties

The DnsCache type exposes the following members.

Properties
Name | Description
Count | Gets the number of DNS records already in the cache.
Enabled | Gets or sets whether DNS records caching should be used.
SmtpMXMaxFailureCount | Gets or sets the maximum number of seriated failures of the SMTP MX server required in order to consider the SMTP MX server down.
SmtpMXNextAttemptInterval | Gets or sets the amount of time (in milliseconds) the failed SMTP MX server spends in quarantine.
Timeout | Gets or sets the interval which specifies for how long DNS records in the cache remain actual.
Top
See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache.Count Property

DnsCacheCount Property
Gets the number of DNS records already in the cache.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int Count { get; }
Public Shared ReadOnly Property Count As Integer
    Get

Property Value

Type: Int32
An integer value specifying the number of DNS MX, TXT and PTR records already in the cache. The value is zero if the cache is empty.
See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache.Enabled Property

DnsCacheEnabled Property
Gets or sets whether DNS records caching should be used.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool Enabled { get; set; }
Public Shared Property Enabled As Boolean
    Get
    Set

Property Value

Type: Boolean
true if DNS records caching is enabled; otherwise, false. The default value is true.
Remarks
Under normal circumstances, disabling DNS caching is not recommended due to significant performance impact. However, this may help in troubleshooting.
See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache.SmtpMXMaxFailureCount Property

DnsCacheSmtpMXMaxFailureCount Property
Gets or sets the maximum number of seriated failures of the SMTP MX server required in order to consider the SMTP MX server down.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int SmtpMXMaxFailureCount { get; set; }
Public Shared Property SmtpMXMaxFailureCount As Integer
    Get
    Set

Property Value

Type: Int32
The number of seriated failures of the SMTP MX server which needs to be achieved in order to consider this server down. The default value is 1.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is less than 1.
Remarks

When making connections to SMTP MX servers, it may happen that the connection with the server cannot be temporarily established. However, the server may revert back to function shortly (on the next connection attempt or after certain time interval elapses).

Note Note
This property does not set the number of attempts to connect to the server prior to returning an error. It only sets whether MailBee should cache the information about bad status of the given SMTP MX server for subsequent sending of other e-mail messages if any. In other words, this property makes sense only if the application sends multiple messages, not just one. Also, this property will not have any effect if DNS MX caching is disabled (Enabled is false).

If the given SMTP MX server reached SmtpMXMaxFailureCount number of seriated failures, MailBee won't try to connect to it until SmtpMXNextAttemptInterval elapses.

See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache.SmtpMXNextAttemptInterval Property

DnsCacheSmtpMXNextAttemptInterval Property
Gets or sets the amount of time (in milliseconds) the failed SMTP MX server spends in quarantine.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int SmtpMXNextAttemptInterval { get; set; }
Public Shared Property SmtpMXNextAttemptInterval As Integer
    Get
    Set

Property Value

Type: Int32
The length of the period (in milliseconds) the failed SMTP MX server spends in quarantine. The default value is 1000 (1 second).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
If the SMTP MX server could not be contacted SmtpMXMaxFailureCount times, it's set in quarantine for SmtpMXNextAttemptInterval milliseconds. During this interval, the server is not used (other servers used if any, or an error occurs if all the servers are in quarantine). When SmtpMXNextAttemptInterval elapses, MailBee may try this server again. If it fails again, it's been put in quarantine again (this time, SmtpMXMaxFailureCount will have no effect since the server is already known as dead).
Note Note
This property will have no effect if DNS MX caching is disabled (Enabled is false).
See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsCache.Timeout Property

DnsCacheTimeout Property
Gets or sets the interval which specifies for how long DNS records in the cache remain actual.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static int Timeout { get; set; }
Public Shared Property Timeout As Integer
    Get
    Set

Property Value

Type: Int32
Positive integer value which specifies the amount time (in minutes) to allow DNS records remain in the cache. The default value is 90 minutes.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative or zero.
Remarks

By default, a DNS record in the cache considered be valid for 90 minutes since the moment it was added to the cache. Increasing Timeout value may improve performance in the case if DNS records of recipient domains change rarely.

In the case if all DNS records become invalid (for instance, after reconfiguration of the network) and the cache is no longer valid, the developer may manually initialize it by either running the application again or calling Clear method to clear the DNS cache of the existing instance of the application.

See Also

Reference

DnsCache Class
MailBee.DnsMX Namespace


DnsReplyCode Enumeration

DnsReplyCode Enumeration
Lists DNS server known reply codes.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum DnsReplyCode
Public Enumeration DnsReplyCode
Members
Member name | Value | Description
NoError | 0 | No error condition.
FormatError | 1 | Format error - The name server was unable to interpret the query.
ServerFailure | 2 | Server failure - The name server was unable to process this query due to a problem with the name server.
NameError | 3 | Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist.
NotImplemented | 4 | Not Implemented - The name server does not support the requested kind of query.
Refused | 5 | Refused - The name server refuses to perform the specified operation for policy reasons.
See Also

Reference

MailBee.DnsMX Namespace


DnsServer Class

DnsServer Class
Represents a DNS server to be queried about domain names of the Internet hosts.
Inheritance Hierarchy
SystemObject
MailBee.DnsMXDnsServer

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class DnsServer : ISortableByPriority
<SerializableAttribute>
Public Class DnsServer
    Implements ISortableByPriority

The DnsServer type exposes the following members.

Constructors
 | Name | Description
Public method | DnsServer | Initializes a new instance of the DnsServer class with "127.0.0.1" (localhost) IP address, and assigns the top priority to this instance.
Public method | DnsServer(String) | Initializes a new instance of the DnsServer class with the given IP address string, and assigns the top priority to this instance.
Public method | DnsServer(String, Int32) | Initializes a new instance of the DnsServer class with the given IP address string and priority value.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Reset | Resets failure count to 0.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | FailureCount | Gets the number of repeated failures of the DNS server.
Public property | Host | Gets or sets an IP address of the DNS server as string.
Public property | IP | Gets an IP address of the DNS server as IPAddress.
Public property | Priority | Gets or sets a value of the preference of the DNS server. Lower values are preferred.
Public property | TcpTimeout | Gets or sets the amount of time (in milliseconds) the system will wait for TCP message to be sent or received before the operation times out.
Public property | TryTcp | Gets or sets if MailBee can make DNS queries via TCP.
Public property | UdpRetryCount | Gets or sets a value of the maximum number of times to attempt to connect to the DNS server using the UDP protocol.
Public property | UdpTimeout | Gets or sets the amount of time (in milliseconds) the system will wait for UDP message to be sent or received before the operation times out.
Top
Remarks

MailBee uses instances of this class in order to lookup MX records of the Internet hosts. For example, Smtp component can perform MX lookup queries in direct-send scenarios (sending e-mails without SMTP relay server).

You can also perform DNS MX, TXT and PTR/rDNS queries expilicitly. See Smtp methods like GetMXHosts(String), GetPtrData(String) and GetTxtData(String) for details.

RblFilter class uses DNS servers to query RBL databases.

See Also

Reference

MailBee.DnsMX Namespace


DnsServer Constructor

DnsServer Constructor
Overload List
 | Name | Description
Public method | DnsServer | Initializes a new instance of the DnsServer class with "127.0.0.1" (localhost) IP address, and assigns the top priority to this instance.
Public method | DnsServer(String) | Initializes a new instance of the DnsServer class with the given IP address string, and assigns the top priority to this instance.
Public method | DnsServer(String, Int32) | Initializes a new instance of the DnsServer class with the given IP address string and priority value.
Top
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer Constructor

DnsServer Constructor
Initializes a new instance of the DnsServer class with "127.0.0.1" (localhost) IP address, and assigns the top priority to this instance.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer()
Public Sub New
Remarks
This constructor should not be used unless the DNS server is running on the same machine.
See Also

Reference

DnsServer Class
DnsServer Overload
MailBee.DnsMX Namespace


DnsServer Constructor (String)

DnsServer Constructor (String)
Initializes a new instance of the DnsServer class with the given IP address string, and assigns the top priority to this instance.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer(
    string host
)
Public Sub New (
    host As String
)

Parameters

host
Type: SystemString
IP address of the DNS server.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | host is not a valid IP address string.
Remarks
You can find more information on the server priority in SortableByPriorityCollection class documentation.
See Also

Reference

DnsServer Class
DnsServer Overload
MailBee.DnsMX Namespace
MailBeeSortableByPriorityCollection


DnsServer Constructor (String, Int32)

DnsServer Constructor (String, Int32)
Initializes a new instance of the DnsServer class with the given IP address string and priority value.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer(
    string host,
    int priority
)
Public Sub New (
    host As String,
    priority As Integer
)

Parameters

host
Type: SystemString
IP address of the DNS server.
priority
Type: SystemInt32
A preference of the DNS server. Lower values are preferred.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | host is not a valid IP address string.
Remarks
You can find more information on the server priority in SortableByPriorityCollection class documentation.
See Also

Reference

DnsServer Class
DnsServer Overload
MailBee.DnsMX Namespace
MailBeeSortableByPriorityCollection


DnsServer Methods

DnsServer Methods

The DnsServer type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Reset | Resets failure count to 0.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.Reset Method

DnsServerReset Method
Resets failure count to 0.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reset()
Public Sub Reset
Remarks
MailBee calls method each time the DNS server properly responds. If, however, the DNS server was banned by MailBee due to multiple repeated failures, the developer may call this method to force MailBee to use the DNS server again.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer Properties

DnsServer Properties

The DnsServer type exposes the following members.

Properties
 | Name | Description
Public property | FailureCount | Gets the number of repeated failures of the DNS server.
Public property | Host | Gets or sets an IP address of the DNS server as string.
Public property | IP | Gets an IP address of the DNS server as IPAddress.
Public property | Priority | Gets or sets a value of the preference of the DNS server. Lower values are preferred.
Public property | TcpTimeout | Gets or sets the amount of time (in milliseconds) the system will wait for TCP message to be sent or received before the operation times out.
Public property | TryTcp | Gets or sets if MailBee can make DNS queries via TCP.
Public property | UdpRetryCount | Gets or sets a value of the maximum number of times to attempt to connect to the DNS server using the UDP protocol.
Public property | UdpTimeout | Gets or sets the amount of time (in milliseconds) the system will wait for UDP message to be sent or received before the operation times out.
Top
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.FailureCount Property

DnsServerFailureCount Property
Gets the number of repeated failures of the DNS server.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int FailureCount { get; }
Public ReadOnly Property FailureCount As Integer
    Get

Property Value

Type: Int32
The number of repeated failures of the DNS server. The default value is 0.
Remarks
You can find more information on how MailBee handles DNS server failures in DnsMaxFailureCount property documentation.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.Host Property

DnsServerHost Property
Gets or sets an IP address of the DNS server as string.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Host { get; set; }
Public Property Host As String
    Get
    Set

Property Value

Type: String
IP address of the DNS server.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | Host is not a valid IP address string.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.IP Property

DnsServerIP Property
Gets an IP address of the DNS server as IPAddress.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IPAddress IP { get; }
Public ReadOnly Property IP As IPAddress
    Get

Property Value

Type: IPAddress
IP address of the DNS server.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.Priority Property

DnsServerPriority Property
Gets or sets a value of the preference of the DNS server. Lower values are preferred.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Priority { get; set; }
Public Property Priority As Integer
    Get
    Set

Property Value

Type: Int32
An integer value in the range 0 to 999 indicating the preference of the DNS server.
Remarks
You can find more information on the server priority in SortableByPriorityCollection class documentation.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace
MailBeeSortableByPriorityCollection


DnsServer.TcpTimeout Property

DnsServerTcpTimeout Property
Gets or sets the amount of time (in milliseconds) the system will wait for TCP message to be sent or received before the operation times out.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TcpTimeout { get; set; }
Public Property TcpTimeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the system will wait for TCP message to be sent or received before the operation times out. The default value is 5000 (5 seconds).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | UdpTimeout is negative.
Remarks
If you set the property with a value between 1 and 499, .NET Framework will internally use the value of 500. There is no way to have UDP timeout value less than 500 milliseconds.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.TryTcp Property

DnsServerTryTcp Property
Gets or sets if MailBee can make DNS queries via TCP.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool TryTcp { get; set; }
Public Property TryTcp As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will also make DNS TCP query in case if DNS UDP query returned no data or if there was no UDP query at all; if false, only DNS UDP queries are allowed. The default is true.
Exceptions
Exception | Condition
MailBeeInvalidStateException | An attempt to set this property to false when the current state of DnsServer object denotes that DNS UDP queries are disabled (UdpRetryCount is 0).
Remarks

UDP always precedes TCP. TCP can only be tried if UDP fails or if UDP was disabled at all.

For making DNS MX queries, leave this value true (some DNS servers like Google's 8.8.8.8 provide meaningful replies in TCP only). The same applies to DKIM/DomainKeys checks.

For making DNS RBL queries (actually, DNS A requests), it's better to disable TryTcp for performance sake. The nature of DNS RBL query is that if no requested A record is found, it simply means the respective IP address is not in the blacklist, it's not an error of any kind. Therefore retrying with TCP would be waste of resources.

If DNS UDP queries are disabled (UdpRetryCount is zero), this property must remain true (otherwise, neither TCP not UDP would be available for making a DNS query).

See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.UdpRetryCount Property

DnsServerUdpRetryCount Property
Gets or sets a value of the maximum number of times to attempt to connect to the DNS server using the UDP protocol.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int UdpRetryCount { get; set; }
Public Property UdpRetryCount As Integer
    Get
    Set

Property Value

Type: Int32
An integer value in the range 0 to 10 indicating the maximum number of times to attempt to connect to the DNS server using the UDP protocol. The default value is 2.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | UdpRetryCount is less than 0 or greater than 10.
MailBeeInvalidStateException | An attempt to set this property to 0 when the current state of DnsServer object denotes that DNS TCP queries are disabled (TryTcp is false).
Remarks
In case if UDP retry count exceeded, MailBee will also make yet another attempt via TCP (unless TryTcp is false).
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServer.UdpTimeout Property

DnsServerUdpTimeout Property
Gets or sets the amount of time (in milliseconds) the system will wait for UDP message to be sent or received before the operation times out.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int UdpTimeout { get; set; }
Public Property UdpTimeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the system will wait for UDP message to be sent or received before the operation times out. The default value is 5000 (5 seconds).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | UdpTimeout is negative.
Remarks
If you set the property with a value between 1 and 499, .NET Framework will internally use the value of 500. There is no way to have UDP timeout value less than 500 milliseconds.
See Also

Reference

DnsServer Class
MailBee.DnsMX Namespace


DnsServerCollection Class

DnsServerCollection Class
Represents a sorted collection of DnsServer objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBeeSortableByPriorityCollection
MailBee.DnsMXDnsServerCollection

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class DnsServerCollection : SortableByPriorityCollection
<SerializableAttribute>
Public Class DnsServerCollection
    Inherits SortableByPriorityCollection

The DnsServerCollection type exposes the following members.

Constructors
 | Name | Description
Public method | DnsServerCollection | Initializes a new instance of the DnsServerCollection class
Top
Methods
Name Description
Public method Add(String)
Adds a top (0) priority DNS server under the specified IP address to the collection and sorts the collection according to the elements priorities.
Public method Add(DnsServer)
Adds a DnsServer to the collection and sorts the collection according to the elements priorities.
Public method Add(String, Int32)
Adds a DNS server under the specified IP address and with a particular priority to the collection and sorts the collection according to the elements priorities.
Public method Autodetect
Clears and then populates the collection with DnsServer objects by looking up the following sources:
  1. "MailBee.DnsMX.DnsServerCollection" key in the config file (and/or DnsServers if it's not empty).
  2. Network interface.
  3. Windows registry.
  4. WMI database.
This overload will skip DNS servers with IPv6 addresses and won't add root 8.8.8.8 and 8.8.4.4 servers. See Autodetect(DnsAutodetectOptions) overload for more options.
Public method Autodetect(DnsAutodetectOptions)
Clears and then populates the collection with DnsServer objects by looking up the specified sources.
Public method Clear
Removes all objects from the CollectionBase instance. This method cannot be overridden.
(Inherited from CollectionBase.)
Public method Equals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected method Finalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public method GetEnumerator
Returns an enumerator that iterates through the CollectionBase instance.
(Inherited from CollectionBase.)
Public method GetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public method GetType
Gets the Type of the current instance.
(Inherited from Object.)
Protected method MemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Protected method OnClear
Performs additional custom processes when clearing the contents of the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnClearComplete
Performs additional custom processes after clearing the contents of the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnInsert
Performs additional custom processes before inserting a new element into the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnInsertComplete
Performs additional custom processes after inserting a new element into the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnRemove
Performs additional custom processes when removing an element from the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnRemoveComplete
Performs additional custom processes after removing an element from the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnSet
Performs additional custom processes before setting a value in the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnSetComplete
Performs additional custom processes after setting a value in the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnValidate
Performs additional custom processes when validating a value.
(Inherited from CollectionBase.)
Public method Remove
Removes the specified DnsServer object from the collection.
Public method RemoveAt
Removes the element at the specified index of the CollectionBase instance. This method is not overridable.
(Inherited from CollectionBase.)
Public method SortByPriority
Sorts the items in the collection by their priority value.
(Inherited from SortableByPriorityCollection.)
Public method ToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the element at the specified index.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks
When DnsServers collection is populated with at least one DNS server of higher priority than the top priority SMTP server in SmtpServers collection (or if SMTP collection is empty), Smtp component will by default send e-mails in direct send mode (via MX lookup).
See Also

Reference

MailBee.DnsMX Namespace


DnsServerCollection Constructor

DnsServerCollection Constructor
Initializes a new instance of the DnsServerCollection class

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServerCollection()
Public Sub New
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


DnsServerCollection Methods

DnsServerCollection Methods

The DnsServerCollection type exposes the following members.

Methods
Name Description
Public method Add(String)
Adds a top (0) priority DNS server under the specified IP address to the collection and sorts the collection according to the elements priorities.
Public method Add(DnsServer)
Adds a DnsServer to the collection and sorts the collection according to the elements priorities.
Public method Add(String, Int32)
Adds a DNS server under the specified IP address and with a particular priority to the collection and sorts the collection according to the elements priorities.
Public method Autodetect
Clears and then populates the collection with DnsServer objects by looking up the following sources:
  1. "MailBee.DnsMX.DnsServerCollection" key in the config file (and/or DnsServers if it's not empty).
  2. Network interface.
  3. Windows registry.
  4. WMI database.
This overload will skip DNS servers with IPv6 addresses and won't add root 8.8.8.8 and 8.8.4.4 servers. See Autodetect(DnsAutodetectOptions) overload for more options.
Public method Autodetect(DnsAutodetectOptions)
Clears and then populates the collection with DnsServer objects by looking up the specified sources.
Public method Clear
Removes all objects from the CollectionBase instance. This method cannot be overridden.
(Inherited from CollectionBase.)
Public method Equals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected method Finalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public method GetEnumerator
Returns an enumerator that iterates through the CollectionBase instance.
(Inherited from CollectionBase.)
Public method GetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public method GetType
Gets the Type of the current instance.
(Inherited from Object.)
Protected method MemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Protected method OnClear
Performs additional custom processes when clearing the contents of the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnClearComplete
Performs additional custom processes after clearing the contents of the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnInsert
Performs additional custom processes before inserting a new element into the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnInsertComplete
Performs additional custom processes after inserting a new element into the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnRemove
Performs additional custom processes when removing an element from the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnRemoveComplete
Performs additional custom processes after removing an element from the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnSet
Performs additional custom processes before setting a value in the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnSetComplete
Performs additional custom processes after setting a value in the CollectionBase instance.
(Inherited from CollectionBase.)
Protected method OnValidate
Performs additional custom processes when validating a value.
(Inherited from CollectionBase.)
Public method Remove
Removes the specified DnsServer object from the collection.
Public method RemoveAt
Removes the element at the specified index of the CollectionBase instance. This method is not overridable.
(Inherited from CollectionBase.)
Public method SortByPriority
Sorts the items in the collection by their priority value.
(Inherited from SortableByPriorityCollection.)
Public method ToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


DnsServerCollection.Add Method

DnsServerCollectionAdd Method
Overload List
 | Name | Description
Public method | Add(String) | Adds a top (0) priority DNS server under the specified IP address to the collection and sorts the collection according to the elements priorities.
Public method | Add(DnsServer) | Adds a DnsServer to the collection and sorts the collection according to the elements priorities.
Public method | Add(String, Int32) | Adds a DNS server under the specified IP address and with a particular priority to the collection and sorts the collection according to the elements priorities.
Top
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


DnsServerCollection.Add Method (String)

DnsServerCollectionAdd Method (String)
Adds a top (0) priority DNS server under the specified IP address to the collection and sorts the collection according to the elements priorities.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer Add(
    string host
)
Public Function Add (
    host As String
) As DnsServer

Parameters

host
Type: SystemString
IP address of the DNS server to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).

Return Value

Type: DnsServer
A reference to DnsServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | host is not a valid IP address string.
See Also

Reference

DnsServerCollection Class
Add Overload
MailBee.DnsMX Namespace


DnsServerCollection.Add Method (DnsServer)

DnsServerCollectionAdd Method (DnsServer)
Adds a DnsServer to the collection and sorts the collection according to the elements priorities.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    DnsServer server
)
Public Sub Add (
    server As DnsServer
)

Parameters

server
Type: MailBee.DnsMXDnsServer
A DnsServer to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).
Remarks
It's recommended to add elements from higher priority to lower priority. Thus, the elements will stay in the same order as they were added.
See Also

Reference

DnsServerCollection Class
Add Overload
MailBee.DnsMX Namespace


DnsServerCollection.Add Method (String, Int32)

DnsServerCollectionAdd Method (String, Int32)
Adds a DNS server under the specified IP address and with a particular priority to the collection and sorts the collection according to the elements priorities.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer Add(
    string host,
    int priority
)
Public Function Add (
    host As String,
    priority As Integer
) As DnsServer

Parameters

host
Type: SystemString
IP address of the DNS server to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).
priority
Type: SystemInt32
A preference of the DNS server. Lower values are preferred.

Return Value

Type: DnsServer
A reference to DnsServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | host is not a valid IP address string.
Remarks
It's recommended to add elements from higher priority to lower priority. Thus, the elements will stay in the same order as they were added.
See Also

Reference

DnsServerCollection Class
Add Overload
MailBee.DnsMX Namespace


DnsServerCollection.Autodetect Method

DnsServerCollectionAutodetect Method
Overload List
Name Description
Public method Autodetect
Clears and then populates the collection with DnsServer objects by looking up the following sources:
  1. "MailBee.DnsMX.DnsServerCollection" key in the config file (and/or DnsServers if it's not empty).
  2. Network interface.
  3. Windows registry.
  4. WMI database.
This overload will skip DNS servers with IPv6 addresses and won't add root 8.8.8.8 and 8.8.4.4 servers. See Autodetect(DnsAutodetectOptions) overload for more options.
Public method Autodetect(DnsAutodetectOptions)
Clears and then populates the collection with DnsServer objects by looking up the specified sources.
Top
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


DnsServerCollection.Autodetect Method

DnsServerCollectionAutodetect Method
Clears and then populates the collection with DnsServer objects by looking up the following sources:
  1. "MailBee.DnsMX.DnsServerCollection" key in the config file (and/or DnsServers if it's not empty).
  2. Network interface.
  3. Windows registry.
  4. WMI database.
This overload will skip DNS servers with IPv6 addresses and won't add root 8.8.8.8 and 8.8.4.4 servers. See Autodetect(DnsAutodetectOptions) overload for more options.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Autodetect()
Public Function Autodetect As Boolean

Return Value

Type: Boolean
true if at least one DNS server was found; otherwise, false.
Remarks

Once at least one DNS server definition is found, these definitions are added to the collection as DnsServer objects, and the method returns.

You can find more information and code samples on MailBee DNS server autodetection mechanism in DnsAutodetectOptions enumeration documentation.

Note Note
Network interface and WMI database search requires Full trust for MailBee assembly. If the current security setting is lower than Full trust, Network interface and WMI database search won't find any DNS server definitions.
See Also

Reference

DnsServerCollection Class
Autodetect Overload
MailBee.DnsMX Namespace
MailBee.DnsMXDnsAutodetectOptions


DnsServerCollection.Autodetect Method (DnsAutodetectOptions)

DnsServerCollectionAutodetect Method (DnsAutodetectOptions)
Clears and then populates the collection with DnsServer objects by looking up the specified sources.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Autodetect(
    DnsAutodetectOptions options
)
Public Function Autodetect (
    options As DnsAutodetectOptions
) As Boolean

Parameters

options
Type: MailBee.DnsMXDnsAutodetectOptions
The sources to look DNS server definitons for.

Return Value

Type: Boolean
true if at least one DNS server was found; otherwise, false.
Remarks
Once at least one DNS server definition is found, these definitions are added to the collection as DnsServer objects, and the method returns.
Note Note
WMI database search requires Full trust for MailBee assembly. If the current security setting is lower than Full trust, WMI database search won't find any DNS server definitions.
See Also

Reference

DnsServerCollection Class
Autodetect Overload
MailBee.DnsMX Namespace
MailBee.DnsMXDnsAutodetectOptions


DnsServerCollection.Remove Method

DnsServerCollectionRemove Method
Removes the specified DnsServer object from the collection.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Remove(
    DnsServer server
)
Public Sub Remove (
    server As DnsServer
)

Parameters

server
Type: MailBee.DnsMXDnsServer
A reference to the DnsServer object to be removed.
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


DnsServerCollection Properties

DnsServerCollection Properties

The DnsServerCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the element at the specified index.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


DnsServerCollection.Item Property

DnsServerCollectionItem Property
Gets or sets the element at the specified index.

Namespace: MailBee.DnsMX
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServer this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As DnsServer
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index of the entry to get or set.

Property Value

Type: DnsServer
The element at the specified index.
See Also

Reference

DnsServerCollection Class
MailBee.DnsMX Namespace


MailBee.EwsMail Namespace

MailBee.EwsMail Namespace

MailBee.EwsMail namespace provides a set of types which let you communicate with MS Exchange server via EWS (Exchange Web Services) protocol. Under the hood, this feature uses EWS Managed API library. EWS functionality resides in separate DLLs. In Nuget, you need to install MailBee.NET.EWS package to get the required libraries.

EWS support is only available in .NET Framework v3.5-4.8 and .NET Core 2.0+. In UWP, it requires Windows 10 Fall Creators Update as the minimum target for the project. Only sync methods are supported in .NET Framework and only async methods are supported in .NET Core and UWP.

Classes
 | Class | Description
 | Ews | Provides properties and methods for working with e-mails on MS Exchange server via Exchange Web Services.
Public class | EwsFolder | Represents a folder in Exchange account.
Public class | EwsItem | Represents an item in MS Exchange folder (a mail message, contact, appointment, etc).
Public class | EwsItemList | Represents a collection o EwsItem objects, with optional paging capability.
Public class | MailBeeEwsException | The exception that is thrown when Managed EWS API layer throws an exception.
Enumerations
 | Enumeration | Description
Public enumeration | EwsItemParts | Defines message elements available for download using DownloadItem(ItemId, EwsItemParts) or DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) methods.


MailBeeEwsException Class

MailBeeEwsException Class
The exception that is thrown when Managed EWS API layer throws an exception.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.EwsMailMailBeeEwsException

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeEwsException : MailBeeEmailProtocolException
<SerializableAttribute>
Public Class MailBeeEwsException
    Inherits MailBeeEmailProtocolException

The MailBeeEwsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeEwsException | Initializes a new instance of the MailBeeEwsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This is wrapper for exceptions thrown by EWS Managed API. You can access the original exception via InnerException property. ErrorCode can be either EwsLocalException (denoting that exception is caused by a client) or EwsRemoteException (denoting an error reported by the MS Exchange server).
See Also

Reference

MailBee.EwsMail Namespace


MailBeeEwsException Constructor

MailBeeEwsException Constructor
Initializes a new instance of the MailBeeEwsException class

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeEwsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeEwsException Class
MailBee.EwsMail Namespace


MailBeeEwsException Methods

MailBeeEwsException Methods

The MailBeeEwsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeEwsException Class
MailBee.EwsMail Namespace


MailBeeEwsException Properties

MailBeeEwsException Properties

The MailBeeEwsException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeEwsException Class
MailBee.EwsMail Namespace


MailBeeEwsException Events

MailBeeEwsException Events

The MailBeeEwsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeEwsException Class
MailBee.EwsMail Namespace


Ews Class

Ews Class
Provides properties and methods for working with e-mails on MS Exchange server via Exchange Web Services.
Inheritance Hierarchy
SystemObject
MailBee.EwsMailEws

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Ews : IComponent, IDisposable
Public Class Ews
    Implements IComponent, IDisposable

The Ews type exposes the following members.

Constructors
 | Name | Description
Public method | Ews | Creates an instance of Ews class.
Public method | Ews(String) | Creates and unlocks an instance of Ews class.
Top
Methods
 | Name | Description
Public method | AddAttachmentToItem | Adds an attachment to an existing item.
Public method | AddAttachmentToItemAsync | Async/await version of AddAttachmentToItem(ItemId, String, String).
Public method | Autodiscover | Automatically determines the URL of the EWS server.
Public method | CopyItem | Copies the specified item (e.g. mail message) into the specified folder.
Public method | CopyItemAsync | Async/await version of CopyItem(ItemId, FolderId).
Public method | CreateFolder | Creates a folder in the MS Exchange account.
Public method | CreateFolderAsync | Async/await version of CreateFolder(String, FolderId).
Public method | CreatePropSet | Creates EWS Managed API PropertySet object.
Public method | DeleteAttachment | Deletes the attachment with the specified filename from the specified item.
Public method | DeleteAttachmentAsync | Async/await version of DeleteAttachment(ItemId, String, Boolean, Boolean).
Public method | DeleteAttachments | Deletes all attachments in the specified item.
Public method | DeleteAttachmentsAsync | Async/await version of DeleteAttachments(ItemId).
Public method | DeleteFolder | Deletes a folder with the specified ID.
Public method | DeleteFolderAsync | Async/await version of DeleteFolder(FolderId).
Public method | DeleteItem | Deletes the specified item (e.g. mail message).
Public method | DeleteItemAsync | Async/await version of DeleteItem(ItemId).
Public method | DeleteItems | Deletes the specified item (e.g. mail message).
Public method | DeleteItemsAsync | Async/await version of DeleteItems(IEnumerableItemId).
Public method | Dispose | Closes all opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.
Public method | DownloadEntireMessage | Downloads the specified item by its ID and returns it as MailMessage object.
Public method | DownloadEntireMessageAsync | Async/await version of DownloadEntireMessage(ItemId).
Public method | DownloadFolderByFullName(String) | Gets the reference to the folder denoted by its full name in the MS Exchange account.
Public method | DownloadFolderByFullName(FolderId, String) | Gets the reference to the given folder in the specified containing folder in the MS Exchange account.
Public method | DownloadFolderByFullName(String, Int32) | Gets the reference to the folder denoted by its full name in the MS Exchange account.
Public method | DownloadFolderByFullNameAsync(String) | Async/await version of DownloadFolderByFullName(String).
Public method | DownloadFolderByFullNameAsync(FolderId, String) | Async/await version of DownloadFolderByFullName(FolderId, String).
Public method | DownloadFolderByFullNameAsync(String, Int32) | Async/await version of DownloadFolderByFullName(String, Int32).
Public method | DownloadFolderById(FolderId) | Gets the reference to the folder with given ID in the MS Exchange account.
Public method | DownloadFolderById(FolderId, PropertySet) | Gets the reference to the folder with given ID in the MS Exchange account, also requesting the specified properties.
Public method | DownloadFolderByIdAsync(FolderId) | Async/await version of DownloadFolderById(FolderId).
Public method | DownloadFolderByIdAsync(FolderId, PropertySet) | Async/await version of DownloadFolderById(FolderId, PropertySet).
Public method | DownloadFolderByShortName | Gets the reference to the given folder in the MS Exchange account.
Public method | DownloadFolderByShortNameAsync | Async/await version of DownloadFolderByShortName(FolderId, String).
Public method | DownloadFolders(Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFolders(FolderId, Boolean, Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFolders(FolderId, FolderView, SearchFilter, Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFoldersAsync(Boolean) | Async/await version of DownloadFolders(Boolean).
Public method | DownloadFoldersAsync(FolderId, Boolean, Boolean) | Async/await version of DownloadFolders(FolderId, Boolean, Boolean).
Public method | DownloadFoldersAsync(FolderId, FolderView, SearchFilter, Boolean) | Async/await version of DownloadFolders(FolderId, FolderView, SearchFilter, Boolean).
Public method | DownloadItem(FolderId, Int32) | Downloads an item in the specified folder at the specified index.
Public method | DownloadItem(ItemId, EwsItemParts) | Downloads the specified portions of the specified item by its ID.
Public method | DownloadItem(ItemId, PropertySet) | Downloads the specified item by its ID using PropertySet settings.
Public method | DownloadItem(FolderId, Int32, EwsItemParts) | Downloads the specified portions of an Exchange item in the specified folder at the specified index.
Public method | DownloadItem(FolderId, Int32, PropertySet) | Downloads an item in the specified folder at the specified index using PropertySet settings.
Public method | DownloadItemAsync(FolderId, Int32) | Async/await version of DownloadItem(FolderId, Int32).
Public method | DownloadItemAsync(ItemId, EwsItemParts) | Async/await version of DownloadItem(ItemId, EwsItemParts).
Public method | DownloadItemAsync(ItemId, PropertySet) | Async/await version of DownloadItem(ItemId, PropertySet).
Public method | DownloadItemAsync(FolderId, Int32, EwsItemParts) | Async/await version of DownloadItem(FolderId, Int32, EwsItemParts).
Public method | DownloadItemAsync(FolderId, Int32, PropertySet) | Async/await version of DownloadItem(FolderId, Int32, PropertySet).
Public method | DownloadItemIds(FolderId, Boolean) | Downloads IDs of all or unread items in the specified folder.
Public method | DownloadItemIds(FolderId, ItemView, Boolean) | Downloads IDs of items in the specified folder in the specified ItemView range.
Public method | DownloadItemIdsAsync(FolderId, Boolean) | Async/await version of DownloadItemIds(FolderId, Boolean).
Public method | DownloadItemIdsAsync(FolderId, ItemView, Boolean) | Async/await version of DownloadItemIds(FolderId, ItemView, Boolean).
Public method | DownloadItems(FolderId, Boolean) | Downloads all or unread items in the specified folder.
Public method | DownloadItems(IEnumerableEwsItem, EwsItemParts) | Downloads the specified portions of the specified items.
Public method | DownloadItems(IEnumerableEwsItem, PropertySet) | Downloads the specified items using PropertySet settings.
Public method | DownloadItems(FolderId, ItemView, Boolean) | Downloads items in the specified folder in the specified ItemView range.
Public method | DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) | Downloads the specified portions of the items in the specified ItemView range in the specified folder.
Public method | DownloadItems(FolderId, ItemView, Boolean, PropertySet) | Downloads items in the specified folder in the specified ItemView range using PropertySet settings.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean) | Downloads items in the specified folder in the specified range.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) | Downloads the specified portions of Exchange items in the specified folder in the specified range.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet) | Downloads items in the specified folder in the specified range using PropertySet settings.
Public method | DownloadItemsAsync(FolderId, Boolean) | Async/await version of DownloadItems(FolderId, Boolean).
Public method | DownloadItemsAsync(IEnumerableEwsItem, EwsItemParts) | Async/await version of DownloadItems(IEnumerableEwsItem, EwsItemParts).
Public method | DownloadItemsAsync(IEnumerableEwsItem, PropertySet) | Async/await version of DownloadItems(IEnumerableEwsItem, PropertySet).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean) | Async/await version of DownloadItems(FolderId, ItemView, Boolean).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean, EwsItemParts) | Async/await version of DownloadItems(FolderId, ItemView, Boolean, EwsItemParts).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean, PropertySet) | Async/await version of DownloadItems(FolderId, ItemView, Boolean, PropertySet).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean, EwsItemParts) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean, PropertySet) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet).
Public method | DownloadNativeAttachments | Downloads attachments with the specified string IDs.
Public method | DownloadNativeAttachmentsAsync | Async/await version of DownloadNativeAttachments(String, Boolean).
Public method | EmptyFolder | Empties a folder with the specified ID.
Public method | EmptyFolderAsync | Async/await version of EmptyFolder(FolderId, Boolean).
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | EwsItemsToItemIds | Creates the list of ItemId objects from the collection of EwsItem objects.
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | FindFolderIdByFullName(String) | Gets the ID of the folder denoted by its full name in the MS Exchange account.
Public method | FindFolderIdByFullName(FolderId, String) | Gets the ID of the given folder in the specified containing folder in the MS Exchange account.
Public method | FindFolderIdByFullName(String, Int32) | Gets the ID of the given folder in the MS Exchange account.
Public method | FindFolderIdByFullNameAsync(String) | Async/await version of FindFolderIdByFullName(String).
Public method | FindFolderIdByFullNameAsync(FolderId, String) | Async/await version of FindFolderIdByFullName(FolderId, String).
Public method | FindFolderIdByFullNameAsync(String, Int32) | Async/await version of FindFolderIdByFullName(String, Int32).
Public method | FindFolderIdByShortName | Gets the ID of the given folder in the MS Exchange account.
Public method | FindFolderIdByShortNameAsync | Async/await version of FindFolderIdByShortName(FolderId, String).
Public method | FolderExists(String) | Checks if the folder with the specified full name exists in the MS Exchange account.
Public method | FolderExists(FolderId, String) | Checks if the given folder in the specified containing folder exists in the MS Exchange account.
Public method | FolderExistsAsync(String) | Async/await version of [!:FolderExists(FolderId)].
Public method | FolderExistsAsync(FolderId, String) | Async/await version of FolderExists(FolderId, String).
Public method | GetErrorDescription | Returns a textual description of the last occurred error.
Public method | GetExchangeVersionString | Gets the MS Exchange version as a string.
Public method | GetFolderByName | Finds the EwsFolder in the given list by the folder's full name.
Public method | GetFolderView | Gets FolderView instance tuned for listing all the folders in the account.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | InitEwsClient | Sets the default MS Exchange version.
Public method | InitEwsClient(ExchangeVersion) | Sets the specific MS Exchange version.
Public method | InitEwsClient(ExchangeVersion, TimeZoneInfo) | Sets the specific MS Exchange version.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | MoveFolder | Moves a folder into another folder.
Public method | MoveFolderAsync | Async/await version of MoveFolder(FolderId, FolderId).
Public method | MoveItem | Moves the specified item (e.g. mail message) into the specified folder.
Public method | MoveItemAsync | Async/await version of MoveItem(ItemId, FolderId).
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Public method | RenameFolder | Renames a folder in the MS Exchange account.
Public method | RenameFolderAsync | Async/await version of RenameFolder(String, FolderId).
Public method | RenameOrMoveFolder | Renames or moves a folder denoted by its full name rather than by ID.
Public method | RenameOrMoveFolderAsync | Async/await version of RenameOrMoveFolder(String, String, ListEwsFolder).
Public method | ResolveName | Resolves the specified name into e-mail addresses which exist on the given MS Exchange server.
Public method | ResolveNameAsync | Async/await version of ResolveName(String).
Public method | Search(FolderId, SearchFilter) | Searches the specified folder for items matching the given criteria.
Public method | Search(FolderId, SearchFilter, ItemView) | Searches the specified folder for items matching the given criteria and delivers the results accordingly the specified ItemView.
Public method | SearchAsync(FolderId, SearchFilter) | Async/await version of Search(FolderId, SearchFilter).
Public method | SearchAsync(FolderId, SearchFilter, ItemView) | Async/await version of Search(FolderId, SearchFilter, ItemView).
Public method | SendMessage | Sends MailBee mail message.
Public method | SendMessageAndSaveCopy | Sends MailBee mail message and saves a copy in Sent Items or user-defined folder.
Public method | SendMessageAndSaveCopyAsync | Async/await version of SendMessageAndSaveCopy(MailMessage, FolderId).
Public method | SendMessageAsync | Async/await version of SendMessage(MailMessage).
Public method | SetCredentials(ExchangeCredentials) | Sets the credentials (e.g. OAuth2) of the MS Exchange account for subsequent operations.
Public method | SetCredentials(String, String) | Sets the login and password of the MS Exchange account for subsequent operations.
Public method | SetServerUrl | Gets or sets the URL of EWS service on MS Exchange server.
Public method | TestConnection | Makes a test connection to validate the current settings.
Public method | TestConnectionAsync | Async/await version of TestConnection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | UpdateItem | Writes the changes made to the item to the MS Exchange server.
Public method | UpdateItemAsync | Async/await version of UpdateItem(EwsItem).
Public method | UploadMessage(FolderId, MailMessage, Boolean) | Uploads MailBee's MailMessage into the specified folder on the MS Exchange server.
Public method | UploadMessage(FolderId, Byte, Boolean) | Uploads raw message data into the specified folder on the MS Exchange server.
Public method | UploadMessageAsync(FolderId, MailMessage, Boolean) | Async/await version of UploadMessage(FolderId, MailMessage, Boolean).
Public method | UploadMessageAsync(FolderId, Byte, Boolean) | Async/await version of UploadMessage(FolderId, Byte, Boolean).
Top
Properties
 | Name | Description
Public property | CalculateFolderSizeOnDownload | Gets or sets if folder download operation must also calculate the folder size in bytes.
Public property | DefaultFolderClass | Gets or sets the default class string to assign to folders being created.
Public property | DeleteMethod | Gets or sets the mode of deleting items in EWS.
 | EnableCompatibilityMode | Gets or sets if MailBee should work around bugs of Microsoft.Exchange.WebServices.dll library.
 | EnableSslCertValidation | Gets or sets if SSL certificate of the server must be validated (in case of HTTPS connection).
Public property | FolderLevelDelimiter | Gets or sets which character to use when delimiting nested folder names.
Public property | LastResult | Gets a numeric code of the last error.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MessageFoldersFilter | Gets SearchFilter instance for reducing the list of the downloaded folders to mail-specific folders.
Public property | RequireHttps | Gets or sets if only HTTPS end points are allowed by auto-discover procedure.
Public property | RootFolderType | Gets or sets the top of folder hierarchy in an MS Exchange account.
Public property | Service | Gets a reference to the underlying ExchangeService object.
Public property | Site | Gets or sets the object to be used as a site for the component.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
Events
 | Name | Description
Public event | Disposed | Occurs after the component was disposed.
Public event | ErrorOccurred | Occurs when the MailBeeException is thrown.
Public event | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Ews.Log.MemoryLog is true).
Top
Remarks

This class is a wrapper for a subset of EWS Managed API library functions. This wrapper lets the developer work with EWS items in the way typical for other MailBee components (for instance, native exceptions of EWS Managed API are wrapped with MailBeeException, logging with Log property, etc). However, Ews class still exposes native EWS Managed API objects and types so you can utilize EWS Managed API for advanced tasks not directly covered by MailBee.

Note Note
In .NET Core, EWS is supported starting from .NET Core 2.0 (async methods only). In UWP, EWS requires Windows 10 Fall Creators Update as Min Target (async methods only). In .NET Framework, EWS is supported starting from .NET Framework v3.5 (sync methods only, not async). See more details in EWS Managed API topic.

To use EWS, you need to add a reference to MailBee.NET.EWS.DLL (MailBee.NET.EWS package if you're using Nuget). In its turn, MailBee.NET.EWS.DLL references Managed EWS API (Microsoft.Exchange.WebServices.dll or Microsoft.Exchange.WebServices.NETStandard.dll in case of .NET Framework or .NET Core/UWP, respectively). The MailBee.NET.EWS package installs the dependent DLLs automatically.

The typical procedure of accessing EWS:

  • Create Ews instance.
  • Init Ews instance by requesting the minimum required MS Exchange server version (InitEwsClient(ExchangeVersion) or InitEwsClient() if any version will suffice for you).
  • Call Autodiscover(String) or SetServerUrl(String) to specify the server host (automatically or manually, respectively).
  • Set the user credentials with SetCredentials(String, String) method (or SetCredentials(ExchangeCredentials) for OAuth 2.0).
  • Now you can access e-mails, folders, etc.

Examples
This sample demonstrates various scenarios of interacting with MS Exchange server. That's what we do there:
  • Connect to the explicitly defined server host or auto-discover the server host from the e-mail address.
  • Send e-mail and save the copy in Sent Items.
  • Download folders (get folder list, message count in each folder and its size in bytes).
  • Search, sort and download messages and their parts in different ways.
  • Display message contents, save, add and delete attachments.
  • Set Unread message flag.
  • Manipulate folders (e.g. create).
Note Note
In .NET Core or UWP, replace sync methods with their async versions.
C#
VB
Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using MailBee.EwsMail;
using Microsoft.Exchange.WebServices.Data;

// We need this because MailMessage type exists in both MailBee and Managed EWS.
using MailBeeMailMessage = MailBee.Mime.MailMessage;
using MailBeeAttachment = MailBee.Mime.Attachment;

class Program
{
    // We use this for displaying all strings but IDs.
    static string Shorten(string text, int maxLen)
    {
        if (text == null || text.Length <= maxLen)
        {
            return text;
        }
        else
        {
            return text.Substring(0, maxLen - 2) + "..";
        }
    }

    // Because IDs usually have diff. endings but the same beginning, we'd better leave ending part.
    static string ShortenId(string text)
    {
        int maxLen = 10;
        if (text == null || text.Length <= maxLen)
        {
            return text;
        }
        else
        {
            return ".." + text.Substring((text.Length - maxLen) + 2);
        }
    }

    // Remove CRLFs from strings to make console outputs easier to read.
    static string Flatten(string text)
    {
        if (text == null)
        {
            return null;
        }
        else
        {
            return text.Replace("\r\n", " ").Replace('\n', ' ');
        }
    }

    static void Main(string[] args)
    {
        // If license key is not set in app.config or Registry, set it here.
        MailBee.Global.LicenseKey = "MN1XX-XXXXXXXX-XXXX";

        // Enable self-signed server certificates. Remove this line to connect only to well-established servers with valid certificates.
        Ews.EnableSslCertValidation = false;
        Ews ewsClient = new Ews();

        // Normally, use TimeZoneInfo.Local, or use TimeZoneInfo.Utc if getting "The specified time zone isn't valid" errors.
        ewsClient.InitEwsClient(ExchangeVersion.Exchange2010_SP1, TimeZoneInfo.Utc);
        // ewsClient.InitEwsClient(ExchangeVersion.Exchange2013_SP1, TimeZoneInfo.Utc); // If your Exchange server is newer or Office 365.

        // Log file can be used for debugging. You can also enable .NET Sockets own log by adding System.Net trace listener in app.config file (.NET Framework only).
        ewsClient.Log.Enabled = true;
        ewsClient.Log.Filename = @"C:\Temp\log.txt";
        ewsClient.Log.Clear();

        // Disabled Gzip results in more traffic (that's bad) but makes debugging easier ("network.log" file will contain human-readable data).
        ewsClient.Service.AcceptGzipEncoding = false;

        string email = "user@contoso.com"; // On-premise Exchange account
        // string email = "user@company.onmicrosoft.com"; // Microsoft account

        // Set on-premise Exchange server URL.
        ewsClient.SetServerUrl("http://domain/EWS/Exchange.asmx");
        ewsClient.SetCredentials(email, "secret");

        // Or set Office 365 server URL.
        // ewsClient.SetServerUrl("https://outlook.office365.com/EWS/Exchange.asmx");
        // ewsClient.SetCredentials(email, "secret");

        // Or use autodiscover (must be configured on the Exchange server, Office 365 server has autodiscover working).
        // ewsClient.Autodiscover(email);
        // ewsClient.RequireHttps = true;
        // ewsClient.SetCredentials(email, "secret");

        // Send a mail message with attachment to myself.
        MailBeeMailMessage msg = new MailBeeMailMessage();
        msg.Subject = "Test from EWS";
        msg.BodyPlainText = "Test at " + DateTime.Now.ToString();
        msg.BodyHtmlText = "<html>Test at " + DateTime.Now.ToString() + "</html>";
        msg.Attachments.Add(@"C:\Temp\file.doc"); // Adjust this path to make it denote an existing file.
        msg.To.AddFromString("User <user@contoso.com>");
        msg.From.AsString = "User <user@contoso.com>";
        msg.SetUniqueMessageID(null);
        ewsClient.SendMessageAndSaveCopy(msg, null); // Also save copy to Sent Items.
        // ewsClient.SendMessage(msg); // Or just send.

        ewsClient.CalculateFolderSizeOnDownload = true;
        List<EwsFolder> folders = ewsClient.DownloadFolders(null, false, true);
        foreach (EwsFolder folder in folders)
        {
            Console.WriteLine(string.Format("Folder: '{0}', total msgs: {1}, unread: {2}, size in bytes: {3}",
                folder.ShortName, folder.TotalCount, folder.UnreadCount, folder.Size));
            Console.WriteLine(folder.FullName);
        }

        // Get Sent Items folder from its well-known ID.
        EwsFolder sentFolder = ewsClient.DownloadFolderById(WellKnownFolderName.SentItems);
        Console.WriteLine(string.Format("You have {0} sent messages(s)", sentFolder.TotalCount));
        EwsItemList sentItems = ewsClient.DownloadItems(sentFolder.Id, null, false, EwsItemParts.GenericItem);
        EwsItem lastSentItem = sentItems.FindLast(i => i.Subject == "Test from EWS");
        if (lastSentItem != null)
        {
            // Demonstrate deleting messages. It's safe to delete this message because it's a test message we just sent.
            ewsClient.DeleteItem(lastSentItem.Id);
            Console.WriteLine("Deleted saved copy of a message we sent above");
        }
        else
        {
            Console.WriteLine("For some reason, there was no saved copy of a message we sent above");
        }

        // Will demonstrate various methods of getting EWS folder ID which then can then be used with many methods and properties.
        FolderId foldId = null;

        // Method 1: Get FolderId from folder name.
        foldId = ewsClient.FindFolderIdByFullName("Inbox");

        // Method 2: Remember the fact we already have folder list downloaded, grab FolderId from there.
        // Note: this method is currently not working due to a bug in EWS Managed API.
        EwsFolder inbox = folders.Find(fold => (fold.Id.FolderName.HasValue && fold.Id.FolderName.Value == WellKnownFolderName.Inbox));
        if (inbox == null)
        {
            // You'll most probably end up here.
            Console.WriteLine("Well-known folders only supported in Exchange 2013 and higher");
            // You'll also need:
            // ewsClient.InitEwsClient(ExchangeVersion.Exchange2013_SP1, TimeZoneInfo.Utc);
            // ewsClient.EnableCompatibilityMode = false;
            // Update Microsoft.Exchange.WebServices.dll (current version v2.2 crashes when Well-known folder status if retrieved).

            // For the time being, fallback to searching by name.
            inbox = folders.Find(fold => (fold.FullName.ToUpper() == "INBOX"));
        }
        if (inbox == null)
        {
            Console.WriteLine("Couldn't find Inbox");
            return;
        }
        else
        {
            foldId = inbox.Id;
        }

        // Method 3: Or simply get it via WellKnownFolderName directly. Easiest method.
        foldId = WellKnownFolderName.Inbox;

        Console.WriteLine("Download unread messages, body/headers");

        // Default view means "return all items in the natural order".
        ItemView unreadView = null;

        // Or, modify the default view so that only 10 newest items are returned, newer first.
        int pageSize = 10;
        int page = 0;

        // We'll display items in pages.
        unreadView = new ItemView(pageSize, 0);
        unreadView.OrderBy.Add(EmailMessageSchema.DateTimeReceived, SortDirection.Descending);
        EwsItemList unreadItems = null;

        // Here we not using DownloadItems which accepts startIndex and count as we don't know in advance how many items we have.
        // Instead, we're relying on MoreAvailable property from EWS to determine if there are more items left.
        Console.WriteLine("Press Esc to skip downloading the next page of messages (if any).");
        Console.WriteLine();
        while (true)
        {
            unreadItems = ewsClient.DownloadItems(foldId, unreadView, false, EwsItemParts.GenericItem | EwsItemParts.MailMessageBody | EwsItemParts.MailMessageRecipients);
            if (unreadView != null)
            {
                Console.WriteLine(string.Format("Downloading up to {0} message(s) starting at offset {1} from total of {2}, {3} message(s) actually downloaded.",
                    pageSize, unreadView.Offset, unreadItems.TotalCount, unreadItems.Count));
            }
            foreach (EwsItem item in unreadItems)
            {
                Console.WriteLine(string.Format("UID: {0} Text: {1} HTML: {2}",
                    ShortenId(item.UniqueId), Flatten(Shorten(item.BodyPlainText, 40)), Flatten(Shorten(item.BodyHtmlText, 40))));
                Console.WriteLine();
            }
            Console.WriteLine();
            if (unreadItems.MoreAvailable)
            {
                if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)
                {
                    Console.WriteLine("Esc pressed, will skip downloading the remaining pages and proceed to other examples.");
                    break;
                }
                else
                {
                    Console.WriteLine("Will download the next page.");
                }
            }
            else
            {
                Console.WriteLine("The last page is done.");
                break;
            }
            unreadView.Offset = unreadItems.NextPageOffset;
        }

        Console.WriteLine();

        Console.WriteLine("Download unread messages, full messages with attachments");
        unreadItems = ewsClient.DownloadItems(unreadItems, EwsItemParts.MailMessageFull);
        for (int i = 0; i < unreadItems.Count; i++)
        {
            EwsItem item = unreadItems[i];
            Console.WriteLine(string.Format("ID {0} size: {1}, attachments count: {2}, attachments: {3}", Shorten(item.UniqueId, 10), item.Size,
                item.MailBeeMessage.Attachments.Count,
                string.Join(", ", item.MailBeeMessage.Attachments.Cast<MailBeeAttachment>().Select(a => Shorten(a.Filename, 20)))));

            // For last message, do additional processing.
            if (i == unreadItems.Count - 1)
            {
                if (item.MailBeeMessage.Attachments.Count > 0)
                {
                    // Save all attachments using MailBee.
                    item.MailBeeMessage.Attachments.SaveAll(@"C:\Temp", true);

                    // Save a particular attachment using MailBee.
                    item.MailBeeMessage.Attachments[0].SaveToFolder(@"C:\Temp", true);
                }

                if (item.NativeMessage.Attachments.Count > 0)
                {
                    // Demonstrate working with attachments directly via Managed EWS API.
                    Console.WriteLine("  Attachment ID to name:  " +
                        string.Join(", ", item.NativeMessage.Attachments.Select(a => ShortenId(a.Id) + ": " + Shorten(a.Name, 20))));
                    IEnumerable<FileAttachment> fileAttachs = item.NativeMessage.Attachments.OfType<FileAttachment>();
                    if (fileAttachs.Count() > 0)
                    {
                        Console.WriteLine("  File attachment IDs: " + string.Join(", ", fileAttachs.Select(fa => ShortenId(fa.Id))));
                        FileAttachment fileAttach = fileAttachs.First();
                        fileAttach.Load(Path.Combine(@"C:\Temp", fileAttach.Name)); // This will save attachment to disk.
                    }
                }

                // Add attachment to message and then delete it. This is a kind of action you can only do with EWS and not with POP3 or IMAP, for example
                // (you cannot alter existing messages in POP3/IMAP, only mark them with flags).
                Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count));
                FileAttachment newAttach = ewsClient.AddAttachmentToItem(item.Id, @"C:\Temp\test.txt", "filename.txt");
                item.NativeItem.Load();
                Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count));
                Console.WriteLine("Will delete attachment just added");
                int countAttachsDeleted = ewsClient.DeleteAttachment(item.Id, newAttach.Id, true, true);
                item.NativeItem.Load();
                Console.WriteLine(string.Format("Attachment ID: {0}, instances deleted: {1}", ShortenId(newAttach.Id), countAttachsDeleted));
                Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count));

                bool deleteOtherAttachs = false; // Set to true to enable deletion of other attachments. Do this only in test accounts, not in your normal account!
                if (deleteOtherAttachs)
                {
                    Console.WriteLine("Will delete the remaining attachments, if any");
                    ewsClient.DeleteAttachments(item.Id);
                    item.NativeItem.Load();
                    Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count));
                }
            }

        }
        Console.WriteLine();

        // Update message flags to mark last message in the folder as unread (just to make sure the search for unread messages below will find at least one message).
        if (inbox.TotalCount > 0)
        {
            EwsItem item = ewsClient.DownloadItem(foldId, 0, EwsItemParts.IdOnly);
            item.IsRead = true;
            ewsClient.UpdateItem(item);
        }

        // Clear keyboard buffer to avoid earlier Esc strokes alter the code flow below.
        while (Console.KeyAvailable)
        {
            Console.ReadKey();
        }

        Console.WriteLine("Search for unread messages via using SearchFilter");
        SearchFilter filt = null; // "No filter" means "Search all messages".
        filt = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); // Modify filter to allow only unread messages.
        unreadItems = ewsClient.Search(foldId, filt);
        string unreadUids = string.Join(", ", unreadItems.Select(it => ShortenId(it.UniqueId)));
        Console.WriteLine("Unread IDs (you can then pass them to DownloadItems): " + unreadUids);
        Console.WriteLine();

        // Simply display all messages in the folder with paging. We know in advance how many items to display so we don't need MoreAvailable and custom ItemView.
        Console.WriteLine("Display all messages in the folder in paged manner");
        Console.WriteLine("Press Esc to skip downloading the next page of messages (if any).");
        Console.WriteLine();
        EwsItemList items = null;
        while (page * pageSize < inbox.TotalCount)
        {
            // You can replace EwsItemParts.GenericItem with EwsItemParts.MailMessageFull to download full messages (with body/attachments) instead of basic info.
            // If you do this replacement, item.MailBeeMessage will no longer be null.
            items = ewsClient.DownloadItems(foldId, page * pageSize, pageSize, true, EwsItemParts.GenericItem);
            foreach (EwsItem item in items)
            {
                if (item.MailBeeMessage == null)
                {
                    Console.WriteLine(string.Format("To: '{0}', From: '{1}', Subject: '{2}', IsRead: {3}, Size: {4}",
                        Shorten(item.To, 20), Shorten(item.From, 20), Shorten(item.Subject, 20), item.IsRead, item.Size));
                }
                else
                {
                    Console.WriteLine(string.Format("To: '{0}', From: '{1}', Subject: '{2}', IsRead: {3}, Size: {4}, MailBeeMessage.Size: {5}",
                        Shorten(item.To, 20), Shorten(item.From, 20), Shorten(item.Subject, 20), item.IsRead, item.Size, item.MailBeeMessage.Size));
                }
            }
            page++;
            Console.WriteLine("------------");
            if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)
            {
                Console.WriteLine("Esc pressed, will skip downloading the remaining pages and proceed to other examples.");
                break;
            }
        }

        // Demonstrate working with deeply nested folders. EWS Managed API itself can only work with one level, MailBee adds this functionality on top of EWS.
        if (!ewsClient.FolderExists("Inbox/2nd level/3rd level"))
        {
            // Create a deeply nested folder.
            ewsClient.CreateFolder("Inbox/2nd level/3rd level", null);
            Console.WriteLine("Created folder \"Inbox/2nd level/3rd level\"");
        }
    }
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.IO
Imports MailBee.EwsMail
Imports Microsoft.Exchange.WebServices.Data

' We need this because MailMessage type exists in both MailBee and Managed EWS.
Imports MailBeeMailMessage = MailBee.Mime.MailMessage
Imports MailBeeAttachment = MailBee.Mime.Attachment

Class Program
    ' We use this for displaying all strings but IDs.
    Private Shared Function Shorten(text As String, maxLen As Integer) As String
        If text Is Nothing OrElse text.Length <= maxLen Then
            Return text
        Else
            Return text.Substring(0, maxLen - 2) & ".."
        End If
    End Function

    ' Because IDs usually have diff. endings but the same beginning, we'd better leave ending part.
    Private Shared Function ShortenId(text As String) As String
        Dim maxLen As Integer = 10
        If text Is Nothing OrElse text.Length <= maxLen Then
            Return text
        Else
            Return ".." & text.Substring((text.Length - maxLen) + 2)
        End If
    End Function

    ' Remove CRLFs from strings to make console outputs easier to read.
    Private Shared Function Flatten(text As String) As String
        If text Is Nothing Then
            Return Nothing
        Else
            Return text.Replace(vbCrLf, " ").Replace(vbLf, " ")
        End If
    End Function

    Shared Sub Main(args As String())
        ' If license key is not set in app.config or Registry, set it here.
        MailBee.Global.LicenseKey = "MN1XX-XXXXXXXX-XXXX"

        ' Enable self-signed server certificates. Remove this line to connect only to well-established servers with valid certificates.
        Ews.EnableSslCertValidation = False
        Dim ewsClient As New Ews()

        ' Normally, use TimeZoneInfo.Local, or use TimeZoneInfo.Utc if getting "The specified time zone isn't valid" errors.
        ewsClient.InitEwsClient(ExchangeVersion.Exchange2010_SP1, TimeZoneInfo.Utc)
        ' ewsClient.InitEwsClient(ExchangeVersion.Exchange2013_SP1, TimeZoneInfo.Utc); ' If your Exchange server is newer or Office 365.

        ' Log file can be used for debugging. You can also enable .NET Sockets own log by adding System.Net trace listener in app.config file (.NET Framework only).
        ewsClient.Log.Enabled = True
        ewsClient.Log.Filename = "C:\Temp\log.txt"
        ewsClient.Log.Clear()

        ' Disabled Gzip results in more traffic (that's bad) but makes debugging easier ("network.log" file will contain human-readable data).
        ewsClient.Service.AcceptGzipEncoding = False

        Dim email As String = "user@contoso.com" ' On-premise Exchange account
        ' Dim email As String = "user@company.onmicrosoft.com" ' Microsoft account

        ' Set on-premise Exchange server URL.
        ewsClient.SetServerUrl("http://domain/EWS/Exchange.asmx")
        ewsClient.SetCredentials(email, "secret")

        ' Or set Office 365 server URL.
        ' ewsClient.SetServerUrl("https://outlook.office365.com/EWS/Exchange.asmx")
        ' ewsClient.SetCredentials(email, "secret")

        ' Or use autodiscover (must be configured on the Exchange server, Office 365 server has autodiscover working).
        ' ewsClient.Autodiscover(email)
        ' ewsClient.RequireHttps = True
        ' ewsClient.SetCredentials(email, "secret")

        ' Send a mail message with attachment to myself.
        Dim msg As New MailBeeMailMessage()
        msg.Subject = "Test from EWS"
        msg.BodyPlainText = "Test at " & DateTime.Now.ToString()
        msg.BodyHtmlText = "<html>Test at " & DateTime.Now.ToString() & "</html>"
        msg.Attachments.Add("C:\Temp\file.doc") ' Adjust this path to make it denote an existing file.
        msg.To.AddFromString("User <user@contoso.com>")
        msg.From.AsString = "User <user@contoso.com>"
        msg.SetUniqueMessageID(Nothing)
        ewsClient.SendMessageAndSaveCopy(msg, Nothing) ' Also save copy to Sent Items.
        ' ewsClient.SendMessage(msg) ' Or just send.

        ewsClient.CalculateFolderSizeOnDownload = True
        Dim folders As List(Of EwsFolder) = ewsClient.DownloadFolders(Nothing, False, True)
        For Each folder As EwsFolder In folders
            Console.WriteLine(String.Format("Folder: '{0}', total msgs: {1}, unread: {2}, size in bytes: {3}",
                folder.ShortName, folder.TotalCount, folder.UnreadCount, folder.Size))
            Console.WriteLine(folder.FullName)
        Next

        ' Get Sent Items folder from its well-known ID.
        Dim sentFolder As EwsFolder = ewsClient.DownloadFolderById(WellKnownFolderName.SentItems)
        Console.WriteLine(String.Format("You have {0} sent messages(s)", sentFolder.TotalCount))
        Dim sentItems As EwsItemList = ewsClient.DownloadItems(sentFolder.Id, Nothing, False, EwsItemParts.GenericItem)
        Dim lastSentItem As EwsItem = sentItems.FindLast(Function(i) i.Subject = "Test from EWS")
        If lastSentItem IsNot Nothing Then
            ' Demonstrate deleting messages. It's safe to delete this message because it's a test message we just sent.
            ewsClient.DeleteItem(lastSentItem.Id)
            Console.WriteLine("Deleted saved copy of a message we sent above")
        Else
            Console.WriteLine("For some reason, there was no saved copy of a message we sent above")
        End If

        ' Will demonstrate various methods of getting EWS folder ID which then can then be used with many methods and properties.
        Dim foldId As FolderId = Nothing

        ' Method 1: Get FolderId from folder name.
        foldId = ewsClient.FindFolderIdByFullName("Inbox")

        ' Method 2: Remember the fact we already have folder list downloaded, grab FolderId from there.
        ' Note: this method is currently not working due to a bug in EWS Managed API.
        Dim inbox As EwsFolder = folders.Find(Function(fold) (fold.Id.FolderName.HasValue AndAlso fold.Id.FolderName.Value = WellKnownFolderName.Inbox))
        If inbox Is Nothing Then
            ' You'll most probably end up here.
            Console.WriteLine("Well-known folders only supported in Exchange 2013 and higher")
            ' You'll also need:
            ' ewsClient.InitEwsClient(ExchangeVersion.Exchange2013_SP1, TimeZoneInfo.Utc)
            ' ewsClient.EnableCompatibilityMode = False
            ' Update Microsoft.Exchange.WebServices.dll (current version v2.2 crashes when Well-known folder status if retrieved).

            ' For the time being, fallback to searching by name.
            inbox = folders.Find(Function(fold) (fold.FullName.ToUpper() = "INBOX"))
        End If
        If inbox Is Nothing Then
            Console.WriteLine("Couldn't find Inbox")
            Return
        Else
            foldId = inbox.Id
        End If

        ' Method 3: Or simply get it via WellKnownFolderName directly. Easiest method.
        foldId = WellKnownFolderName.Inbox

        Console.WriteLine("Download unread messages, body/headers")

        ' Default view means "return all items in the natural order".
        Dim unreadView As ItemView = Nothing

        ' Or, modify the default view so that only 10 newest items are returned, newer first.
        Dim pageSize As Integer = 10
        Dim page As Integer = 0

        ' We'll display items in pages.
        unreadView = New ItemView(pageSize, 0)
        unreadView.OrderBy.Add(EmailMessageSchema.DateTimeReceived, SortDirection.Descending)
        Dim unreadItems As EwsItemList = Nothing

        ' Here we not using DownloadItems which accepts startIndex and count as we don't know in advance how many items we have.
        ' Instead, we're relying on MoreAvailable property from EWS to determine if there are more items left.
        Console.WriteLine("Press Esc to skip downloading the next page of messages (if any).")
        Console.WriteLine()
        While True
            unreadItems = ewsClient.DownloadItems(foldId, unreadView, False, EwsItemParts.GenericItem Or EwsItemParts.MailMessageBody Or EwsItemParts.MailMessageRecipients)
            If unreadView IsNot Nothing Then
                Console.WriteLine(String.Format("Downloading up to {0} message(s) starting at offset {1} from total of {2}, {3} message(s) actually downloaded.",
                    pageSize, unreadView.Offset, unreadItems.TotalCount, unreadItems.Count))
            End If
            For Each item As EwsItem In unreadItems
                Console.WriteLine(String.Format("UID: {0} Text: {1} HTML: {2}",
                    ShortenId(item.UniqueId), Flatten(Shorten(item.BodyPlainText, 40)), Flatten(Shorten(item.BodyHtmlText, 40))))
                Console.WriteLine()
            Next
            Console.WriteLine()
            If unreadItems.MoreAvailable Then
                If Console.KeyAvailable AndAlso Console.ReadKey().Key = ConsoleKey.Escape Then
                    Console.WriteLine("Esc pressed, will skip downloading the remaining pages and proceed to other examples.")
                    Exit While
                Else
                    Console.WriteLine("Will download the next page.")
                End If
            Else
                Console.WriteLine("The last page is done.")
                Exit While
            End If
            unreadView.Offset = unreadItems.NextPageOffset
        End While

        Console.WriteLine()

        Console.WriteLine("Download unread messages, full messages with attachments")
        unreadItems = ewsClient.DownloadItems(unreadItems, EwsItemParts.MailMessageFull)
        For i As Integer = 0 To unreadItems.Count - 1
            Dim item As EwsItem = unreadItems(i)
            Console.WriteLine(String.Format("ID {0} size: {1}, attachments count: {2}, attachments: {3}",
                Shorten(item.UniqueId, 10), item.Size, item.MailBeeMessage.Attachments.Count,
                String.Join(", ", item.MailBeeMessage.Attachments.Cast(Of MailBeeAttachment)().Select(Function(a) Shorten(a.Filename, 20)))))

            ' For last message, do additional processing.
            If i = unreadItems.Count - 1 Then
                If item.MailBeeMessage.Attachments.Count > 0 Then
                    ' Save all attachments using MailBee.
                    item.MailBeeMessage.Attachments.SaveAll("C:\Temp", True)

                    ' Save a particular attachment using MailBee.
                    item.MailBeeMessage.Attachments(0).SaveToFolder("C:\Temp", True)
                End If

                If item.NativeMessage.Attachments.Count > 0 Then
                    ' Demonstrate working with attachments directly via Managed EWS API.
                    Console.WriteLine("  Attachment ID to name:  " &
                        String.Join(", ", item.NativeMessage.Attachments.Select(Function(a) ShortenId(a.Id) & ": " & Shorten(a.Name, 20))))
                    Dim fileAttachs As IEnumerable(Of FileAttachment) = item.NativeMessage.Attachments.OfType(Of FileAttachment)()
                    If fileAttachs.Count() > 0 Then
                        Console.WriteLine("  File attachment IDs: " & String.Join(", ", fileAttachs.Select(Function(fa) ShortenId(fa.Id))))
                        Dim fileAttach As FileAttachment = fileAttachs.First()
                        ' This will save attachment to disk.
                        fileAttach.Load(Path.Combine("C:\Temp", fileAttach.Name))
                    End If
                End If

                ' Add attachment to message and then delete it. This is a kind of action you can only do with EWS and not with POP3 or IMAP, for example
                ' (you cannot alter existing messages in POP3/IMAP, only mark them with flags).
                Console.WriteLine(String.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count))
                Dim newAttach As FileAttachment = ewsClient.AddAttachmentToItem(item.Id, "C:\Temp\test.txt", "filename.txt")
                item.NativeItem.Load()
                Console.WriteLine(String.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count))
                Console.WriteLine("Will delete attachment just added")
                Dim countAttachsDeleted As Integer = ewsClient.DeleteAttachment(item.Id, newAttach.Id, True, True)
                item.NativeItem.Load()
                Console.WriteLine(String.Format("Attachment ID: {0}, instances deleted: {1}", ShortenId(newAttach.Id), countAttachsDeleted))
                Console.WriteLine(String.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count))

                Dim deleteOtherAttachs As Boolean = False
                ' Set to true to enable deletion of other attachments. Do this only in test accounts, not in your normal account!
                If deleteOtherAttachs Then
                    Console.WriteLine("Will delete the remaining attachments, if any")
                    ewsClient.DeleteAttachments(item.Id)
                    item.NativeItem.Load()
                    Console.WriteLine(String.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count))
                End If

            End If
        Next
        Console.WriteLine()

        ' Update message flags to mark last message in the folder as unread (just to make sure the search for unread messages below will find at least one message).
        If inbox.TotalCount > 0 Then
            Dim item As EwsItem = ewsClient.DownloadItem(foldId, 0, EwsItemParts.IdOnly)
            item.IsRead = True
            ewsClient.UpdateItem(item)
        End If

        ' Clear keyboard buffer to avoid earlier Esc strokes alter the code flow below.
        While Console.KeyAvailable
            Console.ReadKey()
        End While

        Console.WriteLine("Search for unread messages via using SearchFilter")
        Dim filt As SearchFilter = Nothing ' "No filter" means "Search all messages".
        filt = New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False) ' Modify filter to allow only unread messages.
        unreadItems = ewsClient.Search(foldId, filt)
        Dim unreadUids As String = String.Join(", ", unreadItems.Select(Function(it) ShortenId(it.UniqueId)))
        Console.WriteLine(Convert.ToString("Unread IDs (you can then pass them to DownloadItems): ") & unreadUids)
        Console.WriteLine()

        ' Simply display all messages in the folder with paging. We know in advance how many items to display so we don't need MoreAvailable and custom ItemView.
        Console.WriteLine("Display all messages in the folder in paged manner")
        Console.WriteLine("Press Esc to skip downloading the next page of messages (if any).")
        Console.WriteLine()
        Dim items As EwsItemList = Nothing
        While page * pageSize < inbox.TotalCount
            ' You can replace EwsItemParts.GenericItem with EwsItemParts.MailMessageFull to download full messages (with body/attachments) instead of basic info.
            ' If you do this replacement, item.MailBeeMessage will no longer be null.
            items = ewsClient.DownloadItems(foldId, page * pageSize, pageSize, True, EwsItemParts.GenericItem)
            For Each item As EwsItem In items
                If item.MailBeeMessage Is Nothing Then
                    Console.WriteLine(String.Format("To: '{0}', From: '{1}', Subject: '{2}', IsRead: {3}, Size: {4}",
                        Shorten(item.To, 20), Shorten(item.From, 20), Shorten(item.Subject, 20), item.IsRead, item.Size))
                Else
                    Console.WriteLine(String.Format("To: '{0}', From: '{1}', Subject: '{2}', IsRead: {3}, Size: {4}, MailBeeMessage.Size: {5}",
                        Shorten(item.To, 20), Shorten(item.From, 20), Shorten(item.Subject, 20), item.IsRead, item.Size, item.MailBeeMessage.Size))
                End If
            Next
            page += 1
            Console.WriteLine("------------")
            If Console.KeyAvailable AndAlso Console.ReadKey().Key = ConsoleKey.Escape Then
                Console.WriteLine("Esc pressed, will skip downloading the remaining pages and proceed to other examples.")
                Exit While
            End If
        End While

        ' Demonstrate working with deeply nested folders. EWS Managed API itself can only work with one level, MailBee adds this functionality on top of EWS.
        If Not ewsClient.FolderExists("Inbox/2nd level/3rd level") Then
            ' Create a deeply nested folder.
            ewsClient.CreateFolder("Inbox/2nd level/3rd level", Nothing)
            Console.WriteLine("Created folder ""Inbox/2nd level/3rd level""")
        End If
    End Sub
End Class
See Also

Reference

MailBee.EwsMail Namespace


Ews Constructor

Ews Constructor
Creates an instance of Ews class.
Overload List
 | Name | Description
Public method | Ews | Creates an instance of Ews class.
Public method | Ews(String) | Creates and unlocks an instance of Ews class.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews Constructor

Ews Constructor
Creates an instance of Ews class.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Ews()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET EWS not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

Ews Class
Ews Overload
MailBee.EwsMail Namespace


Ews Constructor (String)

Ews Constructor (String)
Creates and unlocks an instance of Ews class.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Ews(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET EWS not licensed and the supplied license key is invalid.
See Also

Reference

Ews Class
Ews Overload
MailBee.EwsMail Namespace


Ews Methods

Ews Methods

The Ews type exposes the following members.

Methods
 | Name | Description
Public method | AddAttachmentToItem | Adds an attachment to an existing item.
Public method | AddAttachmentToItemAsync | Async/await version of AddAttachmentToItem(ItemId, String, String).
Public method | Autodiscover | Automatically determines the URL of the EWS server.
Public method | CopyItem | Copies the specified item (e.g. mail message) into the specified folder.
Public method | CopyItemAsync | Async/await version of CopyItem(ItemId, FolderId).
Public method | CreateFolder | Creates a folder in the MS Exchange account.
Public method | CreateFolderAsync | Async/await version of CreateFolder(String, FolderId).
Public method | CreatePropSet | Creates EWS Managed API PropertySet object.
Public method | DeleteAttachment | Deletes the attachment with the specified filename from the specified item.
Public method | DeleteAttachmentAsync | Async/await version of DeleteAttachment(ItemId, String, Boolean, Boolean).
Public method | DeleteAttachments | Deletes all attachments in the specified item.
Public method | DeleteAttachmentsAsync | Async/await version of DeleteAttachments(ItemId).
Public method | DeleteFolder | Deletes a folder with the specified ID.
Public method | DeleteFolderAsync | Async/await version of DeleteFolder(FolderId).
Public method | DeleteItem | Deletes the specified item (e.g. mail message).
Public method | DeleteItemAsync | Async/await version of DeleteItem(ItemId).
Public method | DeleteItems | Deletes the specified item (e.g. mail message).
Public method | DeleteItemsAsync | Async/await version of DeleteItems(IEnumerableItemId).
Public method | Dispose | Closes all opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.
Public method | DownloadEntireMessage | Downloads the specified item by its ID and returns it as MailMessage object.
Public method | DownloadEntireMessageAsync | Async/await version of DownloadEntireMessage(ItemId).
Public method | DownloadFolderByFullName(String) | Gets the reference to the folder denoted by its full name in the MS Exchange account.
Public method | DownloadFolderByFullName(FolderId, String) | Gets the reference to the given folder in the specified containing folder in the MS Exchange account.
Public method | DownloadFolderByFullName(String, Int32) | Gets the reference to the folder denoted by its full name in the MS Exchange account.
Public method | DownloadFolderByFullNameAsync(String) | Async/await version of DownloadFolderByFullName(String).
Public method | DownloadFolderByFullNameAsync(FolderId, String) | Async/await version of DownloadFolderByFullName(FolderId, String).
Public method | DownloadFolderByFullNameAsync(String, Int32) | Async/await version of DownloadFolderByFullName(String, Int32).
Public method | DownloadFolderById(FolderId) | Gets the reference to the folder with given ID in the MS Exchange account.
Public method | DownloadFolderById(FolderId, PropertySet) | Gets the reference to the folder with given ID in the MS Exchange account, also requesting the specified properties.
Public method | DownloadFolderByIdAsync(FolderId) | Async/await version of DownloadFolderById(FolderId).
Public method | DownloadFolderByIdAsync(FolderId, PropertySet) | Async/await version of DownloadFolderById(FolderId, PropertySet).
Public method | DownloadFolderByShortName | Gets the reference to the given folder in the MS Exchange account.
Public method | DownloadFolderByShortNameAsync | Async/await version of DownloadFolderByShortName(FolderId, String).
Public method | DownloadFolders(Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFolders(FolderId, Boolean, Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFolders(FolderId, FolderView, SearchFilter, Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFoldersAsync(Boolean) | Async/await version of DownloadFolders(Boolean).
Public method | DownloadFoldersAsync(FolderId, Boolean, Boolean) | Async/await version of DownloadFolders(FolderId, Boolean, Boolean).
Public method | DownloadFoldersAsync(FolderId, FolderView, SearchFilter, Boolean) | Async/await version of DownloadFolders(FolderId, FolderView, SearchFilter, Boolean).
Public method | DownloadItem(FolderId, Int32) | Downloads an item in the specified folder at the specified index.
Public method | DownloadItem(ItemId, EwsItemParts) | Downloads the specified portions of the specified item by its ID.
Public method | DownloadItem(ItemId, PropertySet) | Downloads the specified item by its ID using PropertySet settings.
Public method | DownloadItem(FolderId, Int32, EwsItemParts) | Downloads the specified portions of an Exchange item in the specified folder at the specified index.
Public method | DownloadItem(FolderId, Int32, PropertySet) | Downloads an item in the specified folder at the specified index using PropertySet settings.
Public method | DownloadItemAsync(FolderId, Int32) | Async/await version of DownloadItem(FolderId, Int32).
Public method | DownloadItemAsync(ItemId, EwsItemParts) | Async/await version of DownloadItem(ItemId, EwsItemParts).
Public method | DownloadItemAsync(ItemId, PropertySet) | Async/await version of DownloadItem(ItemId, PropertySet).
Public method | DownloadItemAsync(FolderId, Int32, EwsItemParts) | Async/await version of DownloadItem(FolderId, Int32, EwsItemParts).
Public method | DownloadItemAsync(FolderId, Int32, PropertySet) | Async/await version of DownloadItem(FolderId, Int32, PropertySet).
Public method | DownloadItemIds(FolderId, Boolean) | Downloads IDs of all or unread items in the specified folder.
Public method | DownloadItemIds(FolderId, ItemView, Boolean) | Downloads IDs of items in the specified folder in the specified ItemView range.
Public method | DownloadItemIdsAsync(FolderId, Boolean) | Async/await version of DownloadItemIds(FolderId, Boolean).
Public method | DownloadItemIdsAsync(FolderId, ItemView, Boolean) | Async/await version of DownloadItemIds(FolderId, ItemView, Boolean).
Public method | DownloadItems(FolderId, Boolean) | Downloads all or unread items in the specified folder.
Public method | DownloadItems(IEnumerableEwsItem, EwsItemParts) | Downloads the specified portions of the specified items.
Public method | DownloadItems(IEnumerableEwsItem, PropertySet) | Downloads the specified items using PropertySet settings.
Public method | DownloadItems(FolderId, ItemView, Boolean) | Downloads items in the specified folder in the specified ItemView range.
Public method | DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) | Downloads the specified portions of the items in the specified ItemView range in the specified folder.
Public method | DownloadItems(FolderId, ItemView, Boolean, PropertySet) | Downloads items in the specified folder in the specified ItemView range using PropertySet settings.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean) | Downloads items in the specified folder in the specified range.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) | Downloads the specified portions of Exchange items in the specified folder in the specified range.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet) | Downloads items in the specified folder in the specified range using PropertySet settings.
Public method | DownloadItemsAsync(FolderId, Boolean) | Async/await version of DownloadItems(FolderId, Boolean).
Public method | DownloadItemsAsync(IEnumerableEwsItem, EwsItemParts) | Async/await version of DownloadItems(IEnumerableEwsItem, EwsItemParts).
Public method | DownloadItemsAsync(IEnumerableEwsItem, PropertySet) | Async/await version of DownloadItems(IEnumerableEwsItem, PropertySet).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean) | Async/await version of DownloadItems(FolderId, ItemView, Boolean).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean, EwsItemParts) | Async/await version of DownloadItems(FolderId, ItemView, Boolean, EwsItemParts).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean, PropertySet) | Async/await version of DownloadItems(FolderId, ItemView, Boolean, PropertySet).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean, EwsItemParts) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean, PropertySet) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet).
Public method | DownloadNativeAttachments | Downloads attachments with the specified string IDs.
Public method | DownloadNativeAttachmentsAsync | Async/await version of DownloadNativeAttachments(String, Boolean).
Public method | EmptyFolder | Empties a folder with the specified ID.
Public method | EmptyFolderAsync | Async/await version of EmptyFolder(FolderId, Boolean).
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | EwsItemsToItemIds | Creates the list of ItemId objects from the collection of EwsItem objects.
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | FindFolderIdByFullName(String) | Gets the ID of the folder denoted by its full name in the MS Exchange account.
Public method | FindFolderIdByFullName(FolderId, String) | Gets the ID of the given folder in the specified containing folder in the MS Exchange account.
Public method | FindFolderIdByFullName(String, Int32) | Gets the ID of the given folder in the MS Exchange account.
Public method | FindFolderIdByFullNameAsync(String) | Async/await version of FindFolderIdByFullName(String).
Public method | FindFolderIdByFullNameAsync(FolderId, String) | Async/await version of FindFolderIdByFullName(FolderId, String).
Public method | FindFolderIdByFullNameAsync(String, Int32) | Async/await version of FindFolderIdByFullName(String, Int32).
Public method | FindFolderIdByShortName | Gets the ID of the given folder in the MS Exchange account.
Public method | FindFolderIdByShortNameAsync | Async/await version of FindFolderIdByShortName(FolderId, String).
Public method | FolderExists(String) | Checks if the folder with the specified full name exists in the MS Exchange account.
Public method | FolderExists(FolderId, String) | Checks if the given folder in the specified containing folder exists in the MS Exchange account.
Public method | FolderExistsAsync(String) | Async/await version of [!:FolderExists(FolderId)].
Public method | FolderExistsAsync(FolderId, String) | Async/await version of FolderExists(FolderId, String).
Public method | GetErrorDescription | Returns a textual description of the last occurred error.
Public method | GetExchangeVersionString | Gets the MS Exchange version as a string.
Public method | GetFolderByName | Finds the EwsFolder in the given list by the folder's full name.
Public method | GetFolderView | Gets FolderView instance tuned for listing all the folders in the account.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | InitEwsClient | Sets the default MS Exchange version.
Public method | InitEwsClient(ExchangeVersion) | Sets the specific MS Exchange version.
Public method | InitEwsClient(ExchangeVersion, TimeZoneInfo) | Sets the specific MS Exchange version.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | MoveFolder | Moves a folder into another folder.
Public method | MoveFolderAsync | Async/await version of MoveFolder(FolderId, FolderId).
Public method | MoveItem | Moves the specified item (e.g. mail message) into the specified folder.
Public method | MoveItemAsync | Async/await version of MoveItem(ItemId, FolderId).
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Public method | RenameFolder | Renames a folder in the MS Exchange account.
Public method | RenameFolderAsync | Async/await version of RenameFolder(String, FolderId).
Public method | RenameOrMoveFolder | Renames or moves a folder denoted by its full name rather than by ID.
Public method | RenameOrMoveFolderAsync | Async/await version of RenameOrMoveFolder(String, String, ListEwsFolder).
Public method | ResolveName | Resolves the specified name into e-mail addresses which exist on the given MS Exchange server.
Public method | ResolveNameAsync | Async/await version of ResolveName(String).
Public method | Search(FolderId, SearchFilter) | Searches the specified folder for items matching the given criteria.
Public method | Search(FolderId, SearchFilter, ItemView) | Searches the specified folder for items matching the given criteria and delivers the results accordingly the specified ItemView.
Public method | SearchAsync(FolderId, SearchFilter) | Async/await version of Search(FolderId, SearchFilter).
Public method | SearchAsync(FolderId, SearchFilter, ItemView) | Async/await version of Search(FolderId, SearchFilter, ItemView).
Public method | SendMessage | Sends MailBee mail message.
Public method | SendMessageAndSaveCopy | Sends MailBee mail message and saves a copy in Sent Items or user-defined folder.
Public method | SendMessageAndSaveCopyAsync | Async/await version of SendMessageAndSaveCopy(MailMessage, FolderId).
Public method | SendMessageAsync | Async/await version of SendMessage(MailMessage).
Public method | SetCredentials(ExchangeCredentials) | Sets the credentials (e.g. OAuth2) of the MS Exchange account for subsequent operations.
Public method | SetCredentials(String, String) | Sets the login and password of the MS Exchange account for subsequent operations.
Public method | SetServerUrl | Gets or sets the URL of EWS service on MS Exchange server.
Public method | TestConnection | Makes a test connection to validate the current settings.
Public method | TestConnectionAsync | Async/await version of TestConnection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | UpdateItem | Writes the changes made to the item to the MS Exchange server.
Public method | UpdateItemAsync | Async/await version of UpdateItem(EwsItem).
Public method | UploadMessage(FolderId, MailMessage, Boolean) | Uploads MailBee's MailMessage into the specified folder on the MS Exchange server.
Public method | UploadMessage(FolderId, Byte, Boolean) | Uploads raw message data into the specified folder on the MS Exchange server.
Public method | UploadMessageAsync(FolderId, MailMessage, Boolean) | Async/await version of UploadMessage(FolderId, MailMessage, Boolean).
Public method | UploadMessageAsync(FolderId, Byte, Boolean) | Async/await version of UploadMessage(FolderId, Byte, Boolean).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.AddAttachmentToItem Method

EwsAddAttachmentToItem Method
Adds an attachment to an existing item.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FileAttachment AddAttachmentToItem(
    ItemId id,
    string filename,
    string targetFilename
)
Public Function AddAttachmentToItem (
    id As ItemId,
    filename As String,
    targetFilename As String
) As FileAttachment

Parameters

id
Type: ItemId
The ID of the item. Null reference (Nothing in Visual Basic) not allowed.
filename
Type: SystemString
The path to the local file whihc will then be uploaded to the server and attached to the item. Null reference (Nothing in Visual Basic) or empty string not allowed.
targetFilename
Type: SystemString
The attachment filename as it should appear in the message. If a null reference, Mailbee will take it from filename parameter.

Return Value

Type: FileAttachment
EWS Managed API FileAttachment object representing the attachment just added, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use AddAttachmentToItemAsync(ItemId, String, String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.AddAttachmentToItemAsync Method

EwsAddAttachmentToItemAsync Method
Async/await version of AddAttachmentToItem(ItemId, String, String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FileAttachment> AddAttachmentToItemAsync(
    ItemId id,
    string filename,
    string targetFilename
)
Public Function AddAttachmentToItemAsync (
    id As ItemId,
    filename As String,
    targetFilename As String
) As Task(Of FileAttachment)

Parameters

id
Type: ItemId
filename
Type: SystemString
targetFilename
Type: SystemString

Return Value

Type: Task FileAttachment
A task that represents the asynchronous operation. The value of TResult parameter points to the EWS Managed API FileAttachment object representing the attachment just added, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use AddAttachmentToItem(ItemId, String, String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Autodiscover Method

EwsAutodiscover Method
Automatically determines the URL of the EWS server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Autodiscover(
    string emailAddress
)
Public Function Autodiscover (
    emailAddress As String
) As Boolean

Parameters

emailAddress
Type: SystemString
The e-mail address to autodiscover the EWS server for.

Return Value

Type: Boolean
true if the autodiscover attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
For Autodiscover to work, it must be correctly configured on the given MS Exchange server (e.g. https://domain.com/autodiscover/autodiscover.xml must return the valid XML data). You also need to specify the credentials of a valid Exchange account (usually, the same account you're autodiscovering).
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.CopyItem Method

EwsCopyItem Method
Copies the specified item (e.g. mail message) into the specified folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ItemId CopyItem(
    ItemId copiedItemId,
    FolderId targetFolderId
)
Public Function CopyItem (
    copiedItemId As ItemId,
    targetFolderId As FolderId
) As ItemId

Parameters

copiedItemId
Type: ItemId
The ID of the item to copy. Null reference (Nothing in Visual Basic) not allowed.
targetFolderId
Type: FolderId
The ID of the folder where to copy the message. Null reference not allowed.

Return Value

Type: ItemId
ID of the new item if succeeded; otherwise, a null reference.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use CopyItemAsync(ItemId, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.CopyItemAsync Method

EwsCopyItemAsync Method
Async/await version of CopyItem(ItemId, FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<ItemId> CopyItemAsync(
    ItemId copiedItemId,
    FolderId targetFolderId
)
Public Function CopyItemAsync (
    copiedItemId As ItemId,
    targetFolderId As FolderId
) As Task(Of ItemId)

Parameters

copiedItemId
Type: ItemId
targetFolderId
Type: FolderId

Return Value

Type: Task ItemId
A task that represents the asynchronous operation. The value of TResult parameter points to the ID of the new item if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use CopyItem(ItemId, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.CreateFolder Method

EwsCreateFolder Method
Creates a folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool CreateFolder(
    string newFolderName,
    FolderId parentFolderId
)
Public Function CreateFolder (
    newFolderName As String,
    parentFolderId As FolderId
) As Boolean

Parameters

newFolderName
Type: SystemString
The folder name. Null reference (Nothing in Visual Basic) or empty string not allowed.
parentFolderId
Type: FolderId
The ID of the parent folder where to create the new folder. If a null reference (Nothing in Visual Basic), RootFolderType will be assumed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

newFolderName must be a short name (not a full name with nested folder names in it). To create a folder by its full name, you'll need to create all levels separately (if they do not already exist).

Note Note
This method is not implemented in .NET Core. Use CreateFolderAsync(String, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.CreateFolderAsync Method

EwsCreateFolderAsync Method
Async/await version of CreateFolder(String, FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> CreateFolderAsync(
    string newFolderName,
    FolderId parentFolderId
)
Public Function CreateFolderAsync (
    newFolderName As String,
    parentFolderId As FolderId
) As Task(Of Boolean)

Parameters

newFolderName
Type: SystemString
parentFolderId
Type: FolderId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use CreateFolder(String, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.CreatePropSet Method

EwsCreatePropSet Method
Creates EWS Managed API PropertySet object.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PropertySet CreatePropSet(
    EwsItemParts parts
)
Public Function CreatePropSet (
    parts As EwsItemParts
) As PropertySet

Parameters

parts
Type: MailBee.EwsMailEwsItemParts
A set of EWS item parts to be requested for 'download item' operations.

Return Value

Type: PropertySet
A PropertySet instance configured accordingly the specified parameters.
Remarks

This is a helper method for advanced purposes. You can use it with DownloadItems(FolderId, ItemView, bool, PropertySet) and DownloadItem(ItemId, PropertySet) methods when you need to work directly with EWS Managed API types.

Most applications will not use PropertySet objects directly as they can use DownloadItems(FolderId, ItemView, bool, EwsItemParts) and DownloadItem(ItemId, EwsItemParts) overloads which hide PropertySet complexity from the developer.

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteAttachment Method

EwsDeleteAttachment Method
Deletes the attachment with the specified filename from the specified item.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int DeleteAttachment(
    ItemId id,
    string filenameOrAttachId,
    bool isAttachId,
    bool deleteFirstOccurenceOnly
)
Public Function DeleteAttachment (
    id As ItemId,
    filenameOrAttachId As String,
    isAttachId As Boolean,
    deleteFirstOccurenceOnly As Boolean
) As Integer

Parameters

id
Type: ItemId
The ID of the item. Null reference (Nothing in Visual Basic) not allowed.
filenameOrAttachId
Type: SystemString
The filename or string ID of the attachment to delete. Null reference or empty string not allowed.
isAttachId
Type: SystemBoolean
If true, filenameOrAttachId is treated as ID; otherwise, filename.
deleteFirstOccurenceOnly
Type: SystemBoolean
if true, only the first occurrence of the attachment with the given filename will be removed; otherwise, all occurrences. Ignored if filenameOrAttachId is true (multiple attachments cannot have the same ID).

Return Value

Type: Int32
Number of attachments removed, or zero if no attachments with the given filename or ID found, or -1 on error (if ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

The attachment will be deleted permanently.

There can be multiple attachements with the same filename. With this method you can delete them all or only the first one.

Note Note
The method does not cause an exception in case if no attachment with the given filename or attachment ID is found (you'll simly get zero as the return value). Providing incorrect item ID, however, is considered error.

If you need more sophisticated processing of an item, you can use NativeItem property to access its members and then call UpdateItem(EwsItem) to save the changes to the MS Exchange server.

Note Note
This method is not implemented in .NET Core. Use DeleteAttachmentAsync(ItemId, String, Boolean, Boolean) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteAttachmentAsync Method

EwsDeleteAttachmentAsync Method
Async/await version of DeleteAttachment(ItemId, String, Boolean, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<int> DeleteAttachmentAsync(
    ItemId id,
    string filenameOrAttachId,
    bool isAttachId,
    bool deleteFirstOccurenceOnly
)
Public Function DeleteAttachmentAsync (
    id As ItemId,
    filenameOrAttachId As String,
    isAttachId As Boolean,
    deleteFirstOccurenceOnly As Boolean
) As Task(Of Integer)

Parameters

id
Type: ItemId
filenameOrAttachId
Type: SystemString
isAttachId
Type: SystemBoolean
deleteFirstOccurenceOnly
Type: SystemBoolean

Return Value

Type: Task Int32
A task that represents the asynchronous operation. The value of TResult parameter is Number of attachments removed, or zero if no attachments with the given filename or ID found, or -1 on error (if ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DeleteAttachment(ItemId, String, Boolean, Boolean) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteAttachments Method

EwsDeleteAttachments Method
Deletes all attachments in the specified item.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteAttachments(
    ItemId id
)
Public Function DeleteAttachments (
    id As ItemId
) As Boolean

Parameters

id
Type: ItemId
The ID of the item. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
The attachments will be deleted permanently.
Note Note
This method is not implemented in .NET Core. Use DeleteAttachmentsAsync(ItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteAttachmentsAsync Method

EwsDeleteAttachmentsAsync Method
Async/await version of DeleteAttachments(ItemId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteAttachmentsAsync(
    ItemId id
)
Public Function DeleteAttachmentsAsync (
    id As ItemId
) As Task(Of Boolean)

Parameters

id
Type: ItemId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DeleteAttachments(ItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteFolder Method

EwsDeleteFolder Method
Deletes a folder with the specified ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteFolder(
    FolderId id
)
Public Function DeleteFolder (
    id As FolderId
) As Boolean

Parameters

id
Type: FolderId
The ID of the folder to delete. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delete a folder by its name, first locate its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

To control how items are deleted (e.g. to Trash or permanently), use DeleteMethod property.

This method can delete non-empty folders.

Note Note
This method is not implemented in .NET Core. Use DeleteFolderAsync(FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteFolderAsync Method

EwsDeleteFolderAsync Method
Async/await version of DeleteFolder(FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteFolderAsync(
    FolderId id
)
Public Function DeleteFolderAsync (
    id As FolderId
) As Task(Of Boolean)

Parameters

id
Type: FolderId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter points is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DeleteFolder(FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteItem Method

EwsDeleteItem Method
Deletes the specified item (e.g. mail message).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteItem(
    ItemId id
)
Public Function DeleteItem (
    id As ItemId
) As Boolean

Parameters

id
Type: ItemId
The ID of the item to delete. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
The item is deleted using DeleteMethod mode.
Note Note
This method is not implemented in .NET Core. Use DeleteItemAsync(ItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteItemAsync Method

EwsDeleteItemAsync Method
Async/await version of DeleteItem(ItemId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteItemAsync(
    ItemId id
)
Public Function DeleteItemAsync (
    id As ItemId
) As Task(Of Boolean)

Parameters

id
Type: ItemId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DeleteItem(ItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteItems Method

EwsDeleteItems Method
Deletes the specified item (e.g. mail message).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public List<ItemId> DeleteItems(
    IEnumerable<ItemId> ids
)
Public Function DeleteItems (
    ids As IEnumerable(Of ItemId)
) As List(Of ItemId)

Parameters

ids
Type: System.Collections.GenericIEnumerable ItemId
The IDs of the items to delete. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: List ItemId
The list of IDs which have been deleted if succeeded; otherwise, a null reference.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

The item is deleted using DeleteMethod mode.

If you have a collection of EwsItem objects, you can convert it into the collection of ItemId elements using EwsItemsToItemIds(IEnumerableEwsItem) method which you can then pass to the current method.

Note Note
This method can still complete successfully if at least one item has been deleted. To make sure all the requested items have been deleted, check that the length of the resulting list is the same as the count of elements in the input. ItemId values of the items which could not be deleted will not be present in the resuling list.
Note Note
This method is not implemented in .NET Core. Use DeleteItemsAsync(IEnumerableItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteItemsAsync Method

EwsDeleteItemsAsync Method
Async/await version of DeleteItems(IEnumerableItemId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<List<ItemId>> DeleteItemsAsync(
    IEnumerable<ItemId> ids
)
Public Function DeleteItemsAsync (
    ids As IEnumerable(Of ItemId)
) As Task(Of List(Of ItemId))

Parameters

ids
Type: System.Collections.GenericIEnumerable ItemId

Return Value

Type: Task List ItemId
A task that represents the asynchronous operation. The value of TResult parameter points to the list of IDs which have been deleted if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DeleteItems(IEnumerableItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Dispose Method

EwsDispose Method
Overload List
 | Name | Description
Public method | Dispose | Closes all opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Dispose Method

EwsDispose Method
Closes all opened network connections (if any) and releases any used system resources.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
Actually, there is no need to call this method because this component always disposes resources automatically.
See Also

Reference

Ews Class
Dispose Overload
MailBee.EwsMail Namespace


Ews.Dispose Method (Boolean)

EwsDispose Method (Boolean)
When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Remarks
If the derived class does not use any additional resources, this method does not need to be overridden. If, however, it's overridden, the developer must also call Dispose method of the base class.
See Also

Reference

Ews Class
Dispose Overload
MailBee.EwsMail Namespace


Ews.DownloadEntireMessage Method

EwsDownloadEntireMessage Method
Downloads the specified item by its ID and returns it as MailMessage object.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DownloadEntireMessage(
    ItemId id
)
Public Function DownloadEntireMessage (
    id As ItemId
) As MailMessage

Parameters

id
Type: ItemId
The ID of the item. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: MailMessage
The downloaded e-mail, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To get item IDs, you can use DownloadItemIds(FolderId, Boolean) or Search(FolderId, SearchFilter) methods and then pass Id of items of the returned list to the current method. If you have a string ID (UniqueId), you can create ItemId using #ctor(String) constructor.

This method downloads the entire message with attachments as MailBee's MailMessage object. MS Exchange also lets you download attachments separately (if you know their string IDs) using EWS Managed API, see DownloadNativeAttachments(String, Boolean) method for details.

To download multiple entire messages or learn message flags like unread status, you can use a method like DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) passing MailMessageFull as parts parameter value. The mail messages can then be accessed with MailBeeMessage property for each EwsItem in the returned list.

Note Note
This method is not implemented in .NET Core. Use DownloadEntireMessageAsync(ItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadEntireMessageAsync Method

EwsDownloadEntireMessageAsync Method
Async/await version of DownloadEntireMessage(ItemId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessage> DownloadEntireMessageAsync(
    ItemId id
)
Public Function DownloadEntireMessageAsync (
    id As ItemId
) As Task(Of MailMessage)

Parameters

id
Type: ItemId

Return Value

Type: Task MailMessage
A task that represents the asynchronous operation. The value of TResult parameter points to MailMessage object which represents the downloaded e-mail, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadEntireMessage(ItemId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullName Method

EwsDownloadFolderByFullName Method
Overload List
 | Name | Description
Public method | DownloadFolderByFullName(String) | Gets the reference to the folder denoted by its full name in the MS Exchange account.
Public method | DownloadFolderByFullName(FolderId, String) | Gets the reference to the given folder in the specified containing folder in the MS Exchange account.
Public method | DownloadFolderByFullName(String, Int32) | Gets the reference to the folder denoted by its full name in the MS Exchange account.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullName Method (String)

EwsDownloadFolderByFullName Method (String)
Gets the reference to the folder denoted by its full name in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder DownloadFolderByFullName(
    string folderFullName
)
Public Function DownloadFolderByFullName (
    folderFullName As String
) As EwsFolder

Parameters

folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.

Return Value

Type: EwsFolder
The EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

Note Note
Scanning the entire folder tree is an expensive operation. If your Exchange account has thousands of folders, consider optimizations like those provided by DownloadFolderByFullName(FolderId, string) or DownloadFolderByFullName(string, int) overloads.
Note Note
This method is not implemented in .NET Core. Use DownloadFolderByFullNameAsync(String) instead.
See Also

Reference

Ews Class
DownloadFolderByFullName Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullName Method (FolderId, String)

EwsDownloadFolderByFullName Method (FolderId, String)
Gets the reference to the given folder in the specified containing folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder DownloadFolderByFullName(
    FolderId containingFolderId,
    string folderFullName
)
Public Function DownloadFolderByFullName (
    containingFolderId As FolderId,
    folderFullName As String
) As EwsFolder

Parameters

containingFolderId
Type: FolderId
The ID of the containing folder where to search for the given folder. If a null reference (Nothing in Visual Basic), RootFolderType will be assumed.
folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.

Return Value

Type: EwsFolder
The EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

containingFolderId is just for optimization so you can leave it a null reference. However, if you already know that the folder you're looking for is contained in some upper level folder, you can specify it there. This will optimize performance as only a subset of all folders in the account will be searched. If you don't know the containing folder, you can use another optimization provided by DownloadFolderByFullName(string, int) overload.

containingFolderId does not need to be the immediate parent of the folder you're looking for, it can be any level up (e.g. you can specify WellKnownFolderName.Inbox while searching for "Inbox/Nested folder/Deeply nested folder"). Still, more close containingFolderId's level is to folderFullName's level - faster the search will be.

Note Note
This method is not implemented in .NET Core. Use DownloadFolderByFullNameAsync(FolderId, String) instead.
See Also

Reference

Ews Class
DownloadFolderByFullName Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullName Method (String, Int32)

EwsDownloadFolderByFullName Method (String, Int32)
Gets the reference to the folder denoted by its full name in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder DownloadFolderByFullName(
    string folderFullName,
    int recursionLevel
)
Public Function DownloadFolderByFullName (
    folderFullName As String,
    recursionLevel As Integer
) As EwsFolder

Parameters

folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.
recursionLevel
Type: SystemInt32
Specifies how many levels of folder hierarchy to scan in shallow mode before switching to deep traversal mode. If 0, the entire account will be searched in a single operation (deep traversal). Higher values increase the number of search queries to the server but make each query more lightweight. Negative values not allowed.

Return Value

Type: EwsFolder
The EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

Note Note
This overload exists only for optimization purposes when dealing with very complex and deeply nested folder hierarchies in Exchange accounts.

Scanning the entire folder tree is an expensive operation. If your Exchange account has thousands of folders, this method can be used as an optimization. While DownloadFolderByFullName(string) overload internally downloads the entire folder tree in a single call (this can time out with complex hierachies), the current overload makes multiple queries, one per hierarchy level. Each query returns only the folder on the current level, not going deeply.

So, it will find "Inbox" in the message root, then will search "Inbox" folder for "Nested folder", and finally will search "Nested folder" for "Deeply nested folder". This approach is much eaiser for the server and produces less traffic. The drawback is that multiple requests to the server needed instead of a single one. If you have deeply nested folders, the number of queries can become very high.

At the same time, the value of reducing load on the server with making "flat" searches instead of "deep traversal" diminishes with every level of hierarchy. If you, let's say, have 15625 folders on 6th level of hierarchy (each folder contains 5 sub-folders, the formula is 5x5x5x5x5x5), you'll typically have 125 lowest-level subfolders in Level 3 folders. It would be a disaster to search through 15625 in a single query but 125 is another deal. Normally, we'd need 6 queries for each of 6 levels but we can make 3 flat queries to get on Level 3 and then one deep-traversal query over the remaining 125 folders down the road. 4 queries instead of 6.

recursionLevel provides tradeoff between request complexity and number of requests. If you set it to 3 (or any larger value), then in the current example we'll do 3 queries, like shown above. However, if you set it to, let's say, 2, it will do only two queries. The first will search message root for "Inbox" while the second query will load the entire sub-tree of "Inbox" folder. If your entire account has hundreds of folders but Inbox particularly has not so many sub-folders (although they can be nested quite deeply), you'll get signifacant performance benefit.

The most optimal value of recursionLevel depends on the folder structure of a particular account but the value of 3 can be a good starting point.

Another method of optimization is using DownloadFolderByFullName(FolderId, string) overload (it lets you specify the containing folder under which tree to perform deep search).

Note Note
This method is not implemented in .NET Core. Use DownloadFolderByFullNameAsync(String, Int32) instead.
See Also

Reference

Ews Class
DownloadFolderByFullName Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullNameAsync Method

EwsDownloadFolderByFullNameAsync Method
Overload List
 | Name | Description
Public method | DownloadFolderByFullNameAsync(String) | Async/await version of DownloadFolderByFullName(String).
Public method | DownloadFolderByFullNameAsync(FolderId, String) | Async/await version of DownloadFolderByFullName(FolderId, String).
Public method | DownloadFolderByFullNameAsync(String, Int32) | Async/await version of DownloadFolderByFullName(String, Int32).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullNameAsync Method (String)

EwsDownloadFolderByFullNameAsync Method (String)
Async/await version of DownloadFolderByFullName(String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsFolder> DownloadFolderByFullNameAsync(
    string folderFullName
)
Public Function DownloadFolderByFullNameAsync (
    folderFullName As String
) As Task(Of EwsFolder)

Parameters

folderFullName
Type: SystemString

Return Value

Type: Task EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolderByFullName(String) instead.
See Also

Reference

Ews Class
DownloadFolderByFullNameAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullNameAsync Method (FolderId, String)

EwsDownloadFolderByFullNameAsync Method (FolderId, String)
Async/await version of DownloadFolderByFullName(FolderId, String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsFolder> DownloadFolderByFullNameAsync(
    FolderId containingFolderId,
    string folderFullName
)
Public Function DownloadFolderByFullNameAsync (
    containingFolderId As FolderId,
    folderFullName As String
) As Task(Of EwsFolder)

Parameters

containingFolderId
Type: FolderId
folderFullName
Type: SystemString

Return Value

Type: Task EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolderByFullName(FolderId, String) instead.
See Also

Reference

Ews Class
DownloadFolderByFullNameAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByFullNameAsync Method (String, Int32)

EwsDownloadFolderByFullNameAsync Method (String, Int32)
Async/await version of DownloadFolderByFullName(String, Int32).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsFolder> DownloadFolderByFullNameAsync(
    string folderFullName,
    int recursionLevel
)
Public Function DownloadFolderByFullNameAsync (
    folderFullName As String,
    recursionLevel As Integer
) As Task(Of EwsFolder)

Parameters

folderFullName
Type: SystemString
recursionLevel
Type: SystemInt32

Return Value

Type: Task EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolderByFullName(String, Int32) instead.
See Also

Reference

Ews Class
DownloadFolderByFullNameAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderById Method

EwsDownloadFolderById Method
Gets the reference to the folder with given ID in the MS Exchange account.
Gets the reference to the folder with given ID in the MS Exchange account.
Overload List
 | Name | Description
Public method | DownloadFolderById(FolderId) | Gets the reference to the folder with given ID in the MS Exchange account.
Public method | DownloadFolderById(FolderId, PropertySet) | Gets the reference to the folder with given ID in the MS Exchange account, also requesting the specified properties.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolderById Method (FolderId)

EwsDownloadFolderById Method (FolderId)
Gets the reference to the folder with given ID in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder DownloadFolderById(
    FolderId id
)
Public Function DownloadFolderById (
    id As FolderId
) As EwsFolder

Parameters

id
Type: FolderId
The folder's EWS ID.

Return Value

Type: EwsFolder
The EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

This method is useful if you need to get info for special folders like Sent Items (such as via passing folder's WellKnownFolderName). See Ews topic for example.

This overload requests basic folder info (so-called First Class Properties) and also folder names (and also folder size if CalculateFolderSizeOnDownload is true).

Note Note
This method is not implemented in .NET Core. Use DownloadFolderByIdAsync(FolderId) instead.
See Also

Reference

Ews Class
DownloadFolderById Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderById Method (FolderId, PropertySet)

EwsDownloadFolderById Method (FolderId, PropertySet)
Gets the reference to the folder with given ID in the MS Exchange account, also requesting the specified properties.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder DownloadFolderById(
    FolderId id,
    PropertySet propSet
)
Public Function DownloadFolderById (
    id As FolderId,
    propSet As PropertySet
) As EwsFolder

Parameters

id
Type: FolderId
The folder's EWS ID.
propSet
Type: PropertySet
Extra properties of the folder to request from the Exchange server. If a null reference (Nothing in Visual Basic), basic properties are requested.

Return Value

Type: EwsFolder
The EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

This method is useful if you need to get info for special folders like Sent Items (such as via passing folder's WellKnownFolderName). This particular overload is for advanced purposes if you need property set different from those provided by basic DownloadFolderById(FolderId) overload.

Note Note
This method is not implemented in .NET Core. Use DownloadFolderByIdAsync(FolderId, PropertySet) instead.
See Also

Reference

Ews Class
DownloadFolderById Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByIdAsync Method

EwsDownloadFolderByIdAsync Method
Overload List
 | Name | Description
Public method | DownloadFolderByIdAsync(FolderId) | Async/await version of DownloadFolderById(FolderId).
Public method | DownloadFolderByIdAsync(FolderId, PropertySet) | Async/await version of DownloadFolderById(FolderId, PropertySet).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolderByIdAsync Method (FolderId)

EwsDownloadFolderByIdAsync Method (FolderId)
Async/await version of DownloadFolderById(FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsFolder> DownloadFolderByIdAsync(
    FolderId id
)
Public Function DownloadFolderByIdAsync (
    id As FolderId
) As Task(Of EwsFolder)

Parameters

id
Type: FolderId

Return Value

Type: Task EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolderById(FolderId) instead.
See Also

Reference

Ews Class
DownloadFolderByIdAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByIdAsync Method (FolderId, PropertySet)

EwsDownloadFolderByIdAsync Method (FolderId, PropertySet)
Async/await version of DownloadFolderById(FolderId, PropertySet).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsFolder> DownloadFolderByIdAsync(
    FolderId id,
    PropertySet propSet
)
Public Function DownloadFolderByIdAsync (
    id As FolderId,
    propSet As PropertySet
) As Task(Of EwsFolder)

Parameters

id
Type: FolderId
propSet
Type: PropertySet

Return Value

Type: Task EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolderById(FolderId, PropertySet) instead.
See Also

Reference

Ews Class
DownloadFolderByIdAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFolderByShortName Method

EwsDownloadFolderByShortName Method
Gets the reference to the given folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder DownloadFolderByShortName(
    FolderId parentFolderId,
    string folderName
)
Public Function DownloadFolderByShortName (
    parentFolderId As FolderId,
    folderName As String
) As EwsFolder

Parameters

parentFolderId
Type: FolderId
The ID of the parent folder where to search for the given folder. If a null reference (Nothing in Visual Basic), RootFolderType will be assumed.
folderName
Type: SystemString
The folder name. Null reference or empty string not allowed.

Return Value

Type: EwsFolder
The EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

parentFolderId must be the immediate parent of folderName folder. Also, folderName must be a short name (not a full name with nested folder names in it).

You can use DownloadFolderByFullName(FolderId, string) method to search for a folder by its full name.

Note Note
This method is not implemented in .NET Core. Use DownloadFolderByShortNameAsync(FolderId, String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolderByShortNameAsync Method

EwsDownloadFolderByShortNameAsync Method
Async/await version of DownloadFolderByShortName(FolderId, String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsFolder> DownloadFolderByShortNameAsync(
    FolderId parentFolderId,
    string folderName
)
Public Function DownloadFolderByShortNameAsync (
    parentFolderId As FolderId,
    folderName As String
) As Task(Of EwsFolder)

Parameters

parentFolderId
Type: FolderId
folderName
Type: SystemString

Return Value

Type: Task EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to EwsFolder object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolderByShortName(FolderId, String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolders Method

EwsDownloadFolders Method
Overload List
 | Name | Description
Public method | DownloadFolders(Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFolders(FolderId, Boolean, Boolean) | Downloads the list of folders of the MS Exchange account.
Public method | DownloadFolders(FolderId, FolderView, SearchFilter, Boolean) | Downloads the list of folders of the MS Exchange account.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFolders Method (Boolean)

EwsDownloadFolders Method (Boolean)
Downloads the list of folders of the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public List<EwsFolder> DownloadFolders(
    bool includeSubfolders
)
Public Function DownloadFolders (
    includeSubfolders As Boolean
) As List(Of EwsFolder)

Parameters

includeSubfolders
Type: SystemBoolean
If true, sub-folders will also be returned; otherwise, only the current level of folders.

Return Value

Type: List EwsFolder
The list of folders of the current MS Exchange account under RootFolderType, if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
This method returns the list of sub-folders of RootFolderType folder (and their own sub-folders if includeSubfolders is true).
Note Note
This method is not implemented in .NET Core. Use DownloadFoldersAsync(Boolean) instead.
See Also

Reference

Ews Class
DownloadFolders Overload
MailBee.EwsMail Namespace


Ews.DownloadFolders Method (FolderId, Boolean, Boolean)

EwsDownloadFolders Method (FolderId, Boolean, Boolean)
Downloads the list of folders of the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public List<EwsFolder> DownloadFolders(
    FolderId parentFolderId,
    bool includeParentFolder,
    bool includeSubfolders
)
Public Function DownloadFolders (
    parentFolderId As FolderId,
    includeParentFolder As Boolean,
    includeSubfolders As Boolean
) As List(Of EwsFolder)

Parameters

parentFolderId
Type: FolderId
The ID of the folder for which to return folders. If a null reference (Nothing in Visual Basic), RootFolderType value will be used.
includeParentFolder
Type: SystemBoolean
If true, the folder denoted by parentFolderId will be included in the resulting list; otherwise, it won't be there.
includeSubfolders
Type: SystemBoolean
If true, sub-folders will also be returned; otherwise, only the current level of folders.

Return Value

Type: List EwsFolder
The list of folders of the current MS Exchange account under parentFolderId, if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
This method returns the list of sub-folders of parentFolderId folder (and their own sub-folders if includeSubfolders is true).
Note Note
This method is not implemented in .NET Core. Use DownloadFoldersAsync(FolderId, Boolean, Boolean) instead.
See Also

Reference

Ews Class
DownloadFolders Overload
MailBee.EwsMail Namespace


Ews.DownloadFolders Method (FolderId, FolderView, SearchFilter, Boolean)

EwsDownloadFolders Method (FolderId, FolderView, SearchFilter, Boolean)
Downloads the list of folders of the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public List<EwsFolder> DownloadFolders(
    FolderId parentFolderId,
    FolderView view,
    SearchFilter filter,
    bool includeParentFolder
)
Public Function DownloadFolders (
    parentFolderId As FolderId,
    view As FolderView,
    filter As SearchFilter,
    includeParentFolder As Boolean
) As List(Of EwsFolder)

Parameters

parentFolderId
Type: FolderId
The ID of the folder for which to return folders. If a null reference (Nothing in Visual Basic), RootFolderType value will be used.
view
Type: FolderView
Managed EWS view object which configures how many folders to return, whether or not to include sub-folders, ordering, etc. If a null reference, MailBee will pass the view which lists no sub-folders, max item count, normal ordering.
filter
Type: SearchFilter
Managed EWS filter which configures what kind of folders to return. If a null reference, no filter will be applied and all kinds of folders will be returned.
includeParentFolder
Type: SystemBoolean
If true, the folder denoted by parentFolderId will be included in the resulting list; otherwise, it won't be there.

Return Value

Type: List EwsFolder
The list of folders of the current MS Exchange account under parentFolderId, if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
This method returns the list of sub-folders of parentFolderId folder accordingly the specified settings. If you don't need non-email folders, you can pass MessageFoldersFilter property as filter value.
Note Note
This method is not implemented in .NET Core. Use DownloadFoldersAsync(FolderId, FolderView, SearchFilter, Boolean) instead.
See Also

Reference

Ews Class
DownloadFolders Overload
MailBee.EwsMail Namespace


Ews.DownloadFoldersAsync Method

EwsDownloadFoldersAsync Method
Overload List
 | Name | Description
Public method | DownloadFoldersAsync(Boolean) | Async/await version of DownloadFolders(Boolean).
Public method | DownloadFoldersAsync(FolderId, Boolean, Boolean) | Async/await version of DownloadFolders(FolderId, Boolean, Boolean).
Public method | DownloadFoldersAsync(FolderId, FolderView, SearchFilter, Boolean) | Async/await version of DownloadFolders(FolderId, FolderView, SearchFilter, Boolean).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadFoldersAsync Method (Boolean)

EwsDownloadFoldersAsync Method (Boolean)
Async/await version of DownloadFolders(Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<List<EwsFolder>> DownloadFoldersAsync(
    bool includeSubfolders
)
Public Function DownloadFoldersAsync (
    includeSubfolders As Boolean
) As Task(Of List(Of EwsFolder))

Parameters

includeSubfolders
Type: SystemBoolean

Return Value

Type: Task List EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to the list of sub-folders of RootFolderType folder (and their own sub-folders if includeSubfolders is true) if the method succeeds; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolders(Boolean) instead.
See Also

Reference

Ews Class
DownloadFoldersAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFoldersAsync Method (FolderId, Boolean, Boolean)

EwsDownloadFoldersAsync Method (FolderId, Boolean, Boolean)
Async/await version of DownloadFolders(FolderId, Boolean, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<List<EwsFolder>> DownloadFoldersAsync(
    FolderId parentFolderId,
    bool includeParentFolder,
    bool includeSubfolders
)
Public Function DownloadFoldersAsync (
    parentFolderId As FolderId,
    includeParentFolder As Boolean,
    includeSubfolders As Boolean
) As Task(Of List(Of EwsFolder))

Parameters

parentFolderId
Type: FolderId
includeParentFolder
Type: SystemBoolean
includeSubfolders
Type: SystemBoolean

Return Value

Type: Task List EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to the list of sub-folders of RootFolderType folder (and their own sub-folders if includeSubfolders is true) if the method succeeds; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolders(FolderId, Boolean, Boolean) instead.
See Also

Reference

Ews Class
DownloadFoldersAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadFoldersAsync Method (FolderId, FolderView, SearchFilter, Boolean)

EwsDownloadFoldersAsync Method (FolderId, FolderView, SearchFilter, Boolean)
Async/await version of DownloadFolders(FolderId, FolderView, SearchFilter, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<List<EwsFolder>> DownloadFoldersAsync(
    FolderId parentFolderId,
    FolderView view,
    SearchFilter filter,
    bool includeParentFolder
)
Public Function DownloadFoldersAsync (
    parentFolderId As FolderId,
    view As FolderView,
    filter As SearchFilter,
    includeParentFolder As Boolean
) As Task(Of List(Of EwsFolder))

Parameters

parentFolderId
Type: FolderId
view
Type: FolderView
filter
Type: SearchFilter
includeParentFolder
Type: SystemBoolean

Return Value

Type: Task List EwsFolder
A task that represents the asynchronous operation. The value of TResult parameter points to the list of folders of the current MS Exchange account under parentFolderId, if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadFolders(FolderId, FolderView, SearchFilter, Boolean) instead.
See Also

Reference

Ews Class
DownloadFoldersAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItem Method

EwsDownloadItem Method
Downloads the specified item by its ID.
Overload List
 | Name | Description
Public method | DownloadItem(FolderId, Int32) | Downloads an item in the specified folder at the specified index.
Public method | DownloadItem(ItemId, EwsItemParts) | Downloads the specified portions of the specified item by its ID.
Public method | DownloadItem(ItemId, PropertySet) | Downloads the specified item by its ID using PropertySet settings.
Public method | DownloadItem(FolderId, Int32, EwsItemParts) | Downloads the specified portions of an Exchange item in the specified folder at the specified index.
Public method | DownloadItem(FolderId, Int32, PropertySet) | Downloads an item in the specified folder at the specified index using PropertySet settings.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadItem Method (FolderId, Int32)

EwsDownloadItem Method (FolderId, Int32)
Downloads an item in the specified folder at the specified index.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem DownloadItem(
    FolderId id,
    int index
)
Public Function DownloadItem (
    id As FolderId,
    index As Integer
) As EwsItem

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
index
Type: SystemInt32
The zero-based index of the message to be downloaded.

Return Value

Type: EwsItem
The item in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

Note Note
This overload downloads only basic properties of an Exchange. You need to use other overloads (such as those accepting the parameter of EwsItemParts type) to get full e-mail message.
Note Note
In EWS, message indices start from 0 while in IMAP and POP3 they start from 1. Also, the default sorting order in Exchange is "newer first". In IMAP/POP3, "older first" is the default.
Note Note
This method is not implemented in .NET Core. Use DownloadItemAsync(FolderId, Int32) instead.
See Also

Reference

Ews Class
DownloadItem Overload
MailBee.EwsMail Namespace


Ews.DownloadItem Method (ItemId, EwsItemParts)

EwsDownloadItem Method (ItemId, EwsItemParts)
Downloads the specified portions of the specified item by its ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem DownloadItem(
    ItemId id,
    EwsItemParts parts
)
Public Function DownloadItem (
    id As ItemId,
    parts As EwsItemParts
) As EwsItem

Parameters

id
Type: ItemId
The ID of the item. Null reference (Nothing in Visual Basic) not allowed.
parts
Type: MailBee.EwsMailEwsItemParts
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). You can combine multiple values.

Return Value

Type: EwsItem
The downloaded item, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To get item IDs, you can use DownloadItemIds(FolderId, Boolean) or Search(FolderId, SearchFilter) methods and then pass Id of items of the returned list to the current method.

In advanced cases, you can store UniqueId string in database and later recreate ItemId object using #ctor(String) constructor. Then you can supply that object to this method. This is useful in case if you need to get IDs for items and items themselves at different times.

Note Note
This method is not implemented in .NET Core. Use DownloadItemAsync(ItemId, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItem Overload
MailBee.EwsMail Namespace


Ews.DownloadItem Method (ItemId, PropertySet)

EwsDownloadItem Method (ItemId, PropertySet)
Downloads the specified item by its ID using PropertySet settings.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem DownloadItem(
    ItemId id,
    PropertySet properties
)
Public Function DownloadItem (
    id As ItemId,
    properties As PropertySet
) As EwsItem

Parameters

id
Type: ItemId
The ID of the item. Null reference (Nothing in Visual Basic) not allowed.
properties
Type: PropertySet
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). If a null reference, only item ID is requested.

Return Value

Type: EwsItem
The downloaded item, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To get item IDs, you can use DownloadItemIds(FolderId, Boolean) or Search(FolderId, SearchFilter) methods and then pass Id of items of the returned list to the current method.

In advanced cases, you can store UniqueId string in database and later recreate ItemId object using #ctor(String) constructor. Then you can supply that object to this method. This is useful in case if you need to get IDs for items and items themselves at different times.

Note Note
This method is not implemented in .NET Core. Use DownloadItemAsync(ItemId, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItem Overload
MailBee.EwsMail Namespace


Ews.DownloadItem Method (FolderId, Int32, EwsItemParts)

EwsDownloadItem Method (FolderId, Int32, EwsItemParts)
Downloads the specified portions of an Exchange item in the specified folder at the specified index.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem DownloadItem(
    FolderId id,
    int index,
    EwsItemParts parts
)
Public Function DownloadItem (
    id As FolderId,
    index As Integer,
    parts As EwsItemParts
) As EwsItem

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
index
Type: SystemInt32
The zero-based index of the message to be downloaded.
parts
Type: MailBee.EwsMailEwsItemParts
The settings which specify which portions of an MS Exchange item to download (e.g. item ID, mail header, body, etc). You can combine multiple values.

Return Value

Type: EwsItem
The item in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

With this overload you can download an entire message by passing MailMessageFull as parts parameter value.

Note Note
In EWS, message indices start from 0 while in IMAP and POP3 they start from 1. Also, the default sorting order in Exchange is "newer first". In IMAP/POP3, "older first" is the default.
Note Note
This method is not implemented in .NET Core. Use DownloadItemAsync(FolderId, Int32, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItem Overload
MailBee.EwsMail Namespace


Ews.DownloadItem Method (FolderId, Int32, PropertySet)

EwsDownloadItem Method (FolderId, Int32, PropertySet)
Downloads an item in the specified folder at the specified index using PropertySet settings.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem DownloadItem(
    FolderId id,
    int index,
    PropertySet properties
)
Public Function DownloadItem (
    id As FolderId,
    index As Integer,
    properties As PropertySet
) As EwsItem

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
index
Type: SystemInt32
The zero-based index of the message to be downloaded.
properties
Type: PropertySet
The settings which specify which portions of an MS Exchange item to download (e.g. item ID, mail header, body, etc). If a null reference, only item ID is requested.

Return Value

Type: EwsItem
The item in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

This is advanced overload which lets you request item parts in the native way of Exchange EWS (via PropertySet obejct). If you just want to dowload a full message with attachments, use DownloadItem(FolderId, Int32, EwsItemParts) overload and pass MailMessageFull as parts parameter value.

Note Note
In EWS, message indices start from 0 while in IMAP and POP3 they start from 1. Also, the default sorting order in Exchange is "newer first". In IMAP/POP3, "older first" is the default.
Note Note
This method is not implemented in .NET Core. Use DownloadItemAsync(FolderId, Int32, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItem Overload
MailBee.EwsMail Namespace


Ews.DownloadItemAsync Method

EwsDownloadItemAsync Method
Overload List
 | Name | Description
Public method | DownloadItemAsync(FolderId, Int32) | Async/await version of DownloadItem(FolderId, Int32).
Public method | DownloadItemAsync(ItemId, EwsItemParts) | Async/await version of DownloadItem(ItemId, EwsItemParts).
Public method | DownloadItemAsync(ItemId, PropertySet) | Async/await version of DownloadItem(ItemId, PropertySet).
Public method | DownloadItemAsync(FolderId, Int32, EwsItemParts) | Async/await version of DownloadItem(FolderId, Int32, EwsItemParts).
Public method | DownloadItemAsync(FolderId, Int32, PropertySet) | Async/await version of DownloadItem(FolderId, Int32, PropertySet).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadItemAsync Method (FolderId, Int32)

EwsDownloadItemAsync Method (FolderId, Int32)
Async/await version of DownloadItem(FolderId, Int32).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItem> DownloadItemAsync(
    FolderId id,
    int index
)
Public Function DownloadItemAsync (
    id As FolderId,
    index As Integer
) As Task(Of EwsItem)

Parameters

id
Type: FolderId
index
Type: SystemInt32

Return Value

Type: Task EwsItem
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItem object which represents the item in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItem(FolderId, Int32) instead.
See Also

Reference

Ews Class
DownloadItemAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemAsync Method (ItemId, EwsItemParts)

EwsDownloadItemAsync Method (ItemId, EwsItemParts)
Async/await version of DownloadItem(ItemId, EwsItemParts).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItem> DownloadItemAsync(
    ItemId id,
    EwsItemParts parts
)
Public Function DownloadItemAsync (
    id As ItemId,
    parts As EwsItemParts
) As Task(Of EwsItem)

Parameters

id
Type: ItemId
parts
Type: MailBee.EwsMailEwsItemParts

Return Value

Type: Task EwsItem
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItem object which represents the downloaded item, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItem(ItemId, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItemAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemAsync Method (ItemId, PropertySet)

EwsDownloadItemAsync Method (ItemId, PropertySet)
Async/await version of DownloadItem(ItemId, PropertySet).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItem> DownloadItemAsync(
    ItemId id,
    PropertySet properties
)
Public Function DownloadItemAsync (
    id As ItemId,
    properties As PropertySet
) As Task(Of EwsItem)

Parameters

id
Type: ItemId
properties
Type: PropertySet

Return Value

Type: Task EwsItem
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItem object which represents the downloaded item, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItem(ItemId, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItemAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemAsync Method (FolderId, Int32, EwsItemParts)

EwsDownloadItemAsync Method (FolderId, Int32, EwsItemParts)
Async/await version of DownloadItem(FolderId, Int32, EwsItemParts).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItem> DownloadItemAsync(
    FolderId id,
    int index,
    EwsItemParts parts
)
Public Function DownloadItemAsync (
    id As FolderId,
    index As Integer,
    parts As EwsItemParts
) As Task(Of EwsItem)

Parameters

id
Type: FolderId
index
Type: SystemInt32
parts
Type: MailBee.EwsMailEwsItemParts

Return Value

Type: Task EwsItem
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItem object which represents the item in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItem(FolderId, Int32, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItemAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemAsync Method (FolderId, Int32, PropertySet)

EwsDownloadItemAsync Method (FolderId, Int32, PropertySet)
Async/await version of DownloadItem(FolderId, Int32, PropertySet).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItem> DownloadItemAsync(
    FolderId id,
    int index,
    PropertySet properties
)
Public Function DownloadItemAsync (
    id As FolderId,
    index As Integer,
    properties As PropertySet
) As Task(Of EwsItem)

Parameters

id
Type: FolderId
index
Type: SystemInt32
properties
Type: PropertySet

Return Value

Type: Task EwsItem
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItem object which represents the item in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItem(FolderId, Int32, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItemAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemIds Method

EwsDownloadItemIds Method
Downloads IDs of items in the specified folder.
Overload List
 | Name | Description
Public method | DownloadItemIds(FolderId, Boolean) | Downloads IDs of all or unread items in the specified folder.
Public method | DownloadItemIds(FolderId, ItemView, Boolean) | Downloads IDs of items in the specified folder in the specified ItemView range.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadItemIds Method (FolderId, Boolean)

EwsDownloadItemIds Method (FolderId, Boolean)
Downloads IDs of all or unread items in the specified folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItemIds(
    FolderId id,
    bool unreadOnly
)
Public Function DownloadItemIds (
    id As FolderId,
    unreadOnly As Boolean
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.

Return Value

Type: EwsItemList
The list of EwsItem items with Id property set, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

You can use this method to get the list of all IDs in the folder. You can then use methods like DownloadItems(IEnumerableEwsItem, EwsItemParts) to get full items for the returned list (you can also process the returned list to make any subset from it or change sorting order, for instance, to implement paged output). You can also use MS Exchange's own mechanism of paging using ItemView objects with methods like DownloadItemIds(FolderId, ItemView, bool) or DownloadItems(FolderId, ItemView, bool, EwsItemParts).

Item string IDs (UniqueId value) can then be stored elsewhere, and you can later recreate EwsItem from that string using EwsItem(String) constructor.

Items are returned in the default sorting order which usually means "newer first" in Exchange. This is different from IMAP and POP3, where "older first" is the default.

Note Note
In the returned collection of EwsItem objects, you can access their Id and UniqueId properties only. Accessing other properties will cause an exception (because only ID was loaded for each item).
Note Note
This method is not implemented in .NET Core. Use DownloadItemIdsAsync(FolderId, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemIds Overload
MailBee.EwsMail Namespace


Ews.DownloadItemIds Method (FolderId, ItemView, Boolean)

EwsDownloadItemIds Method (FolderId, ItemView, Boolean)
Downloads IDs of items in the specified folder in the specified ItemView range.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItemIds(
    FolderId id,
    ItemView view,
    bool unreadOnly
)
Public Function DownloadItemIds (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
view
Type: ItemView
The settings which specify how many items to download, offset, and ordering. If a null reference, all the matching items are downloaded.
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.

Return Value

Type: EwsItemList
The list of EwsItem items with Id property set, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

Usually, you'll immediately pass the returned list to a method like DownloadItems(IEnumerableEwsItem, EwsItemParts). However, once you downloaded the item IDs, you can also store UniqueId values elsewhere and later recreate EwsItem objects from that strings using EwsItem(String) constructor.

Items are returned in the default sorting order which usually means "newer first" in Exchange. This is different from IMAP and POP3, where "older first" is the default.

Note Note
In the returned collection of EwsItem objects, you can access their Id and UniqueId properties only. Accessing other properties will cause an exception (because only ID was loaded for each item).
Note Note
This method is not implemented in .NET Core. Use DownloadItemIdsAsync(FolderId, ItemView, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemIds Overload
MailBee.EwsMail Namespace


Ews.DownloadItemIdsAsync Method

EwsDownloadItemIdsAsync Method
Overload List
 | Name | Description
Public method | DownloadItemIdsAsync(FolderId, Boolean) | Async/await version of DownloadItemIds(FolderId, Boolean).
Public method | DownloadItemIdsAsync(FolderId, ItemView, Boolean) | Async/await version of DownloadItemIds(FolderId, ItemView, Boolean).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadItemIdsAsync Method (FolderId, Boolean)

EwsDownloadItemIdsAsync Method (FolderId, Boolean)
Async/await version of DownloadItemIds(FolderId, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemIdsAsync(
    FolderId id,
    bool unreadOnly
)
Public Function DownloadItemIdsAsync (
    id As FolderId,
    unreadOnly As Boolean
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
unreadOnly
Type: SystemBoolean

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of EwsItem items with Id property set, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItemIds(FolderId, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemIdsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemIdsAsync Method (FolderId, ItemView, Boolean)

EwsDownloadItemIdsAsync Method (FolderId, ItemView, Boolean)
Async/await version of DownloadItemIds(FolderId, ItemView, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemIdsAsync(
    FolderId id,
    ItemView view,
    bool unreadOnly
)
Public Function DownloadItemIdsAsync (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
view
Type: ItemView
unreadOnly
Type: SystemBoolean

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of EwsItem items with Id property set, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItemIds(FolderId, ItemView, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemIdsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method

EwsDownloadItems Method
Downloads MS Exchange items (mail messages, etc).
Overload List
 | Name | Description
Public method | DownloadItems(FolderId, Boolean) | Downloads all or unread items in the specified folder.
Public method | DownloadItems(IEnumerableEwsItem, EwsItemParts) | Downloads the specified portions of the specified items.
Public method | DownloadItems(IEnumerableEwsItem, PropertySet) | Downloads the specified items using PropertySet settings.
Public method | DownloadItems(FolderId, ItemView, Boolean) | Downloads items in the specified folder in the specified ItemView range.
Public method | DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) | Downloads the specified portions of the items in the specified ItemView range in the specified folder.
Public method | DownloadItems(FolderId, ItemView, Boolean, PropertySet) | Downloads items in the specified folder in the specified ItemView range using PropertySet settings.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean) | Downloads items in the specified folder in the specified range.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) | Downloads the specified portions of Exchange items in the specified folder in the specified range.
Public method | DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet) | Downloads items in the specified folder in the specified range using PropertySet settings.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, Boolean)

EwsDownloadItems Method (FolderId, Boolean)
Downloads all or unread items in the specified folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    bool unreadOnly
)
Public Function DownloadItems (
    id As FolderId,
    unreadOnly As Boolean
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
unreadOnly
Type: SystemBoolean
If true, only unread items are downloaded; otherwise, all the items.

Return Value

Type: EwsItemList
The list of all/unread items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

This method can be slow or even time out for folders with thousands of items. For large folders, it's recommended to use overloads which let you specify item ranges.

Note Note
This overload downloads only basic properties of Exchange items. You need to use other overloads to get full e-mail messages.
Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, Boolean) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (IEnumerable(EwsItem), EwsItemParts)

EwsDownloadItems Method (IEnumerableEwsItem, EwsItemParts)
Downloads the specified portions of the specified items.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    IEnumerable<EwsItem> itemIds,
    EwsItemParts parts
)
Public Function DownloadItems (
    itemIds As IEnumerable(Of EwsItem),
    parts As EwsItemParts
) As EwsItemList

Parameters

itemIds
Type: System.Collections.GenericIEnumerable EwsItem
The IDs of the items to download. Null reference (Nothing in Visual Basic) not allowed
parts
Type: MailBee.EwsMailEwsItemParts
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). You can combine multiple values.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To get the list of item IDs for downloading you can use DownloadItemIds(FolderId, Boolean) or Search(FolderId, SearchFilter) methods.

This overload lets you utilize Managed EWS API if you need to download only some portion of items in the folder (for instance, to enable paged output). Alternatively, you can download all IDs of all items using DownloadItemIds(FolderId, Boolean) method and then use DownloadItems(IEnumerable<EwsItem>, EwsItemParts) overload to download the requested items.

Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(IEnumerableEwsItem, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (IEnumerable(EwsItem), PropertySet)

EwsDownloadItems Method (IEnumerableEwsItem, PropertySet)
Downloads the specified items using PropertySet settings.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    IEnumerable<EwsItem> itemIds,
    PropertySet properties
)
Public Function DownloadItems (
    itemIds As IEnumerable(Of EwsItem),
    properties As PropertySet
) As EwsItemList

Parameters

itemIds
Type: System.Collections.GenericIEnumerable EwsItem
The IDs of the items to download. Null reference (Nothing in Visual Basic) not allowed
properties
Type: PropertySet
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). If a null reference, only item ID is requested.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To get the list of item IDs for downloading you can use DownloadItemIds(FolderId, Boolean) or Search(FolderId, SearchFilter) methods.

You can build PropertySet object manually or use CreatePropSet(EwsItemParts) method for this (or just use DownloadItems(IEnumerable<EwsItem>, EwsItemParts) overload).

Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(IEnumerableEwsItem, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, ItemView, Boolean)

EwsDownloadItems Method (FolderId, ItemView, Boolean)
Downloads items in the specified folder in the specified ItemView range.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    ItemView view,
    bool unreadOnly
)
Public Function DownloadItems (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
view
Type: ItemView
The settings which describe how many items to download, offset, and sort ordering. If a null reference, all the matching items are downloaded and the sorting order is default (usually, "newer first").
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

This overload lets you specify EWS's ItemView object to configure ordering and paging of the results. Alternatively, you can download all IDs of all items using DownloadItemIds(FolderId, Boolean) method and then use DownloadItems(IEnumerable<EwsItem>, EwsItemParts) overload to download the requested items.

You can also use DownloadItems(FolderId, int, int, bool) overload if you have a range of messages you want to download.

Note Note
This overload downloads only basic properties of Exchange items. You need to use other overloads to get full e-mail messages.
Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, ItemView, Boolean) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, ItemView, Boolean, EwsItemParts)

EwsDownloadItems Method (FolderId, ItemView, Boolean, EwsItemParts)
Downloads the specified portions of the items in the specified ItemView range in the specified folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    ItemView view,
    bool unreadOnly,
    EwsItemParts parts
)
Public Function DownloadItems (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean,
    parts As EwsItemParts
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
view
Type: ItemView
The settings which specify how many items to download, offset, and sort ordering. If a null reference, all the matching items in the folder are downloaded and the sorting order is default (usually, "newer first").
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.
parts
Type: MailBee.EwsMailEwsItemParts
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). You can combine multiple values.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

This overload lets you specify EWS's ItemView object to configure ordering and paging of the results. Alternatively, you can download all IDs of all items using DownloadItemIds(FolderId, Boolean) method and then use DownloadItems(IEnumerable<EwsItem>, EwsItemParts) overload to download the requested items.

You can also use DownloadItems(FolderId, int, int, bool, EwsItemParts) overload if you have a range of messages you want to download.

With the current overload you can download entire messages by passing MailMessageFull as parts parameter value.

Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, ItemView, Boolean, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, ItemView, Boolean, PropertySet)

EwsDownloadItems Method (FolderId, ItemView, Boolean, PropertySet)
Downloads items in the specified folder in the specified ItemView range using PropertySet settings.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    ItemView view,
    bool unreadOnly,
    PropertySet properties
)
Public Function DownloadItems (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean,
    properties As PropertySet
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
view
Type: ItemView
The settings which specify how many items to download, offset, and sort ordering. If a null reference, all the matching items are downloaded and the sorting order is default (usually, "newer first").
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.
properties
Type: PropertySet
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). If a null reference, only item ID is requested.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

This overload lets you specify EWS's ItemView object to configure ordering and paging of the results. Alternatively, you can download all IDs of all items using DownloadItemIds(FolderId, Boolean) method and then use DownloadItems(IEnumerable<EwsItem>, EwsItemParts) overload to download the requested items.

You can also use DownloadItems(FolderId, int, int, bool, PropertySet) overload if you have a range of messages you want to download.

As for properties parameter, You can build PropertySet object manually or use CreatePropSet(EwsItemParts) method for this.

Note Note
view parameter (ItemView object) has its own PropertySet setting. It's not used by this method so it's recommended to leave the default value. If you need this value to be actually consumed, consider Search(FolderId, SearchFilter, ItemView) method instead.
Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, ItemView, Boolean, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, Int32, Int32, Boolean)

EwsDownloadItems Method (FolderId, Int32, Int32, Boolean)
Downloads items in the specified folder in the specified range.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    int startIndex,
    int count,
    bool unreadOnly
)
Public Function DownloadItems (
    id As FolderId,
    startIndex As Integer,
    count As Integer,
    unreadOnly As Boolean
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
startIndex
Type: SystemInt32
The zero-based index of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of items to be downloaded.
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

Note Note
This overload downloads only basic properties of Exchange items. You need to use other overloads (such as those accepting the parameter of EwsItemParts type) to get full e-mail messages.
Note Note
In EWS, message indices start from 0 while in IMAP and POP3 they start from 1. Also, items are returned in the default sorting order which usually means "newer first" in Exchange. In IMAP/POP3, "older first" is the default. To change sorting order, use overloads accepting the parameter of ItemView type.
Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, Int32, Int32, Boolean) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, Int32, Int32, Boolean, EwsItemParts)

EwsDownloadItems Method (FolderId, Int32, Int32, Boolean, EwsItemParts)
Downloads the specified portions of Exchange items in the specified folder in the specified range.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    int startIndex,
    int count,
    bool unreadOnly,
    EwsItemParts parts
)
Public Function DownloadItems (
    id As FolderId,
    startIndex As Integer,
    count As Integer,
    unreadOnly As Boolean,
    parts As EwsItemParts
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
startIndex
Type: SystemInt32
The zero-based index of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of items to be downloaded.
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.
parts
Type: MailBee.EwsMailEwsItemParts
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). You can combine multiple values.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

With this overload you can download entire messages by passing MailMessageFull as parts parameter value.

Note Note
In EWS, message indices start from 0 while in IMAP and POP3 they start from 1. Also, items are returned in the default sorting order which usually means "newer first" in Exchange. In IMAP/POP3, "older first" is the default. To change sorting order, use overloads accepting the parameter of ItemView type.
Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, Int32, Int32, Boolean, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItems Method (FolderId, Int32, Int32, Boolean, PropertySet)

EwsDownloadItems Method (FolderId, Int32, Int32, Boolean, PropertySet)
Downloads items in the specified folder in the specified range using PropertySet settings.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList DownloadItems(
    FolderId id,
    int startIndex,
    int count,
    bool unreadOnly,
    PropertySet properties
)
Public Function DownloadItems (
    id As FolderId,
    startIndex As Integer,
    count As Integer,
    unreadOnly As Boolean,
    properties As PropertySet
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder. Null reference (Nothing in Visual Basic) not allowed.
startIndex
Type: SystemInt32
The zero-based index of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of items to be downloaded.
unreadOnly
Type: SystemBoolean
If true, only unread items are considered for download; otherwise, all the items.
properties
Type: PropertySet
The settings which specify which portions of MS Exchange items to download (e.g. item ID, mail header, body, etc). If a null reference, only item ID is requested.

Return Value

Type: EwsItemList
The list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

This is advanced overload which lets you request item parts in the native way of Exchange EWS (via PropertySet obejct). If you just want to dowload full messages with attachments, use DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) overload and pass MailMessageFull as parts parameter value.

Note Note
In EWS, message indices start from 0 while in IMAP and POP3 they start from 1. Also, items are returned in the default sorting order which usually means "newer first" in Exchange. In IMAP/POP3, "older first" is the default. To change sorting order, use overloads accepting the parameter of ItemView type.
Note Note
This method is not implemented in .NET Core. Use DownloadItemsAsync(FolderId, Int32, Int32, Boolean, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItems Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method

EwsDownloadItemsAsync Method
Overload List
 | Name | Description
Public method | DownloadItemsAsync(FolderId, Boolean) | Async/await version of DownloadItems(FolderId, Boolean).
Public method | DownloadItemsAsync(IEnumerableEwsItem, EwsItemParts) | Async/await version of DownloadItems(IEnumerableEwsItem, EwsItemParts).
Public method | DownloadItemsAsync(IEnumerableEwsItem, PropertySet) | Async/await version of DownloadItems(IEnumerableEwsItem, PropertySet).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean) | Async/await version of DownloadItems(FolderId, ItemView, Boolean).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean, EwsItemParts) | Async/await version of DownloadItems(FolderId, ItemView, Boolean, EwsItemParts).
Public method | DownloadItemsAsync(FolderId, ItemView, Boolean, PropertySet) | Async/await version of DownloadItems(FolderId, ItemView, Boolean, PropertySet).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean, EwsItemParts) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts).
Public method | DownloadItemsAsync(FolderId, Int32, Int32, Boolean, PropertySet) | Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, Boolean)

EwsDownloadItemsAsync Method (FolderId, Boolean)
Async/await version of DownloadItems(FolderId, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    bool unreadOnly
)
Public Function DownloadItemsAsync (
    id As FolderId,
    unreadOnly As Boolean
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
unreadOnly
Type: SystemBoolean

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of all/unread items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (IEnumerable(EwsItem), EwsItemParts)

EwsDownloadItemsAsync Method (IEnumerableEwsItem, EwsItemParts)
Async/await version of DownloadItems(IEnumerableEwsItem, EwsItemParts).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    IEnumerable<EwsItem> itemIds,
    EwsItemParts parts
)
Public Function DownloadItemsAsync (
    itemIds As IEnumerable(Of EwsItem),
    parts As EwsItemParts
) As Task(Of EwsItemList)

Parameters

itemIds
Type: System.Collections.GenericIEnumerable EwsItem
parts
Type: MailBee.EwsMailEwsItemParts

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(IEnumerableEwsItem, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (IEnumerable(EwsItem), PropertySet)

EwsDownloadItemsAsync Method (IEnumerableEwsItem, PropertySet)
Async/await version of DownloadItems(IEnumerableEwsItem, PropertySet).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    IEnumerable<EwsItem> itemIds,
    PropertySet properties
)
Public Function DownloadItemsAsync (
    itemIds As IEnumerable(Of EwsItem),
    properties As PropertySet
) As Task(Of EwsItemList)

Parameters

itemIds
Type: System.Collections.GenericIEnumerable EwsItem
properties
Type: PropertySet

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(IEnumerableEwsItem, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, ItemView, Boolean)

EwsDownloadItemsAsync Method (FolderId, ItemView, Boolean)
Async/await version of DownloadItems(FolderId, ItemView, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    ItemView view,
    bool unreadOnly
)
Public Function DownloadItemsAsync (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
view
Type: ItemView
unreadOnly
Type: SystemBoolean

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, ItemView, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, ItemView, Boolean, EwsItemParts)

EwsDownloadItemsAsync Method (FolderId, ItemView, Boolean, EwsItemParts)
Async/await version of DownloadItems(FolderId, ItemView, Boolean, EwsItemParts).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    ItemView view,
    bool unreadOnly,
    EwsItemParts parts
)
Public Function DownloadItemsAsync (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean,
    parts As EwsItemParts
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
view
Type: ItemView
unreadOnly
Type: SystemBoolean
parts
Type: MailBee.EwsMailEwsItemParts

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, ItemView, Boolean, PropertySet)

EwsDownloadItemsAsync Method (FolderId, ItemView, Boolean, PropertySet)
Async/await version of DownloadItems(FolderId, ItemView, Boolean, PropertySet).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    ItemView view,
    bool unreadOnly,
    PropertySet properties
)
Public Function DownloadItemsAsync (
    id As FolderId,
    view As ItemView,
    unreadOnly As Boolean,
    properties As PropertySet
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
view
Type: ItemView
unreadOnly
Type: SystemBoolean
properties
Type: PropertySet

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, ItemView, Boolean, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, Int32, Int32, Boolean)

EwsDownloadItemsAsync Method (FolderId, Int32, Int32, Boolean)
Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    int startIndex,
    int count,
    bool unreadOnly
)
Public Function DownloadItemsAsync (
    id As FolderId,
    startIndex As Integer,
    count As Integer,
    unreadOnly As Boolean
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
startIndex
Type: SystemInt32
count
Type: SystemInt32
unreadOnly
Type: SystemBoolean

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, Int32, Int32, Boolean) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, Int32, Int32, Boolean, EwsItemParts)

EwsDownloadItemsAsync Method (FolderId, Int32, Int32, Boolean, EwsItemParts)
Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    int startIndex,
    int count,
    bool unreadOnly,
    EwsItemParts parts
)
Public Function DownloadItemsAsync (
    id As FolderId,
    startIndex As Integer,
    count As Integer,
    unreadOnly As Boolean,
    parts As EwsItemParts
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
startIndex
Type: SystemInt32
count
Type: SystemInt32
unreadOnly
Type: SystemBoolean
parts
Type: MailBee.EwsMailEwsItemParts

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadItemsAsync Method (FolderId, Int32, Int32, Boolean, PropertySet)

EwsDownloadItemsAsync Method (FolderId, Int32, Int32, Boolean, PropertySet)
Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> DownloadItemsAsync(
    FolderId id,
    int startIndex,
    int count,
    bool unreadOnly,
    PropertySet properties
)
Public Function DownloadItemsAsync (
    id As FolderId,
    startIndex As Integer,
    count As Integer,
    unreadOnly As Boolean,
    properties As PropertySet
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
startIndex
Type: SystemInt32
count
Type: SystemInt32
unreadOnly
Type: SystemBoolean
properties
Type: PropertySet

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to EwsItemList object which represents the list of items in the given folder, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet) instead.
See Also

Reference

Ews Class
DownloadItemsAsync Overload
MailBee.EwsMail Namespace


Ews.DownloadNativeAttachments Method

EwsDownloadNativeAttachments Method
Downloads attachments with the specified string IDs.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public List<Attachment> DownloadNativeAttachments(
    string[] attachmentIds,
    bool ignoreInlineAttachments
)
Public Function DownloadNativeAttachments (
    attachmentIds As String(),
    ignoreInlineAttachments As Boolean
) As List(Of Attachment)

Parameters

attachmentIds
Type: SystemString
The array of attachment IDs. Null reference (Nothing in Visual Basic) or empty array not allowed.
ignoreInlineAttachments
Type: SystemBoolean
If true, only "real" attachments will be returned. If false, attachments of all types will be returned (including embedded pics, etc).

Return Value

Type: List Attachment
The list of MS Exchange attachments, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

This is the advanced method which deals directly with EWS Managed API objects and types.

To get the list of attachment IDs (which you can supply to this method), you'll need to use a method like DownloadItem(ItemId, EwsItemParts) with MailMessageAttachments flag set and then examine Attachments collection of NativeMessage object.

Attachment type does not expose all the available EWS Managed API attachment properties. You'll need to cast it to FileAttachment or ItemAttachment types to get the rest of them.

Note Note
To simply get e-mail message with all attachments, use DownloadEntireMessage(ItemId) method. It will return the message with attachments collection in the same way Imap and Pop3 components do. DownloadNativeAttachments(String, Boolean) method, however, returns attachment objects using native MS Exchange types, not MailBee types. This can be useful for advanced purposes if you need to extract MS Exchange specific data from them.
Note Note
This method is not implemented in .NET Core. Use DownloadNativeAttachmentsAsync(String, Boolean) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DownloadNativeAttachmentsAsync Method

EwsDownloadNativeAttachmentsAsync Method
Async/await version of DownloadNativeAttachments(String, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<List<Attachment>> DownloadNativeAttachmentsAsync(
    string[] attachmentIds,
    bool ignoreInlineAttachments
)
Public Function DownloadNativeAttachmentsAsync (
    attachmentIds As String(),
    ignoreInlineAttachments As Boolean
) As Task(Of List(Of Attachment))

Parameters

attachmentIds
Type: SystemString
ignoreInlineAttachments
Type: SystemBoolean

Return Value

Type: Task List Attachment
A task that represents the asynchronous operation. The value of TResult parameter points to the list of MS Exchange attachments, or a null reference (Nothing in Visual Basic) on error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use DownloadNativeAttachments(String, Boolean) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.EmptyFolder Method

EwsEmptyFolder Method
Empties a folder with the specified ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EmptyFolder(
    FolderId id,
    bool deleteSubFolders
)
Public Function EmptyFolder (
    id As FolderId,
    deleteSubFolders As Boolean
) As Boolean

Parameters

id
Type: FolderId
The ID of the folder to empty. Null reference (Nothing in Visual Basic) not allowed.
deleteSubFolders
Type: SystemBoolean
If true, sub-folders will be deleted as well as items in the folder itself. Otherwise, only items in the folder itself will be deleted.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To empty a folder by its name, first locate its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

To control how items are deleted (e.g. to Trash or permanently), use DeleteMethod property.

Note Note
This method is not implemented in .NET Core. Use EmptyFolderAsync(FolderId, Boolean) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.EmptyFolderAsync Method

EwsEmptyFolderAsync Method
Async/await version of EmptyFolder(FolderId, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> EmptyFolderAsync(
    FolderId id,
    bool deleteSubFolders
)
Public Function EmptyFolderAsync (
    id As FolderId,
    deleteSubFolders As Boolean
) As Task(Of Boolean)

Parameters

id
Type: FolderId
deleteSubFolders
Type: SystemBoolean

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use EmptyFolder(FolderId, Boolean) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.EwsItemsToItemIds Method

EwsEwsItemsToItemIds Method
Creates the list of ItemId objects from the collection of EwsItem objects.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static List<ItemId> EwsItemsToItemIds(
    IEnumerable<EwsItem> items
)
Public Shared Function EwsItemsToItemIds (
    items As IEnumerable(Of EwsItem)
) As List(Of ItemId)

Parameters

items
Type: System.Collections.GenericIEnumerable EwsItem
The collection from which to create the list of EwsItem objects.

Return Value

Type: List ItemId
The list of EwsItem objects.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | items is a null reference (Nothing in Visual Basic).
Remarks
This is a helper method which you can use if you have a collection of EwsItem objects which you need to pass to a method accepting the collection of ItemId objects. For instance, you got the collection of EwsItem objects with DownloadItemIds(FolderId, Boolean) method and want to pass it to DeleteItems(IEnumerableItemId) method (which accepts the collection of ItemId objects).
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullName Method

EwsFindFolderIdByFullName Method
Overload List
 | Name | Description
Public method | FindFolderIdByFullName(String) | Gets the ID of the folder denoted by its full name in the MS Exchange account.
Public method | FindFolderIdByFullName(FolderId, String) | Gets the ID of the given folder in the specified containing folder in the MS Exchange account.
Public method | FindFolderIdByFullName(String, Int32) | Gets the ID of the given folder in the MS Exchange account.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullName Method (String)

EwsFindFolderIdByFullName Method (String)
Gets the ID of the folder denoted by its full name in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderId FindFolderIdByFullName(
    string folderFullName
)
Public Function FindFolderIdByFullName (
    folderFullName As String
) As FolderId

Parameters

folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.

Return Value

Type: FolderId
The FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

Key difference of this method from DownloadFolderByFullName(String) is that it returns just ID. This means that MailBee requests less info from the server making this method a bit more efficient. However, if you need the detailed info about the folder (e.g. message count, unseen count, etc), use DownloadFolderByFullName(String) instead.

Note Note
Scanning the entire folder tree is an expensive operation. If your Exchange account has thousands of folders, consider optimizations like those provided by FindFolderIdByFullName(FolderId, string) or FindFolderIdByFullName(string, int) overloads.
Note Note
This method is not implemented in .NET Core. Use FindFolderIdByFullNameAsync(String) instead.
See Also

Reference

Ews Class
FindFolderIdByFullName Overload
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullName Method (FolderId, String)

EwsFindFolderIdByFullName Method (FolderId, String)
Gets the ID of the given folder in the specified containing folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderId FindFolderIdByFullName(
    FolderId containingFolderId,
    string folderFullName
)
Public Function FindFolderIdByFullName (
    containingFolderId As FolderId,
    folderFullName As String
) As FolderId

Parameters

containingFolderId
Type: FolderId
The ID of the containing folder where to search for the given folder. If a null reference (Nothing in Visual Basic), RootFolderType will be assumed.
folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.

Return Value

Type: FolderId
The FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

containingFolderId is just for optimization so you can leave it a null reference. However, if you already know that the folder you're looking for is contained in some upper level folder, you can specify it there. This will optimize performance as only a subset of all folders in the account will be searched. If you don't know the containing folder, you can use another optimization provided by FindFolderIdByFullName(string, int) overload.

containingFolderId does not need to be the immediate parent of the folder you're looking for, it can be any level up (e.g. you can specify WellKnownFolderName.Inbox while searching for "Inbox/Nested folder/Deeply nested folder"). Still, more close containingFolderId's level is to folderFullName's level - faster the search will be.

Key difference of this method from DownloadFolderByFullName(FolderId, String) is that it returns just ID. This means that MailBee requests less info from the server making this method a bit more efficient. However, if you need the detailed info about the folder (e.g. message count, unseen count, etc), use DownloadFolderByFullName(FolderId, String) instead.

Note Note
This method is not implemented in .NET Core. Use FindFolderIdByFullNameAsync(FolderId, String) instead.
See Also

Reference

Ews Class
FindFolderIdByFullName Overload
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullName Method (String, Int32)

EwsFindFolderIdByFullName Method (String, Int32)
Gets the ID of the given folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderId FindFolderIdByFullName(
    string folderFullName,
    int recursionLevel
)
Public Function FindFolderIdByFullName (
    folderFullName As String,
    recursionLevel As Integer
) As FolderId

Parameters

folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.
recursionLevel
Type: SystemInt32
Specifies how many levels of folder hierarchy to scan in shallow mode before switching to deep traversal mode. If 0, the entire account will be searched in a single operation (deep traversal). Higher values increase the number of search queries to the server but make each query more lightweight. Negative values not allowed.

Return Value

Type: FolderId
The FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

Key difference of this method from DownloadFolderByFullName(String, Int32) is that it returns just ID. This means that MailBee requests less info from the server making this method a bit more efficient. However, if you need the detailed info about the folder (e.g. message count, unseen count, etc), use DownloadFolderByFullName(String, Int32) instead.

Note Note
This overload exists only for optimization purposes when dealing with very complex and deeply nested folder hierarchies in Exchange accounts. DownloadFolderByFullName(String, Int32) topic provides more details on recursionLevel and how it can help improve performance.
Note Note
This method is not implemented in .NET Core. Use FindFolderIdByFullNameAsync(String, Int32) instead.
See Also

Reference

Ews Class
FindFolderIdByFullName Overload
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullNameAsync Method

EwsFindFolderIdByFullNameAsync Method
Overload List
 | Name | Description
Public method | FindFolderIdByFullNameAsync(String) | Async/await version of FindFolderIdByFullName(String).
Public method | FindFolderIdByFullNameAsync(FolderId, String) | Async/await version of FindFolderIdByFullName(FolderId, String).
Public method | FindFolderIdByFullNameAsync(String, Int32) | Async/await version of FindFolderIdByFullName(String, Int32).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullNameAsync Method (String)

EwsFindFolderIdByFullNameAsync Method (String)
Async/await version of FindFolderIdByFullName(String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderId> FindFolderIdByFullNameAsync(
    string folderFullName
)
Public Function FindFolderIdByFullNameAsync (
    folderFullName As String
) As Task(Of FolderId)

Parameters

folderFullName
Type: SystemString

Return Value

Type: Task FolderId
A task that represents the asynchronous operation. The value of TResult parameter points to FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use FindFolderIdByFullName(String) instead.
See Also

Reference

Ews Class
FindFolderIdByFullNameAsync Overload
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullNameAsync Method (FolderId, String)

EwsFindFolderIdByFullNameAsync Method (FolderId, String)
Async/await version of FindFolderIdByFullName(FolderId, String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderId> FindFolderIdByFullNameAsync(
    FolderId containingFolderId,
    string folderFullName
)
Public Function FindFolderIdByFullNameAsync (
    containingFolderId As FolderId,
    folderFullName As String
) As Task(Of FolderId)

Parameters

containingFolderId
Type: FolderId
folderFullName
Type: SystemString

Return Value

Type: Task FolderId
A task that represents the asynchronous operation. The value of TResult parameter points to FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use FindFolderIdByFullName(FolderId, String) instead.
See Also

Reference

Ews Class
FindFolderIdByFullNameAsync Overload
MailBee.EwsMail Namespace


Ews.FindFolderIdByFullNameAsync Method (String, Int32)

EwsFindFolderIdByFullNameAsync Method (String, Int32)
Async/await version of FindFolderIdByFullName(String, Int32).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderId> FindFolderIdByFullNameAsync(
    string folderFullName,
    int recursionLevel
)
Public Function FindFolderIdByFullNameAsync (
    folderFullName As String,
    recursionLevel As Integer
) As Task(Of FolderId)

Parameters

folderFullName
Type: SystemString
recursionLevel
Type: SystemInt32

Return Value

Type: Task FolderId
A task that represents the asynchronous operation. The value of TResult parameter points to FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use FindFolderIdByFullName(String, Int32) instead.
See Also

Reference

Ews Class
FindFolderIdByFullNameAsync Overload
MailBee.EwsMail Namespace


Ews.FindFolderIdByShortName Method

EwsFindFolderIdByShortName Method
Gets the ID of the given folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderId FindFolderIdByShortName(
    FolderId parentFolderId,
    string folderName
)
Public Function FindFolderIdByShortName (
    parentFolderId As FolderId,
    folderName As String
) As FolderId

Parameters

parentFolderId
Type: FolderId
The ID of the parent folder where to search for the given folder. If a null reference (Nothing in Visual Basic), RootFolderType will be assumed.
folderName
Type: SystemString
The folder name. Null reference or empty string not allowed.

Return Value

Type: FolderId
The FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

parentFolderId must be the immediate parent of folderName folder. Also, folderName must be a short name (not a full name with nested folder names in it).

Key difference of this method from DownloadFolderByShortName(FolderId, String) is that it returns just ID. This means that MailBee requests less info from the server making this method a bit more efficient. However, if you need the detailed info about the folder (e.g. message count, unseen count, etc), use DownloadFolderByShortName(FolderId, String) instead.

Note Note
This method is not implemented in .NET Core. Use FindFolderIdByShortNameAsync(FolderId, String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FindFolderIdByShortNameAsync Method

EwsFindFolderIdByShortNameAsync Method
Async/await version of FindFolderIdByShortName(FolderId, String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderId> FindFolderIdByShortNameAsync(
    FolderId parentFolderId,
    string folderName
)
Public Function FindFolderIdByShortNameAsync (
    parentFolderId As FolderId,
    folderName As String
) As Task(Of FolderId)

Parameters

parentFolderId
Type: FolderId
folderName
Type: SystemString

Return Value

Type: Task FolderId
A task that represents the asynchronous operation. The value of TResult parameter points to FolderId object if the folder exists; otherwise, a null reference (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use FindFolderIdByShortName(FolderId, String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FolderExists Method

EwsFolderExists Method
Overload List
 | Name | Description
Public method | FolderExists(String) | Checks if the folder with the specified full name exists in the MS Exchange account.
Public method | FolderExists(FolderId, String) | Checks if the given folder in the specified containing folder exists in the MS Exchange account.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FolderExists Method (String)

EwsFolderExists Method (String)
Checks if the folder with the specified full name exists in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool FolderExists(
    string folderFullName
)
Public Function FolderExists (
    folderFullName As String
) As Boolean

Parameters

folderFullName
Type: SystemString
The full folder name, such as "Inbox/Nested folder/Deeply nested folder". Null reference (Nothing in Visual Basic) or empty string not allowed.

Return Value

Type: Boolean
true if the folder exists; otherwise, false (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

Note Note
Scanning the entire folder tree is an expensive operation. If your Exchange account has thousands of folders, consider optimizations like those provided by DownloadFolderByFullName(FolderId, String) method.
Note Note
This method is not implemented in .NET Core. Use FolderExistsAsync(String) instead.
See Also

Reference

Ews Class
FolderExists Overload
MailBee.EwsMail Namespace


Ews.FolderExists Method (FolderId, String)

EwsFolderExists Method (FolderId, String)
Checks if the given folder in the specified containing folder exists in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool FolderExists(
    FolderId parentFolderId,
    string folderName
)
Public Function FolderExists (
    parentFolderId As FolderId,
    folderName As String
) As Boolean

Parameters

parentFolderId
Type: FolderId
The ID of the parent folder where to search for the given folder. If a null reference (Nothing in Visual Basic), RootFolderType will be assumed.
folderName
Type: SystemString
The folder name. Null reference or empty string not allowed.

Return Value

Type: Boolean
true if the folder exists; otherwise, false (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

parentFolderId must be the immediate parent of folderName folder. Also, folderName must be a short name (not a full name with nested folder names in it). You can use FolderExists(string) overload to search for a folder by its full name.

To get the folder itself (not just the fact whether it exists or not), use DownloadFolderByShortName(FolderId, String) method.

Note Note
This method is not implemented in .NET Core. Use FolderExistsAsync(FolderId, String) instead.
See Also

Reference

Ews Class
FolderExists Overload
MailBee.EwsMail Namespace


Ews.FolderExistsAsync Method

EwsFolderExistsAsync Method
Overload List
 | Name | Description
Public method | FolderExistsAsync(String) | Async/await version of [!:FolderExists(FolderId)].
Public method | FolderExistsAsync(FolderId, String) | Async/await version of FolderExists(FolderId, String).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FolderExistsAsync Method (String)

EwsFolderExistsAsync Method (String)
Async/await version of [!:FolderExists(FolderId)].

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> FolderExistsAsync(
    string folderFullName
)
Public Function FolderExistsAsync (
    folderFullName As String
) As Task(Of Boolean)

Parameters

folderFullName
Type: SystemString

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the folder exists; otherwise, false (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use FolderExists(String) instead.
See Also

Reference

Ews Class
FolderExistsAsync Overload
MailBee.EwsMail Namespace


Ews.FolderExistsAsync Method (FolderId, String)

EwsFolderExistsAsync Method (FolderId, String)
Async/await version of FolderExists(FolderId, String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> FolderExistsAsync(
    FolderId parentFolderId,
    string folderName
)
Public Function FolderExistsAsync (
    parentFolderId As FolderId,
    folderName As String
) As Task(Of Boolean)

Parameters

parentFolderId
Type: FolderId
folderName
Type: SystemString

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the folder exists; otherwise, false (or if an error occurred and ThrowExceptions is false).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use FolderExists(FolderId, String) instead.
See Also

Reference

Ews Class
FolderExistsAsync Overload
MailBee.EwsMail Namespace


Ews.GetErrorDescription Method

EwsGetErrorDescription Method
Returns a textual description of the last occurred error.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetErrorDescription()
Public Function GetErrorDescription As String

Return Value

Type: String
A string value containing a textual description of the last occurred error.
Remarks
Error descriptions can be localized or edited by deriving from Resources class.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.GetExchangeVersionString Method

EwsGetExchangeVersionString Method
Gets the MS Exchange version as a string.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetExchangeVersionString()
Public Function GetExchangeVersionString As String

Return Value

Type: String
The MS Exchange version if at least EWS API request has been completed using this Ews instance; otherwise, or a null reference (Nothing in Visual Basic).
Remarks

You need to do any action which causes the request to be sent to the MS Exchange server to have this property set. For instance, TestConnection.

The example of the returned value: "Exchange2010_SP1".

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.GetFolderByName Method

EwsGetFolderByName Method
Finds the EwsFolder in the given list by the folder's full name.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsFolder GetFolderByName(
    string folderFullName,
    List<EwsFolder> folders
)
Public Function GetFolderByName (
    folderFullName As String,
    folders As List(Of EwsFolder)
) As EwsFolder

Parameters

folderFullName
Type: SystemString
The full folder name.
folders
Type: System.Collections.GenericList EwsFolder
The list of folders to search.

Return Value

Type: EwsFolder
The reference to the EwsFolder object denoted by the given folder's full name, or a null reference if there is no such folder in the provided list.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | folderFullName or folders a null reference (Nothing in Visual Basic).
Remarks

This method does not send anything to the MS Exchange server, neiter it does any I/O at all (therefore it doesn't have an async version). It just performs search over the provided collection. To get the list of folders which you can then supply to this method, you can use DownloadFolders(Boolean) method.

To delimit levels of hierarchy in the folder name, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

Note Note
Although you could always call a method like DownloadFolderByFullName(String) to find folders, it may not be effective if you need to make multiple folder search queries. If (instead of making a network query each time) you download folders only once and then access the cached list with GetFolderByName(String, ListEwsFolder) method, you'll achieve better performance.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.GetFolderView Method

EwsGetFolderView Method
Gets FolderView instance tuned for listing all the folders in the account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderView GetFolderView(
    bool includeSubfolders
)
Public Function GetFolderView (
    includeSubfolders As Boolean
) As FolderView

Parameters

includeSubfolders
Type: SystemBoolean
If true, subfolders will also be requested; otherwise, only current level folders will be requested.

Return Value

Type: FolderView
A FolderView instance you can then pass to DownloadFolders(FolderId, FolderView, SearchFilter, bool) method which actually downloads the requested folder list.
Remarks
Although you can construct FolderView objects manually, you can also use this helper method for this. Or, you can use DownloadFolders(FolderId, bool, bool) overload which does not require FolderView object at all.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace
EwsDownloadFolders(FolderId, FolderView, SearchFilter, Boolean)


Ews.InitEwsClient Method

EwsInitEwsClient Method
Overload List
 | Name | Description
Public method | InitEwsClient | Sets the default MS Exchange version.
Public method | InitEwsClient(ExchangeVersion) | Sets the specific MS Exchange version.
Public method | InitEwsClient(ExchangeVersion, TimeZoneInfo) | Sets the specific MS Exchange version.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.InitEwsClient Method

EwsInitEwsClient Method
Sets the default MS Exchange version.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void InitEwsClient()
Public Sub InitEwsClient
Remarks
Before using any EWS methods, you must set the minimum featureset you expect the MS Exchange server to support. This overloads sets Exchange2007_SP1 featureset (the first version to support EWS). If you need advanced functions which have been added later, use InitEwsClient(ExchangeVersion) overload.
See Also

Reference

Ews Class
InitEwsClient Overload
MailBee.EwsMail Namespace


Ews.InitEwsClient Method (ExchangeVersion)

EwsInitEwsClient Method (ExchangeVersion)
Sets the specific MS Exchange version.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void InitEwsClient(
    ExchangeVersion version
)
Public Sub InitEwsClient (
    version As ExchangeVersion
)

Parameters

version
Type: ExchangeVersion
MS Exchange featureset you expect the server to support.
Remarks

Before using any EWS methods, you must set the minimum featureset you expect the MS Exchange server to support.

Some functions (for instance, searching folders) are supported in newest versions of MS Exchange only. You need to let the server know that you want to use the featureset of newer MS Exchange versions using this method.

This method itself does not verify the MS Exchange server version. It just initializes Ews component in the way that any further requests to the server will expect that its version is not lower than the specified one.

See Also

Reference

Ews Class
InitEwsClient Overload
MailBee.EwsMail Namespace


Ews.InitEwsClient Method (ExchangeVersion, TimeZoneInfo)

EwsInitEwsClient Method (ExchangeVersion, TimeZoneInfo)
Sets the specific MS Exchange version.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void InitEwsClient(
    ExchangeVersion version,
    TimeZoneInfo timeZone
)
Public Sub InitEwsClient (
    version As ExchangeVersion,
    timeZone As TimeZoneInfo
)

Parameters

version
Type: ExchangeVersion
MS Exchange featureset you expect the server to support.
timeZone
Type: SystemTimeZoneInfo
The timezone to be used for all datetime calculations.
Remarks

Before using any EWS methods, you must set the minimum featureset you expect the MS Exchange server to support.

Some functions (for instance, searching folders) are supported in newest versions of MS Exchange only. You need to let the server know that you want to use the featureset of newer MS Exchange versions using this method.

This method itself does not verify the MS Exchange server version. It just initializes Ews component in the way that any further requests to the server will expect that its version is not lower than the specified one.

This overload also lets you redefine the timezone to use if your desired timezone is not local for this computer.

See Also

Reference

Ews Class
InitEwsClient Overload
MailBee.EwsMail Namespace


Ews.MoveFolder Method

EwsMoveFolder Method
Moves a folder into another folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MoveFolder(
    FolderId id,
    FolderId destinationFolderId
)
Public Function MoveFolder (
    id As FolderId,
    destinationFolderId As FolderId
) As Boolean

Parameters

id
Type: FolderId
The ID of the folder to move. Null reference (Nothing in Visual Basic) not allowed.
destinationFolderId
Type: FolderId
The ID of the parent destination folder. Null reference not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
You can use RenameOrMoveFolder(String, String, ListEwsFolder) method to move a folder by its full name.
Note Note
This method is not implemented in .NET Core. Use MoveFolderAsync(FolderId, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.MoveFolderAsync Method

EwsMoveFolderAsync Method
Async/await version of MoveFolder(FolderId, FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> MoveFolderAsync(
    FolderId id,
    FolderId destinationFolderId
)
Public Function MoveFolderAsync (
    id As FolderId,
    destinationFolderId As FolderId
) As Task(Of Boolean)

Parameters

id
Type: FolderId
destinationFolderId
Type: FolderId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use MoveFolder(FolderId, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.MoveItem Method

EwsMoveItem Method
Moves the specified item (e.g. mail message) into the specified folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ItemId MoveItem(
    ItemId movedItemId,
    FolderId targetFolderId
)
Public Function MoveItem (
    movedItemId As ItemId,
    targetFolderId As FolderId
) As ItemId

Parameters

movedItemId
Type: ItemId
The ID of the item to move. Null reference (Nothing in Visual Basic) not allowed.
targetFolderId
Type: FolderId
The ID of the folder where to copy the message. Null reference not allowed.

Return Value

Type: ItemId
ID of the new item if succeeded; otherwise, a null reference.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use MoveItemAsync(ItemId, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.MoveItemAsync Method

EwsMoveItemAsync Method
Async/await version of MoveItem(ItemId, FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<ItemId> MoveItemAsync(
    ItemId movedItemId,
    FolderId targetFolderId
)
Public Function MoveItemAsync (
    movedItemId As ItemId,
    targetFolderId As FolderId
) As Task(Of ItemId)

Parameters

movedItemId
Type: ItemId
targetFolderId
Type: FolderId

Return Value

Type: Task ItemId
A task that represents the asynchronous operation. The value of TResult parameter points to the ID of the new item if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use MoveItem(ItemId, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.OnErrorOccurred Method

EwsOnErrorOccurred Method
Used by MailBee to raise ErrorOccurred event.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnErrorOccurred(
    ErrorEventArgs args
)
Protected Sub OnErrorOccurred (
    args As ErrorEventArgs
)

Parameters

args
Type: MailBeeErrorEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace
EwsErrorOccurred


Ews.OnLogNewEntry Method

EwsOnLogNewEntry Method
Used by MailBee to raise LogNewEntry event.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLogNewEntry(
    LogNewEntryEventArgs args
)
Protected Sub OnLogNewEntry (
    args As LogNewEntryEventArgs
)

Parameters

args
Type: MailBeeLogNewEntryEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace
EwsLogNewEntry


Ews.RenameFolder Method

EwsRenameFolder Method
Renames a folder in the MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RenameFolder(
    string folderNewName,
    FolderId id
)
Public Function RenameFolder (
    folderNewName As String,
    id As FolderId
) As Boolean

Parameters

folderNewName
Type: SystemString
The new name of the folder. Null reference (Nothing in Visual Basic) or empty string not allowed.
id
Type: FolderId
The ID of the folder being renamed. Null reference not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

folderNewName must be a short name (not a full name with nested folder names in it). You can use RenameOrMoveFolder(String, String, ListEwsFolder) method to rename a folder by its full name.

Note Note
This method is not implemented in .NET Core. Use RenameFolderAsync(String, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.RenameFolderAsync Method

EwsRenameFolderAsync Method
Async/await version of RenameFolder(String, FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> RenameFolderAsync(
    string folderNewName,
    FolderId id
)
Public Function RenameFolderAsync (
    folderNewName As String,
    id As FolderId
) As Task(Of Boolean)

Parameters

folderNewName
Type: SystemString
id
Type: FolderId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use RenameFolder(String, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.RenameOrMoveFolder Method

EwsRenameOrMoveFolder Method
Renames or moves a folder denoted by its full name rather than by ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RenameOrMoveFolder(
    string folderOldFullName,
    string folderNewFullName,
    List<EwsFolder> allFolders
)
Public Function RenameOrMoveFolder (
    folderOldFullName As String,
    folderNewFullName As String,
    allFolders As List(Of EwsFolder)
) As Boolean

Parameters

folderOldFullName
Type: SystemString
The full name of the folder to rename or move. Null reference (Nothing in Visual Basic) or empty string not allowed.
folderNewFullName
Type: SystemString
The full name the folder should get upon moving/renaming. Null reference or empty string not allowed.
allFolders
Type: System.Collections.GenericList EwsFolder
The list of all folders in the account. You can leave it a null reference but MailBee will have to make a few additional network queries to locate the given folders in the Exchange account.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | folderOldFullName denotes non-existing folder or folderNewFullName denotes the path with non-existing parent folder or folderNewFullName folder already exists and ThrowExceptions is true.
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To delimit levels of hierarchy in folder names, use the same character which is set by FolderLevelDelimiter property. By default, it's '/' (forward slash).

allFolders parameter serves optimization purpose only. EWS does not support working with full folder names so MailBee emulates this by finding folders in the MS Exchange account. So, when you need to do something with a folder denoted by its full name, MailBee needs the list of all the folders where it can find the actual item. Usually, you can let MailBee find the folders needed (if allFolders is not set). In advanced cases (if you want to optimize performance) you can supply the list of folders yourself (for instance, you may get it with DownloadFolders(Boolean) method). In this case, allFolders list must include all the folders in the account. Otherwise, you may get MailBeeInvalidArgumentException.

Also, folderNewFullName must denote a folder within an existing parent folder (or in the account root). This method cannot create multiple levels of folder hierarchy at once. I.e. EWS will fail if you specified folderNewFullName as "A/B/C" but there is no "A/B" folder already in the account. First, you need to create "A" and then "A/B".

Note Note
This method is not implemented in .NET Core. Use RenameOrMoveFolderAsync(String, String, ListEwsFolder) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.RenameOrMoveFolderAsync Method

EwsRenameOrMoveFolderAsync Method
Async/await version of RenameOrMoveFolder(String, String, ListEwsFolder).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> RenameOrMoveFolderAsync(
    string folderOldFullName,
    string folderNewFullName,
    List<EwsFolder> allFolders
)
Public Function RenameOrMoveFolderAsync (
    folderOldFullName As String,
    folderNewFullName As String,
    allFolders As List(Of EwsFolder)
) As Task(Of Boolean)

Parameters

folderOldFullName
Type: SystemString
folderNewFullName
Type: SystemString
allFolders
Type: System.Collections.GenericList EwsFolder

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use RenameOrMoveFolder(String, String, ListEwsFolder) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.ResolveName Method

EwsResolveName Method
Resolves the specified name into e-mail addresses which exist on the given MS Exchange server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ResolveName(
    string name
)
Public Function ResolveName (
    name As String
) As EmailAddressCollection

Parameters

name
Type: SystemString
The display name of an account to resolve. Null reference (Nothing in Visual Basic) or empty string not allowed.

Return Value

Type: EmailAddressCollection
On succeess, the collection of MailBee's EmailAddress objects representing e-mail addresses which correspond to the specified name; otherwise, a null reference.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use ResolveNameAsync(String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.ResolveNameAsync Method

EwsResolveNameAsync Method
Async/await version of ResolveName(String).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EmailAddressCollection> ResolveNameAsync(
    string name
)
Public Function ResolveNameAsync (
    name As String
) As Task(Of EmailAddressCollection)

Parameters

name
Type: SystemString

Return Value

Type: Task EmailAddressCollection
A task that represents the asynchronous operation. The value of TResult parameter points to the collection of MailBee's EmailAddress objects representing e-mail addresses which correspond to the specified name if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use ResolveName(String) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Search Method

EwsSearch Method
Searches the specified folder for items matching the given criteria.
Overload List
 | Name | Description
Public method | Search(FolderId, SearchFilter) | Searches the specified folder for items matching the given criteria.
Public method | Search(FolderId, SearchFilter, ItemView) | Searches the specified folder for items matching the given criteria and delivers the results accordingly the specified ItemView.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Search Method (FolderId, SearchFilter)

EwsSearch Method (FolderId, SearchFilter)
Searches the specified folder for items matching the given criteria.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList Search(
    FolderId id,
    SearchFilter filter
)
Public Function Search (
    id As FolderId,
    filter As SearchFilter
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder where to perform search. Null reference (Nothing in Visual Basic) not allowed.
filter
Type: SearchFilter
The EWS Managed API filter. If a null reference, no filter is applied and all the items are returned.

Return Value

Type: EwsItemList
If succeeded, the list of items which passed the specified criteria; otherwise, a null reference.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
EwsItem objects in the returned list have only Id and UniqueId properties set. To get the actual items, you'll need to download them separately, such as with DownloadItems(IEnumerableEwsItem, EwsItemParts) method.
Note Note
This method requires MS Exchange 2010 at least (and EWS client must be initialized with InitEwsClient(ExchangeVersion) not less than ExchangeVersion.Exchange2010).
Note Note
This method is not implemented in .NET Core. Use SearchAsync(FolderId, SearchFilter) instead.
See Also

Reference

Ews Class
Search Overload
MailBee.EwsMail Namespace


Ews.Search Method (FolderId, SearchFilter, ItemView)

EwsSearch Method (FolderId, SearchFilter, ItemView)
Searches the specified folder for items matching the given criteria and delivers the results accordingly the specified ItemView.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItemList Search(
    FolderId id,
    SearchFilter filter,
    ItemView view
)
Public Function Search (
    id As FolderId,
    filter As SearchFilter,
    view As ItemView
) As EwsItemList

Parameters

id
Type: FolderId
The ID of the folder where to perform search. Null reference (Nothing in Visual Basic) not allowed.
filter
Type: SearchFilter
The EWS Managed API filter. If a null reference, no filter is applied and all the items are returned (unless view setting limits the output).
view
Type: ItemView
The settings which specify how many items to return, offset, ordering, which message properties to download. If a null reference, all the items passed through the filter are returned.

Return Value

Type: EwsItemList
If succeeded, the list of items which passed the specified criteria; otherwise, a null reference.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

EwsItem objects in the returned list have only Id and UniqueId properties set. To get the actual items, you'll need to download them separately, such as with DownloadItems(IEnumerableEwsItem, EwsItemParts) method.

Alternatively, you can specify PropertySet property in view object (for instance, add more properties to be requested from the Exchange server). This will make this method an alternative to DownloadItems(FolderId, ItemView, Boolean, PropertySet) method and its overloads. The current method, however, performs only a single query to the Exchange server while DownloadItems(FolderId, ItemView, Boolean, PropertySet) makes two. The current method is faster but not any property can be requested within a single call. For instance, finding and downloading messages with message bodies requires two queries (so that DownloadItems(FolderId, ItemView, Boolean, PropertySet) method must be used).

Note Note
This method requires MS Exchange 2010 at least (and EWS client must be initialized with InitEwsClient(ExchangeVersion) not less than ExchangeVersion.Exchange2010).
Note Note
This method is not implemented in .NET Core. Use SearchAsync(FolderId, SearchFilter, ItemView) instead.
See Also

Reference

Ews Class
Search Overload
MailBee.EwsMail Namespace


Ews.SearchAsync Method

EwsSearchAsync Method
Overload List
 | Name | Description
Public method | SearchAsync(FolderId, SearchFilter) | Async/await version of Search(FolderId, SearchFilter).
Public method | SearchAsync(FolderId, SearchFilter, ItemView) | Async/await version of Search(FolderId, SearchFilter, ItemView).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.SearchAsync Method (FolderId, SearchFilter)

EwsSearchAsync Method (FolderId, SearchFilter)
Async/await version of Search(FolderId, SearchFilter).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> SearchAsync(
    FolderId id,
    SearchFilter filter
)
Public Function SearchAsync (
    id As FolderId,
    filter As SearchFilter
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
filter
Type: SearchFilter

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to the list of items which passed the specified criteria if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use Search(FolderId, SearchFilter) instead.
See Also

Reference

Ews Class
SearchAsync Overload
MailBee.EwsMail Namespace


Ews.SearchAsync Method (FolderId, SearchFilter, ItemView)

EwsSearchAsync Method (FolderId, SearchFilter, ItemView)
Async/await version of Search(FolderId, SearchFilter, ItemView).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EwsItemList> SearchAsync(
    FolderId id,
    SearchFilter filter,
    ItemView view
)
Public Function SearchAsync (
    id As FolderId,
    filter As SearchFilter,
    view As ItemView
) As Task(Of EwsItemList)

Parameters

id
Type: FolderId
filter
Type: SearchFilter
view
Type: ItemView

Return Value

Type: Task EwsItemList
A task that represents the asynchronous operation. The value of TResult parameter points to the list of items which passed the specified criteria if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use Search(FolderId, SearchFilter, ItemView) instead.
See Also

Reference

Ews Class
SearchAsync Overload
MailBee.EwsMail Namespace


Ews.SendMessage Method

EwsSendMessage Method
Sends MailBee mail message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SendMessage(
    MailMessage msg
)
Public Function SendMessage (
    msg As MailMessage
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
The MailBee mail message to send. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use SendMessageAsync(MailMessage) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.SendMessageAndSaveCopy Method

EwsSendMessageAndSaveCopy Method
Sends MailBee mail message and saves a copy in Sent Items or user-defined folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SendMessageAndSaveCopy(
    MailMessage msg,
    FolderId sentMessagesFolderId
)
Public Function SendMessageAndSaveCopy (
    msg As MailMessage,
    sentMessagesFolderId As FolderId
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
The MailBee mail message to send. Null reference (Nothing in Visual Basic) not allowed.
sentMessagesFolderId
Type: FolderId
The ID of the folder where to save the copy, or a null reference to save into the folder assigned as Sent Items for the current account.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use SendMessageAndSaveCopyAsync(MailMessage, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.SendMessageAndSaveCopyAsync Method

EwsSendMessageAndSaveCopyAsync Method
Async/await version of SendMessageAndSaveCopy(MailMessage, FolderId).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendMessageAndSaveCopyAsync(
    MailMessage msg,
    FolderId sentMessagesFolderId
)
Public Function SendMessageAndSaveCopyAsync (
    msg As MailMessage,
    sentMessagesFolderId As FolderId
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
sentMessagesFolderId
Type: FolderId

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use SendMessageAndSaveCopy(MailMessage, FolderId) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.SendMessageAsync Method

EwsSendMessageAsync Method
Async/await version of SendMessage(MailMessage).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendMessageAsync(
    MailMessage msg
)
Public Function SendMessageAsync (
    msg As MailMessage
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use SendMessage(MailMessage) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.SetCredentials Method

EwsSetCredentials Method
Overload List
 | Name | Description
Public method | SetCredentials(ExchangeCredentials) | Sets the credentials (e.g. OAuth2) of the MS Exchange account for subsequent operations.
Public method | SetCredentials(String, String) | Sets the login and password of the MS Exchange account for subsequent operations.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.SetCredentials Method (ExchangeCredentials)

EwsSetCredentials Method (ExchangeCredentials)
Sets the credentials (e.g. OAuth2) of the MS Exchange account for subsequent operations.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetCredentials(
    ExchangeCredentials creds
)
Public Sub SetCredentials (
    creds As ExchangeCredentials
)

Parameters

creds
Type: ExchangeCredentials
The credentials that are used to authenticate with EWS.
Remarks

This overload lets the developer use other authentication methods than login/password. For instance, OAuthCredentials for OAuth2 authentication.

See Authenticate an EWS application by using OAuth on how to get OAuthCredentials with Managed EWS API.

See Also

Reference

Ews Class
SetCredentials Overload
MailBee.EwsMail Namespace


Ews.SetCredentials Method (String, String)

EwsSetCredentials Method (String, String)
Sets the login and password of the MS Exchange account for subsequent operations.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetCredentials(
    string accountName,
    string password
)
Public Sub SetCredentials (
    accountName As String,
    password As String
)

Parameters

accountName
Type: SystemString
The account name or a null reference (Nothing in Visual Basic) in case if Integrated Windows Authentication must be used.
password
Type: SystemString
The account password or a null reference in case if Integrated Windows Authentication must be used.
Remarks
If you want to use OAuth2 authentication, use SetCredentials(ExchangeCredentials) overload.
See Also

Reference

Ews Class
SetCredentials Overload
MailBee.EwsMail Namespace


Ews.SetServerUrl Method

EwsSetServerUrl Method
Gets or sets the URL of EWS service on MS Exchange server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetServerUrl(
    string url
)
Public Sub SetServerUrl (
    url As String
)

Parameters

url
Type: SystemString
The EWS URL.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | url is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
Using Autodiscover(String) is the preferred way of obtaining EWS URL but it requires that Autodiscover is correctly set up on the server (it's not always so). Also, Autodiscover can be slow. If this is a concern for you, you can set this URL directly. Typically, it's something like "https://server.com/EWS/Exchange.asmx".
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.TestConnection Method

EwsTestConnection Method
Makes a test connection to validate the current settings.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool TestConnection()
Public Function TestConnection As Boolean

Return Value

Type: Boolean
true if the test connection succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
You can use this method if you need to check if the server URL (or Autodiscover settings), login and password are correct.
Note Note
This method is not implemented in .NET Core. Use TestConnectionAsync instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.TestConnectionAsync Method

EwsTestConnectionAsync Method
Async/await version of TestConnection.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> TestConnectionAsync()
Public Function TestConnectionAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use TestConnection instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.UpdateItem Method

EwsUpdateItem Method
Writes the changes made to the item to the MS Exchange server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UpdateItem(
    EwsItem item
)
Public Function UpdateItem (
    item As EwsItem
) As Boolean

Parameters

item
Type: MailBee.EwsMailEwsItem
The item (e.g. mail message) to update. Null reference (Nothing in Visual Basic) not allowed.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use UpdateItemAsync(EwsItem) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.UpdateItemAsync Method

EwsUpdateItemAsync Method
Async/await version of UpdateItem(EwsItem).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UpdateItemAsync(
    EwsItem item
)
Public Function UpdateItemAsync (
    item As EwsItem
) As Task(Of Boolean)

Parameters

item
Type: MailBee.EwsMailEwsItem

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use UpdateItem(EwsItem) instead.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.UploadMessage Method

EwsUploadMessage Method
Uploads a message into a folder on the MS Exchange server.
Overload List
 | Name | Description
Public method | UploadMessage(FolderId, MailMessage, Boolean) | Uploads MailBee's MailMessage into the specified folder on the MS Exchange server.
Public method | UploadMessage(FolderId, Byte, Boolean) | Uploads raw message data into the specified folder on the MS Exchange server.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.UploadMessage Method (FolderId, MailMessage, Boolean)

EwsUploadMessage Method (FolderId, MailMessage, Boolean)
Uploads MailBee's MailMessage into the specified folder on the MS Exchange server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    FolderId id,
    MailMessage msg,
    bool isDraft
)
Public Function UploadMessage (
    id As FolderId,
    msg As MailMessage,
    isDraft As Boolean
) As Boolean

Parameters

id
Type: FolderId
The ID of the folder where to upload the message. Null reference (Nothing in Visual Basic) not allowed.
msg
Type: MailBee.MimeMailMessage
The mail message to be uploaded. Null reference not allowed.
isDraft
Type: SystemBoolean
If true, the message will be uploaded as draft; otherwise, as normal message.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks

To specify the folder by its name, first get its ID with FindFolderIdByShortName(FolderId, String) or FindFolderIdByFullName(String) method.

Note Note
This method is not implemented in .NET Core. Use UploadMessageAsync(FolderId, MailMessage, Boolean) instead.
See Also

Reference

Ews Class
UploadMessage Overload
MailBee.EwsMail Namespace


Ews.UploadMessage Method (FolderId, Byte[], Boolean)

EwsUploadMessage Method (FolderId, Byte, Boolean)
Uploads raw message data into the specified folder on the MS Exchange server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    FolderId id,
    byte[] bytes,
    bool isDraft
)
Public Function UploadMessage (
    id As FolderId,
    bytes As Byte(),
    isDraft As Boolean
) As Boolean

Parameters

id
Type: FolderId
The ID of the folder where to upload the message. Null reference (Nothing in Visual Basic) not allowed.
bytes
Type: SystemByte
The raw bytes of the mail message to be uploaded. Null reference not allowed.
isDraft
Type: SystemBoolean
If true, the message will be uploaded as draft; otherwise, as normal message.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Core.
Remarks
Note Note
This method is not implemented in .NET Core. Use UploadMessageAsync(FolderId, Byte, Boolean) instead.
See Also

Reference

Ews Class
UploadMessage Overload
MailBee.EwsMail Namespace


Ews.UploadMessageAsync Method

EwsUploadMessageAsync Method
Overload List
 | Name | Description
Public method | UploadMessageAsync(FolderId, MailMessage, Boolean) | Async/await version of UploadMessage(FolderId, MailMessage, Boolean).
Public method | UploadMessageAsync(FolderId, Byte, Boolean) | Async/await version of UploadMessage(FolderId, Byte, Boolean).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.UploadMessageAsync Method (FolderId, MailMessage, Boolean)

EwsUploadMessageAsync Method (FolderId, MailMessage, Boolean)
Async/await version of UploadMessage(FolderId, MailMessage, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    FolderId id,
    MailMessage msg,
    bool isDraft
)
Public Function UploadMessageAsync (
    id As FolderId,
    msg As MailMessage,
    isDraft As Boolean
) As Task(Of Boolean)

Parameters

id
Type: FolderId
msg
Type: MailBee.MimeMailMessage
isDraft
Type: SystemBoolean

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use UploadMessage(FolderId, MailMessage, Boolean) instead.
See Also

Reference

Ews Class
UploadMessageAsync Overload
MailBee.EwsMail Namespace


Ews.UploadMessageAsync Method (FolderId, Byte[], Boolean)

EwsUploadMessageAsync Method (FolderId, Byte, Boolean)
Async/await version of UploadMessage(FolderId, Byte, Boolean).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    FolderId id,
    byte[] bytes,
    bool isDraft
)
Public Function UploadMessageAsync (
    id As FolderId,
    bytes As Byte(),
    isDraft As Boolean
) As Task(Of Boolean)

Parameters

id
Type: FolderId
bytes
Type: SystemByte
isDraft
Type: SystemBoolean

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
NotImplementedException | The .NET runtime is .NET Framework.
Remarks
Note Note
This method is not implemented in .NET Framework. Use UploadMessage(FolderId, Byte, Boolean) instead.
See Also

Reference

Ews Class
UploadMessageAsync Overload
MailBee.EwsMail Namespace


Ews Properties

Ews Properties

The Ews type exposes the following members.

Properties
 | Name | Description
Public property | CalculateFolderSizeOnDownload | Gets or sets if folder download operation must also calculate the folder size in bytes.
Public property | DefaultFolderClass | Gets or sets the default class string to assign to folders being created.
Public property | DeleteMethod | Gets or sets the mode of deleting items in EWS.
 | EnableCompatibilityMode | Gets or sets if MailBee should work around bugs of Microsoft.Exchange.WebServices.dll library.
 | EnableSslCertValidation | Gets or sets if SSL certificate of the server must be validated (in case of HTTPS connection).
Public property | FolderLevelDelimiter | Gets or sets which character to use when delimiting nested folder names.
Public property | LastResult | Gets a numeric code of the last error.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MessageFoldersFilter | Gets SearchFilter instance for reducing the list of the downloaded folders to mail-specific folders.
Public property | RequireHttps | Gets or sets if only HTTPS end points are allowed by auto-discover procedure.
Public property | RootFolderType | Gets or sets the top of folder hierarchy in an MS Exchange account.
Public property | Service | Gets a reference to the underlying ExchangeService object.
Public property | Site | Gets or sets the object to be used as a site for the component.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.CalculateFolderSizeOnDownload Property

EwsCalculateFolderSizeOnDownload Property
Gets or sets if folder download operation must also calculate the folder size in bytes.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool CalculateFolderSizeOnDownload { get; set; }
Public Property CalculateFolderSizeOnDownload As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, methods like DownloadFolders(Boolean), DownloadFolderByShortName(FolderId, String) or DownloadFolderByFullName(FolderId, String) will also set Size property in their results; otherwise, this property value will remain -1. The default is false.
Remarks
Calculating folder size is an expensive operation and therefore is not performed by default.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DefaultFolderClass Property

EwsDefaultFolderClass Property
Gets or sets the default class string to assign to folders being created.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DefaultFolderClass { get; set; }
Public Property DefaultFolderClass As String
    Get
    Set

Property Value

Type: String
The default class string. The default value is "IPF.Note".
Remarks

This property affects CreateFolder(String, FolderId) method. Usually, you don't need to change its value unless you need to create non-email folders.

It's allowed to assign value to a null reference (Nothing in Visual Basic) or an empty string. This will cause any folders being created to not have any FolderClass.

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.DeleteMethod Property

EwsDeleteMethod Property
Gets or sets the mode of deleting items in EWS.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeleteMode DeleteMethod { get; set; }
Public Property DeleteMethod As DeleteMode
    Get
    Set

Property Value

Type: DeleteMode
The mode of deleting items. The default value is HardDelete (unrecoverable deletion).
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.EnableCompatibilityMode Property

EwsEnableCompatibilityMode Property
Gets or sets if MailBee should work around bugs of Microsoft.Exchange.WebServices.dll library.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool EnableCompatibilityMode { get; set; }
Public Shared Property EnableCompatibilityMode As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will avoid using features which work incorrectly with the current version of EWS Managed API from Microsoft. If false, no feature limitation is performed. The default value is true.
Remarks
Currently, the only limitation controlled by this property concerns listing well-known folder names when downloading folder list. This functionality is available in Exchange 2013 and higher but the latest Microsoft.Exchange.WebServices.dll v2.2 still crashes when listing some folders.
Note Note
This property has no effect if InitEwsClient(ExchangeVersion) was called for Exchange version 2007 or 2010 (i.e. prior to 2013).
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.EnableSslCertValidation Property

EwsEnableSslCertValidation Property
Gets or sets if SSL certificate of the server must be validated (in case of HTTPS connection).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool EnableSslCertValidation { get; set; }
Public Shared Property EnableSslCertValidation As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the client will check if the SSL certificate presented by the server is valid. If false, no SSL certificate check is performed. The default is false.
Remarks
This property is static so it affects all instances of Ews class in case if you have many of them.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.FolderLevelDelimiter Property

EwsFolderLevelDelimiter Property
Gets or sets which character to use when delimiting nested folder names.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public char FolderLevelDelimiter { get; set; }
Public Property FolderLevelDelimiter As Char
    Get
    Set

Property Value

Type: Char
The default is '/' (forward slash).
Remarks
EWS itself rarely operates with full folder names so it's mainly MailBee-specific. MailBee will use this delimiter when returning full folder name such as with FullName property.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.LastResult Property

EwsLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Log Property

EwsLog Property
Gets the object used for logging MailBee activities into a file or memory buffer.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Logger Log { get; }
Public ReadOnly Property Log As Logger
    Get

Property Value

Type: Logger
A reference to the object used for logging MailBee activities into a file or memory buffer.
Remarks

Ews class has its own logging which you can configure using this property. It works all the same for all MailBee network components, see Imap.Log for examples.

However, as Ews class is just a wrapper for EWS Managed API library, most of activities take place in its code. To get more comprehensive logging (such as for debugging), you can also enable tracing of all network requests. This will let you see what's EWS Managed API layer is doing under the hood.

Examples
This is what you need to add into app.config or web.config to enable tracing of network requests into "network.log" file in the application folder. You can specify absolute path as well (just make sure your application is allowed to write into the specified location).
Copy
<system.diagnostics>
  <sources>
    <source name="System.Net" tracemode="protocolonly" maxdatasize="4096">
      <listeners>
        <add name="System.Net"/>
      </listeners>
    </source>
  </sources>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <add name="System.Net.Cache" value="Verbose"/>
    <add name="System.Net.Http" value="Verbose"/>
    <add name="System.Net.Sockets" value="Verbose"/>
    <add name="System.Net.WebSockets" value="Verbose"/>
  </switches>
  <sharedListeners>
    <add name="System.Net"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="network.log"
    />
  </sharedListeners>
  <trace autoflush="true"/>
</system.diagnostics>
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.MessageFoldersFilter Property

EwsMessageFoldersFilter Property
Gets SearchFilter instance for reducing the list of the downloaded folders to mail-specific folders.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SearchFilter MessageFoldersFilter { get; }
Public ReadOnly Property MessageFoldersFilter As SearchFilter
    Get

Property Value

Type: SearchFilter
The filter preconfigured to return only mail-specific folders when used with DownloadFolders(FolderId, FolderView, SearchFilter, bool) method.
Remarks

This is a helper property, you can construct SearchFilter objects manually if you need this.

MailBee considers a folder to be mail-specific is it has FolderClass equal to "IPF.Note" or does not have FolderClass at all. By default, DownloadFolders(bool) method and its overloads will list all the folders in the account. Using DownloadFolders(FolderId, FolderView, SearchFilter, bool) with SearchFilter set to MessageFoldersFilter lets you limit the output to mail-specific folders only.

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.RequireHttps Property

EwsRequireHttps Property
Gets or sets if only HTTPS end points are allowed by auto-discover procedure.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RequireHttps { get; set; }
Public Property RequireHttps As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, only HTTPS end points can be retrieved by auto-discover procedure. If false, both HTTP and HTTPS end points are permitted. The default is false.
Remarks
This value is only meaningful for auto-discovering the server host/port from the e-mail address (Autodiscover(String) method). It controls whether auto-discover procedure should discard HTTP-only host if there is no HTTPS host assigned as a EWS mail server for the given e-mail address. You can always connect to both HTTP and HTTPS if you manually specify the server host using SetServerUrl(String) method.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace
EwsAutodiscover(String)


Ews.RootFolderType Property

EwsRootFolderType Property
Gets or sets the top of folder hierarchy in an MS Exchange account.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public WellKnownFolderName RootFolderType { get; set; }
Public Property RootFolderType As WellKnownFolderName
    Get
    Set

Property Value

Type: WellKnownFolderName
The type of the folder to be referenced as a top of the hierarchy by MailBee methods which work with folders. The default is WellKnownFolderName.MsgFolderRoot.
Remarks
This property does not change anything in an MS Exchange account. It just lets you change the scope of methods which deal with folders. For instance, by default the scope is limited to folders which are specific to e-mails. For instance, you can change it to WellKnownFolderName.Root if you need to see all the folders in an account, even ones not related to e-mail.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Service Property

EwsService Property
Gets a reference to the underlying ExchangeService object.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ExchangeService Service { get; }
Public ReadOnly Property Service As ExchangeService
    Get

Property Value

Type: ExchangeService
A reference to the underlying ExchangeService object, or a null reference (Nothing in Visual Basic) if InitEwsClient hasn't been called yet.
Remarks
As Ews is just a wrapper around Managed EWS API, this property provides you with the access to that API. You can use it if you need any functionality not directly exposed by the wrapper.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Site Property

EwsSite Property
Gets or sets the object to be used as a site for the component.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual ISite Site { get; set; }
Public Overridable Property Site As ISite
    Get
    Set

Property Value

Type: ISite
A reference to the object to be used as a site for the component. The default value is a null reference (Nothing in Visual Basic).

Implements

IComponentSite
Remarks
The developer does not need to set this property. It's used by RAD tools such as form designers.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.ThrowExceptions Property

EwsThrowExceptions Property
Gets or sets whether the component will throw exceptions on errors.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the component methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult, GetErrorDescription members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee usage will still be thrown. Typical examples of such errors are: passing invalid arguments to methods, calling methods or settings properties in illegal state (for instance, an attempt to start an asynchronous method while another asynchronous method is not yet finished), etc. Such exceptions indicate programming errors in the application being developed, and thus cannot be suppressed.

ThrowExceptions property does not control whether to throw exceptions which occur due to logging errors (such as "log file cannot be written to", etc). To control whether logging exceptions should be thrown, the developer can use Log.DisableOnException property.

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.TrialDaysLeft Property

EwsTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value which contains the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Version Property

EwsVersion Property
Gets the version of the MailBee assembly.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews Events

Ews Events

The Ews type exposes the following members.

Events
 | Name | Description
Public event | Disposed | Occurs after the component was disposed.
Public event | ErrorOccurred | Occurs when the MailBeeException is thrown.
Public event | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Ews.Log.MemoryLog is true).
Top
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.Disposed Event

EwsDisposed Event
Occurs after the component was disposed.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event EventHandler Disposed
Public Event Disposed As EventHandler

Value

Type: SystemEventHandler

Implements

IComponentDisposed
See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.ErrorOccurred Event

EwsErrorOccurred Event
Occurs when the MailBeeException is thrown.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ErrorEventHandler ErrorOccurred
Public Event ErrorOccurred As ErrorEventHandler

Value

Type: MailBeeErrorEventHandler
Remarks

When MailBee encounters any error, it throws the MailBeeException. If ThrowExceptions is false, this even will be raised instead.

Usage pattern for this event is the same for all MailBee classes. Imap.ErrorOccurred provides typical example.

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


Ews.LogNewEntry Event

EwsLogNewEntry Event
Occurs when an entry is written into the log file (or into the memory buffer if Ews.Log.MemoryLog is true).

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LogNewEntryEventHandler LogNewEntry
Public Event LogNewEntry As LogNewEntryEventHandler

Value

Type: MailBeeLogNewEntryEventHandler
Remarks

This event is raised only if logging is turned on (Enabled is true).

MailBee raises this event BEFORE adding the entry into the the log. Since many properties of NewEntry object are editable, the developer can change the data MailBee will put into the log or even cancel logging the current entry at all. This may be useful the developer wishes to log only those entires which meet certain criteria.

Note Note
Entries added by the developer (through WriteLine(String) method call) do not cause this event to be raised. Thus, it's safe to add user-defined log entries even in the LogNewEntry event handler itself. This does not cause endless recursion which would otherwise occur if WriteLine(String) method called in LogNewEntry event handler raised this event again.

Usage pattern for this event is the same for all MailBee classes. Imap.LogNewEntry provides typical example.

See Also

Reference

Ews Class
MailBee.EwsMail Namespace


EwsFolder Class

EwsFolder Class
Represents a folder in Exchange account.
Inheritance Hierarchy
SystemObject
MailBee.EwsMailEwsFolder

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EwsFolder
Public Class EwsFolder

The EwsFolder type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | FullName | Gets the folder's full name.
Public property | Id | Gets the folder's ID object.
Public property | NativeFolder | Gets EWS Managed API object for this folder.
Public property | ShortName | Gets the folder's own name.
Public property | Size | Gets the total size of all items in the folder.
Public property | TotalCount | Gets the total number of all items in the folder.
Public property | UnreadCount | Gets the number of unread items in the folder.
Top
Remarks
This is a wrapper around EWS Folder class.
See Also

Reference

MailBee.EwsMail Namespace


EwsFolder Methods

EwsFolder Methods

The EwsFolder type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder Properties

EwsFolder Properties

The EwsFolder type exposes the following members.

Properties
 | Name | Description
Public property | FullName | Gets the folder's full name.
Public property | Id | Gets the folder's ID object.
Public property | NativeFolder | Gets EWS Managed API object for this folder.
Public property | ShortName | Gets the folder's own name.
Public property | Size | Gets the total size of all items in the folder.
Public property | TotalCount | Gets the total number of all items in the folder.
Public property | UnreadCount | Gets the number of unread items in the folder.
Top
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.FullName Property

EwsFolderFullName Property
Gets the folder's full name.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string FullName { get; }
Public ReadOnly Property FullName As String
    Get

Property Value

Type: String
Full path of the folder, or a null reference (Nothing in Visual Basic) if the value is not available.
Remarks

This property will have the value like "Inbox/Sub-folder/Deeply nested folder" if FolderLevelDelimiter is '/'.

You may get the value of -1 when acccessing this property in case if you downloaded folders using custom FolderView which didn't request this property from the server.

See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.Id Property

EwsFolderId Property
Gets the folder's ID object.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderId Id { get; }
Public ReadOnly Property Id As FolderId
    Get

Property Value

Type: FolderId
A reference to EWS Managed API's folder ID object.
Remarks
The FolderId object can be used in many methods to efficiently specify the folder to process. Using IDs is more efficient than using names or full names.
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.NativeFolder Property

EwsFolderNativeFolder Property
Gets EWS Managed API object for this folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Folder NativeFolder { get; }
Public ReadOnly Property NativeFolder As Folder
    Get

Property Value

Type: Folder
A reference to EWS Managed API's folder object.
Remarks
EwsFolder class is a wrapper around Folder class. You can use this property to access all the properties and methods EWS Managed API supports.
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.ShortName Property

EwsFolderShortName Property
Gets the folder's own name.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ShortName { get; }
Public ReadOnly Property ShortName As String
    Get

Property Value

Type: String
Display name of the folder as provided by EWS.
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.Size Property

EwsFolderSize Property
Gets the total size of all items in the folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long Size { get; }
Public ReadOnly Property Size As Long
    Get

Property Value

Type: Int64
The total size of all items in the folder in bytes, or -1 if the value is not available.
Remarks
You may get the value of -1 when acccessing this property in case if you downloaded folders using custom FolderView which didn't request this property from the server.
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.TotalCount Property

EwsFolderTotalCount Property
Gets the total number of all items in the folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TotalCount { get; }
Public ReadOnly Property TotalCount As Integer
    Get

Property Value

Type: Int32
The total number of all items in the folder, or -1 if the value is not available.
Remarks
You may get the value of -1 when acccessing this property in case if you downloaded folders using custom FolderView which didn't request this property from the server.
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsFolder.UnreadCount Property

EwsFolderUnreadCount Property
Gets the number of unread items in the folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int UnreadCount { get; }
Public ReadOnly Property UnreadCount As Integer
    Get

Property Value

Type: Int32
The number of unread items in the folder, or -1 if the value is not available.
Remarks
You may get the value of -1 when acccessing this property in case if you downloaded folders using custom FolderView which didn't request this property from the server.
See Also

Reference

EwsFolder Class
MailBee.EwsMail Namespace


EwsItem Class

EwsItem Class
Represents an item in MS Exchange folder (a mail message, contact, appointment, etc).
Inheritance Hierarchy
SystemObject
MailBee.EwsMailEwsItem

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EwsItem
Public Class EwsItem

The EwsItem type exposes the following members.

Constructors
 | Name | Description
Public method | EwsItem(ItemId) | Creates a new EwsItem from the specified ID.
Public method | EwsItem(String) | Creates a new EwsItem from the specified unique ID.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Bcc | Gets a reference to the collection of BCC e-mail addresses.
Public property | BodyHtmlText | Gets the HTML body text of the given message.
Public property | BodyPlainText | Gets the plain-text body text of the given message.
Public property | Cc | Gets a reference to the collection of CC e-mail addresses.
Public property | CodePage | Codepage used to compose the message.
Public property | Date | Gets the date and time when the message was composed.
Public property | DateReceived | Gets the date and time when the message was received by the mail server.
Public property | DatesAsUtc | Indicates if MailBee should return date and time according to UTC standard.
Public property | From | Gets a reference to From e-mail address.
Public property | Id | Gets the EWS item ID.
Public property | IsRead | Gets or sets read/unread status of the mail message.
Public property | MailBeeMessage | Gets a reference to MailBee's MailMessage object representing the mail message.
Public property | NativeItem | Get a reference to EWS Managed API Item representing the given EWS item.
Public property | NativeMessage | Gets a reference to EWS Managed API EmailMessage object representing the mail message.
Public property | ReplyTo | Gets a reference to Reply-To e-mail address.
Public property | Size | The size of the item in bytes.
Public property | Subject | Get the subject of the given message.
Public property | To | Gets a reference to the collection of To e-mail addresses.
Public property | UniqueId | Gets the Unique-ID string.
Top
Remarks
In Ews topic, you can find examples how to get mail messages from MS Exchange server, modify items (add/remove attachments and set Unread flag).
See Also

Reference

MailBee.EwsMail Namespace


EwsItem Constructor

EwsItem Constructor
Overload List
 | Name | Description
Public method | EwsItem(ItemId) | Creates a new EwsItem from the specified ID.
Public method | EwsItem(String) | Creates a new EwsItem from the specified unique ID.
Top
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem Constructor (ItemId)

EwsItem Constructor (ItemId)
Creates a new EwsItem from the specified ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem(
    ItemId id
)
Public Sub New (
    id As ItemId
)

Parameters

id
Type: ItemId
Item ID. Null reference (Nothing in Visual Basic) not allowed.
Remarks
This overload lets you wrap EWS Managed API's ItemId with MailBee's EwsItem object. This can be useful, for instance, if you're building the list of EwsItem object to be then passed to a method like DownloadItems(IEnumerableEwsItem, EwsItemParts) and for some reason already have your input data as ItemId objects from EWS Managed API.
See Also

Reference

EwsItem Class
EwsItem Overload
MailBee.EwsMail Namespace


EwsItem Constructor (String)

EwsItem Constructor (String)
Creates a new EwsItem from the specified unique ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EwsItem(
    string uniqueId
)
Public Sub New (
    uniqueId As String
)

Parameters

uniqueId
Type: SystemString
Item's string ID. Null reference (Nothing in Visual Basic) not allowed.
Remarks
You will usually use this constructor to build EwsItem objects and their collections which you can then pass to methods like DownloadItems(IEnumerableEwsItem, EwsItemParts). This is useful if you stored the list of item IDs somewhere (e.g. database) and later you need to restore it into a collection of EwsItem objects which you can pass to DownloadItems(IEnumerableEwsItem, EwsItemParts) method.
See Also

Reference

EwsItem Class
EwsItem Overload
MailBee.EwsMail Namespace


EwsItem Methods

EwsItem Methods

The EwsItem type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem Properties

EwsItem Properties

The EwsItem type exposes the following members.

Properties
 | Name | Description
Public property | Bcc | Gets a reference to the collection of BCC e-mail addresses.
Public property | BodyHtmlText | Gets the HTML body text of the given message.
Public property | BodyPlainText | Gets the plain-text body text of the given message.
Public property | Cc | Gets a reference to the collection of CC e-mail addresses.
Public property | CodePage | Codepage used to compose the message.
Public property | Date | Gets the date and time when the message was composed.
Public property | DateReceived | Gets the date and time when the message was received by the mail server.
Public property | DatesAsUtc | Indicates if MailBee should return date and time according to UTC standard.
Public property | From | Gets a reference to From e-mail address.
Public property | Id | Gets the EWS item ID.
Public property | IsRead | Gets or sets read/unread status of the mail message.
Public property | MailBeeMessage | Gets a reference to MailBee's MailMessage object representing the mail message.
Public property | NativeItem | Get a reference to EWS Managed API Item representing the given EWS item.
Public property | NativeMessage | Gets a reference to EWS Managed API EmailMessage object representing the mail message.
Public property | ReplyTo | Gets a reference to Reply-To e-mail address.
Public property | Size | The size of the item in bytes.
Public property | Subject | Get the subject of the given message.
Public property | To | Gets a reference to the collection of To e-mail addresses.
Public property | UniqueId | Gets the Unique-ID string.
Top
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.Bcc Property

EwsItemBcc Property
Gets a reference to the collection of BCC e-mail addresses.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Bcc { get; }
Public ReadOnly Property Bcc As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the collection of BCC e-mail addresses, or a null reference (Nothing in Visual Basic) if not available.
Remarks
This property is set if the list of recipients (MailMessageRecipients) has been loaded for the given message and at least one BCC recipient is present in the message. However, BCC recipients are usually not available for incoming messages because BCC header is usually stripped out of an e-mail by mail clients during submitting it to the SMTP server.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.BodyHtmlText Property

EwsItemBodyHtmlText Property
Gets the HTML body text of the given message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string BodyHtmlText { get; }
Public ReadOnly Property BodyHtmlText As String
    Get

Property Value

Type: String
The HTML body text of the given message, or an empty string if HTML body is not available, or a null reference (Nothing in Visual Basic) if this EwsItem was constructed manually (such as with EwsItem(ItemId) constructor) and there is no data in it.
Remarks
HTML body can be not available because it's either missing in the source message or it was not requested from the Exchange server. To make sure HTML body is requested, use a method like DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) passing at least MailMessageBody or MailMessageRawData flag in parts parameter value.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.BodyPlainText Property

EwsItemBodyPlainText Property
Gets the plain-text body text of the given message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string BodyPlainText { get; }
Public ReadOnly Property BodyPlainText As String
    Get

Property Value

Type: String
The HTML body text of the given message, or an empty string if plain-text body is not available, or a null reference (Nothing in Visual Basic) if this EwsItem was constructed manually (such as with EwsItem(ItemId) constructor) and there is no data in it.
Remarks

Plain-text body can be not available because it's either missing in the source message or it was not requested from the Exchange server. To make sure plain-text body is requested, use a method like DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) passing at least MailMessageBody or MailMessageRawData flag in parts parameter value.

MailBee's MailMessage class can produce plain-text from HTML. See BodyPlainText topic for details. To use MailMessage class, you'll need to get MailBeeMessage property set. For that, call a method like DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) passing at least MailMessageRawData flag in parts parameter value.

See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.Cc Property

EwsItemCc Property
Gets a reference to the collection of CC e-mail addresses.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Cc { get; }
Public ReadOnly Property Cc As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the collection of CC e-mail addresses, or a null reference (Nothing in Visual Basic) if not available.
Remarks
This property is set if the list of recipients (MailMessageRecipients) has been loaded for the given message and at least one CC recipient is present in the message.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.CodePage Property

EwsItemCodePage Property
Codepage used to compose the message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int CodePage { get; }
Public ReadOnly Property CodePage As Integer
    Get

Property Value

Type: Int32
The codepage used to compose the message, or 0 if not available, or -1 if this EwsItem was constructed manually (such as with EwsItem(ItemId) constructor) and there is no data in it.
Remarks
MailBee requests this property from the Exchange server if message body is requested (when a method like DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) was called with at least MailMessageBody flag in parts parameter value).
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.Date Property

EwsItemDate Property
Gets the date and time when the message was composed.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime Date { get; }
Public ReadOnly Property Date As DateTime
    Get

Property Value

Type: DateTime
A DateTime value indicating when the message was created, or MinValue if this information is not available.
Remarks
The server obtains this value from "Date:" header of the mail message.
Note Note
DatesAsUtc property can be set to force this property return UTC (GMT) date.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.DateReceived Property

EwsItemDateReceived Property
Gets the date and time when the message was received by the mail server.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime DateReceived { get; }
Public ReadOnly Property DateReceived As DateTime
    Get

Property Value

Type: DateTime
A DateTime value indicating when the message was received by the mail server, or MinValue if this information is not available.
Remarks
DatesAsUtc property can be set to force this property return UTC (GMT) date.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.DatesAsUtc Property

EwsItemDatesAsUtc Property
Indicates if MailBee should return date and time according to UTC standard.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DatesAsUtc { get; set; }
Public Property DatesAsUtc As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, Date and DateReceived properties will return date and time according to UTC (GMT) standard; otherwise, the returned date is timezone-corrected to match local time of the computer running MailBee. The default value is false.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.From Property

EwsItemFrom Property
Gets a reference to From e-mail address.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress From { get; }
Public ReadOnly Property From As EmailAddress
    Get

Property Value

Type: EmailAddress
A reference to From e-mail address, or a null reference (Nothing in Visual Basic) if not available.
Remarks
This property is set if at least basic properties (GenericItem) have been loaded for the given message and From header is present in the message.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.Id Property

EwsItemId Property
Gets the EWS item ID.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ItemId Id { get; }
Public ReadOnly Property Id As ItemId
    Get

Property Value

Type: ItemId
The ID of the item.
Remarks
You can pass this value to request a particular item, such as with DownloadItem(ItemId, EwsItemParts) method. If you know IDs of the items you need, you can download them all at once using DownloadItems(IEnumerableEwsItem, EwsItemParts) method, even if they are in different folders.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.IsRead Property

EwsItemIsRead Property
Gets or sets read/unread status of the mail message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsRead { get; set; }
Public Property IsRead As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, this mail message is read; if false, this mail message is unread or this property is not available.
Exceptions
Exception | Condition
MailBeeInvalidStateException | An attempt to set IsRead property for an EwsItem which in its current state does not represent a mail message.
Remarks

You can use this property only with mail messages (not for contacts, appointments, etc). Also, make sure at least GenericItem was passed to the method which was used to get this EwsItem object (passing just IdOnly won't let you then read the value of this property).

Note Note
To apply changes to IsRead property, you need to call UpdateItem(EwsItem) on this item after changing read/unread status. Also, if you just need to set this flag (not read it) for some EwsItem, requesting just IdOnly to get this item is enough. See the sample in Ews topic for example.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.MailBeeMessage Property

EwsItemMailBeeMessage Property
Gets a reference to MailBee's MailMessage object representing the mail message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailBeeMessage { get; }
Public ReadOnly Property MailBeeMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to MailMessage object representing the mail message, or a null reference (Nothing in Visual Basic) if this value is not available.
Remarks

You can use this property to get MailMessage object which you can then use with other MailBee classes and which lets you access mail message properties and features in different ways.

This property is only set if entire mail messages were requested from MS Exchange server. In particular, MailMessageRawData or MailMessageFull needs to be passed to Ews.DownloadItem(FolderId, int, EwsItemParts), Ews.DownloadItem(ItemId, EwsItemParts) or any other method accepting EwsItemParts parameter.

Note Note
This value can only be available for mail message items (but not for appointments, contacts, etc). To get items of other types, use NativeItem property.

You can also download an entire message directly using DownloadEntireMessage(ItemId) method.

See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.NativeItem Property

EwsItemNativeItem Property
Get a reference to EWS Managed API Item representing the given EWS item.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Item NativeItem { get; }
Public ReadOnly Property NativeItem As Item
    Get

Property Value

Type: Item
A reference to Item object representing the given item.
Remarks

Unlike NativeMessage or MailBeeMessage, this property is available for all kinds of MS Exchange items (including contacts, appointments, etc).

Depending on how many properties of items you requested to download, so many properties will be set in the returned Item object. For properties not loaded, the corresponding Item object properties will throw exceptions. Usually, you need to pass at least GenericItem flag to Ews.DownloadItem(FolderId, int, EwsItemParts), Ews.DownloadItem(ItemId, EwsItemParts) or any other method accepting EwsItemParts parameter. For instance, if you pass just IdOnly, only item ID will be available in the returned Item objects.

See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.NativeMessage Property

EwsItemNativeMessage Property
Gets a reference to EWS Managed API EmailMessage object representing the mail message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailMessage NativeMessage { get; }
Public ReadOnly Property NativeMessage As EmailMessage
    Get

Property Value

Type: EmailMessage
A reference to EmailMessage object representing the mail message, or a null reference (Nothing in Visual Basic) if this value is not available.
Remarks

This property lets you examine EWS Managed API version of a mail message object, with its specific properties. Some properties may cause exceptions if they were not loaded from the server (so it depends on which parts of messages were requested for download). To request all the info, MailMessageFull needs to be passed to Ews.DownloadItem(FolderId, int, EwsItemParts), Ews.DownloadItem(ItemId, EwsItemParts) or any other method accepting EwsItemParts parameter.

This behavior is different from MailBeeMessage property which is "everything or nothing". With NativeMessage object, you can have an object which is loaded only in part. This approach is more flexible although harder to use. MailBee provides you with the both options (MailBeeMessage and NativeMessage).

Note Note
This value is only available for mail message items (but not for appointments, contacts, etc). To get items of other types, use NativeItem property.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.ReplyTo Property

EwsItemReplyTo Property
Gets a reference to Reply-To e-mail address.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ReplyTo { get; }
Public ReadOnly Property ReplyTo As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to Reply-To e-mail address, or a null reference (Nothing in Visual Basic) if not available.
Remarks
This property is set if the list of recipients (MailMessageRecipients) has been loaded for the given message and Reply-To header is present in the message.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.Size Property

EwsItemSize Property
The size of the item in bytes.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Size { get; }
Public ReadOnly Property Size As Integer
    Get

Property Value

Type: Int32
The size of the item in bytes, or -1 if this EwsItem was constructed manually (such as with EwsItem(ItemId) constructor) and there is no data in it.
Remarks
MailBee requests this property from the Exchange server if so-called first-class properties for an item are requested (when a method like DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) was called with at least GenericItem flag in parts parameter value).
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.Subject Property

EwsItemSubject Property
Get the subject of the given message.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Subject { get; }
Public ReadOnly Property Subject As String
    Get

Property Value

Type: String
The subject of the given message, or a null reference (Nothing in Visual Basic) if not available.
Remarks
This property is set if at least basic properties (GenericItem) have been loaded for the given message and Subject header is present in the message.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.To Property

EwsItemTo Property
Gets a reference to the collection of To e-mail addresses.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection To { get; }
Public ReadOnly Property To As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the collection of To e-mail addresses, or a null reference (Nothing in Visual Basic) if not available.
Remarks
This property is set if the list of recipients (MailMessageRecipients) has been loaded for the given message and at least one To recipient is present in the message.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItem.UniqueId Property

EwsItemUniqueId Property
Gets the Unique-ID string.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string UniqueId { get; }
Public ReadOnly Property UniqueId As String
    Get

Property Value

Type: String
The Unique-ID string of the item.
Remarks
EWS ID is actually a string. This property provides access to the string value stored by ItemId object.
See Also

Reference

EwsItem Class
MailBee.EwsMail Namespace


EwsItemList Class

EwsItemList Class
Represents a collection o EwsItem objects, with optional paging capability.
Inheritance Hierarchy
SystemObject
System.Collections.GenericList EwsItem
MailBee.EwsMailEwsItemList

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EwsItemList : List<EwsItem>
Public Class EwsItemList
    Inherits List(Of EwsItem)

The EwsItemList type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds an object to the end of the ListT. (Inherited from List EwsItem .)
Public method | AddRange | Adds the elements of the specified collection to the end of the ListT. (Inherited from List EwsItem .)
Public method | AsReadOnly | Returns a read-only IListT wrapper for the current collection. (Inherited from List EwsItem .)
Public method | BinarySearch(T) | Searches the entire sorted ListT for an element using the default comparer and returns the zero-based index of the element. (Inherited from List EwsItem .)
Public method | BinarySearch(T, IComparerT) | Searches the entire sorted ListT for an element using the specified comparer and returns the zero-based index of the element. (Inherited from List EwsItem .)
Public method | BinarySearch(Int32, Int32, T, IComparerT) | Searches a range of elements in the sorted ListT for an element using the specified comparer and returns the zero-based index of the element. (Inherited from List EwsItem .)
Public method | Clear | Removes all elements from the ListT. (Inherited from List EwsItem .)
Public method | Contains | Determines whether an element is in the ListT. (Inherited from List EwsItem .)
Public method | ConvertAllTOutput | Converts the elements in the current ListT to another type, and returns a list containing the converted elements. (Inherited from List EwsItem .)
Public method | CopyTo(T) | Copies the entire ListT to a compatible one-dimensional array, starting at the beginning of the target array. (Inherited from List EwsItem .)
Public method | CopyTo(T, Int32) | Copies the entire ListT to a compatible one-dimensional array, starting at the specified index of the target array. (Inherited from List EwsItem .)
Public method | CopyTo(Int32, T, Int32, Int32) | Copies a range of elements from the ListT to a compatible one-dimensional array, starting at the specified index of the target array. (Inherited from List EwsItem .)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public method | Exists | Determines whether the ListT contains elements that match the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | Find | Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindAll | Retrieves all the elements that match the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Public method | FindIndex(PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindIndex(Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the ListT that extends from the specified index to the last element. (Inherited from List EwsItem .)
Public method | FindIndex(Int32, Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the ListT that starts at the specified index and contains the specified number of elements. (Inherited from List EwsItem .)
Public method | FindLast | Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindLastIndex(PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindLastIndex(Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the ListT that extends from the first element to the specified index. (Inherited from List EwsItem .)
Public method | FindLastIndex(Int32, Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the ListT that contains the specified number of elements and ends at the specified index. (Inherited from List EwsItem .)
Public method | ForEach | Performs the specified action on each element of the ListT. (Inherited from List EwsItem .)
Public method | GetEnumerator | Returns an enumerator that iterates through the ListT. (Inherited from List EwsItem .)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetRange | Creates a shallow copy of a range of elements in the source ListT. (Inherited from List EwsItem .)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IndexOf(T) | Searches for the specified object and returns the zero-based index of the first occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | IndexOf(T, Int32) | Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the ListT that extends from the specified index to the last element. (Inherited from List EwsItem .)
Public method | IndexOf(T, Int32, Int32) | Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the ListT that starts at the specified index and contains the specified number of elements. (Inherited from List EwsItem .)
Public method | Insert | Inserts an element into the ListT at the specified index. (Inherited from List EwsItem .)
Public method | InsertRange | Inserts the elements of a collection into the ListT at the specified index. (Inherited from List EwsItem .)
Public method | LastIndexOf(T) | Searches for the specified object and returns the zero-based index of the last occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | LastIndexOf(T, Int32) | Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the ListT that extends from the first element to the specified index. (Inherited from List EwsItem .)
Public method | LastIndexOf(T, Int32, Int32) | Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the ListT that contains the specified number of elements and ends at the specified index. (Inherited from List EwsItem .)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Remove | Removes the first occurrence of a specific object from the ListT. (Inherited from List EwsItem .)
Public method | RemoveAll | Removes all the elements that match the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Public method | RemoveAt | Removes the element at the specified index of the ListT. (Inherited from List EwsItem .)
Public method | RemoveRange | Removes a range of elements from the ListT. (Inherited from List EwsItem .)
Public method | Reverse | Reverses the order of the elements in the entire ListT. (Inherited from List EwsItem .)
Public method | Reverse(Int32, Int32) | Reverses the order of the elements in the specified range. (Inherited from List EwsItem .)
Public method | Sort | Sorts the elements in the entire ListT using the default comparer. (Inherited from List EwsItem .)
Public method | Sort(IComparerT) | Sorts the elements in the entire ListT using the specified comparer. (Inherited from List EwsItem .)
Public method | Sort(ComparisonT) | Sorts the elements in the entire ListT using the specified ComparisonT. (Inherited from List EwsItem .)
Public method | Sort(Int32, Int32, IComparerT) | Sorts the elements in a range of elements in ListT using the specified comparer. (Inherited from List EwsItem .)
Public method | ToArray | Copies the elements of the ListT to a new array. (Inherited from List EwsItem .)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | TrimExcess | Sets the capacity to the actual number of elements in the ListT, if that number is less than a threshold value. (Inherited from List EwsItem .)
Public method | TrueForAll | Determines whether every element in the ListT matches the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the total number of elements the internal data structure can hold without resizing. (Inherited from List EwsItem .)
Public property | Count | Gets the number of elements contained in the ListT. (Inherited from List EwsItem .)
Public property | Item | Gets or sets the element at the specified index. (Inherited from List EwsItem .)
Public property | MoreAvailable | Gets a value that indicates whether more items that match the search criteria are available in the searched folder.
Public property | NextPageOffset | Gets the offset that should be used with an ItemView object to retrieve the next page of items.
Public property | TotalCount | Gets the total number of items that match the search criteria that are available in the searched folder.
Top
Remarks
EwsItemList extends normal ListT with extra properties taken from Exchange server which let the app know how many items matching the current criteria haven't been requested yet (this is helpful if the app implements paging and thus requests only certain number of items to be returned rather than all the items). These extra properties are obtained from FindItemsResults object of the underlying EWS Managed API.
See Also

Reference

MailBee.EwsMail Namespace


EwsItemList Methods

EwsItemList Methods

The EwsItemList type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds an object to the end of the ListT. (Inherited from List EwsItem .)
Public method | AddRange | Adds the elements of the specified collection to the end of the ListT. (Inherited from List EwsItem .)
Public method | AsReadOnly | Returns a read-only IListT wrapper for the current collection. (Inherited from List EwsItem .)
Public method | BinarySearch(T) | Searches the entire sorted ListT for an element using the default comparer and returns the zero-based index of the element. (Inherited from List EwsItem .)
Public method | BinarySearch(T, IComparerT) | Searches the entire sorted ListT for an element using the specified comparer and returns the zero-based index of the element. (Inherited from List EwsItem .)
Public method | BinarySearch(Int32, Int32, T, IComparerT) | Searches a range of elements in the sorted ListT for an element using the specified comparer and returns the zero-based index of the element. (Inherited from List EwsItem .)
Public method | Clear | Removes all elements from the ListT. (Inherited from List EwsItem .)
Public method | Contains | Determines whether an element is in the ListT. (Inherited from List EwsItem .)
Public method | ConvertAllTOutput | Converts the elements in the current ListT to another type, and returns a list containing the converted elements. (Inherited from List EwsItem .)
Public method | CopyTo(T) | Copies the entire ListT to a compatible one-dimensional array, starting at the beginning of the target array. (Inherited from List EwsItem .)
Public method | CopyTo(T, Int32) | Copies the entire ListT to a compatible one-dimensional array, starting at the specified index of the target array. (Inherited from List EwsItem .)
Public method | CopyTo(Int32, T, Int32, Int32) | Copies a range of elements from the ListT to a compatible one-dimensional array, starting at the specified index of the target array. (Inherited from List EwsItem .)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public method | Exists | Determines whether the ListT contains elements that match the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | Find | Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindAll | Retrieves all the elements that match the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Public method | FindIndex(PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindIndex(Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the ListT that extends from the specified index to the last element. (Inherited from List EwsItem .)
Public method | FindIndex(Int32, Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the ListT that starts at the specified index and contains the specified number of elements. (Inherited from List EwsItem .)
Public method | FindLast | Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindLastIndex(PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | FindLastIndex(Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the ListT that extends from the first element to the specified index. (Inherited from List EwsItem .)
Public method | FindLastIndex(Int32, Int32, PredicateT) | Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the ListT that contains the specified number of elements and ends at the specified index. (Inherited from List EwsItem .)
Public method | ForEach | Performs the specified action on each element of the ListT. (Inherited from List EwsItem .)
Public method | GetEnumerator | Returns an enumerator that iterates through the ListT. (Inherited from List EwsItem .)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetRange | Creates a shallow copy of a range of elements in the source ListT. (Inherited from List EwsItem .)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IndexOf(T) | Searches for the specified object and returns the zero-based index of the first occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | IndexOf(T, Int32) | Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the ListT that extends from the specified index to the last element. (Inherited from List EwsItem .)
Public method | IndexOf(T, Int32, Int32) | Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the ListT that starts at the specified index and contains the specified number of elements. (Inherited from List EwsItem .)
Public method | Insert | Inserts an element into the ListT at the specified index. (Inherited from List EwsItem .)
Public method | InsertRange | Inserts the elements of a collection into the ListT at the specified index. (Inherited from List EwsItem .)
Public method | LastIndexOf(T) | Searches for the specified object and returns the zero-based index of the last occurrence within the entire ListT. (Inherited from List EwsItem .)
Public method | LastIndexOf(T, Int32) | Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the ListT that extends from the first element to the specified index. (Inherited from List EwsItem .)
Public method | LastIndexOf(T, Int32, Int32) | Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the ListT that contains the specified number of elements and ends at the specified index. (Inherited from List EwsItem .)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Remove | Removes the first occurrence of a specific object from the ListT. (Inherited from List EwsItem .)
Public method | RemoveAll | Removes all the elements that match the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Public method | RemoveAt | Removes the element at the specified index of the ListT. (Inherited from List EwsItem .)
Public method | RemoveRange | Removes a range of elements from the ListT. (Inherited from List EwsItem .)
Public method | Reverse | Reverses the order of the elements in the entire ListT. (Inherited from List EwsItem .)
Public method | Reverse(Int32, Int32) | Reverses the order of the elements in the specified range. (Inherited from List EwsItem .)
Public method | Sort | Sorts the elements in the entire ListT using the default comparer. (Inherited from List EwsItem .)
Public method | Sort(IComparerT) | Sorts the elements in the entire ListT using the specified comparer. (Inherited from List EwsItem .)
Public method | Sort(ComparisonT) | Sorts the elements in the entire ListT using the specified ComparisonT. (Inherited from List EwsItem .)
Public method | Sort(Int32, Int32, IComparerT) | Sorts the elements in a range of elements in ListT using the specified comparer. (Inherited from List EwsItem .)
Public method | ToArray | Copies the elements of the ListT to a new array. (Inherited from List EwsItem .)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | TrimExcess | Sets the capacity to the actual number of elements in the ListT, if that number is less than a threshold value. (Inherited from List EwsItem .)
Public method | TrueForAll | Determines whether every element in the ListT matches the conditions defined by the specified predicate. (Inherited from List EwsItem .)
Top
See Also

Reference

EwsItemList Class
MailBee.EwsMail Namespace


EwsItemList Properties

EwsItemList Properties

The EwsItemList type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the total number of elements the internal data structure can hold without resizing. (Inherited from List EwsItem .)
Public property | Count | Gets the number of elements contained in the ListT. (Inherited from List EwsItem .)
Public property | Item | Gets or sets the element at the specified index. (Inherited from List EwsItem .)
Public property | MoreAvailable | Gets a value that indicates whether more items that match the search criteria are available in the searched folder.
Public property | NextPageOffset | Gets the offset that should be used with an ItemView object to retrieve the next page of items.
Public property | TotalCount | Gets the total number of items that match the search criteria that are available in the searched folder.
Top
See Also

Reference

EwsItemList Class
MailBee.EwsMail Namespace


EwsItemList.MoreAvailable Property

EwsItemListMoreAvailable Property
Gets a value that indicates whether more items that match the search criteria are available in the searched folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MoreAvailable { get; }
Public ReadOnly Property MoreAvailable As Boolean
    Get

Property Value

Type: Boolean
If true, more items are available and you can request the next page of items. If false, no more pages are available or this value itself is not available.
Remarks
See example in Ews topic.
See Also

Reference

EwsItemList Class
MailBee.EwsMail Namespace


EwsItemList.NextPageOffset Property

EwsItemListNextPageOffset Property
Gets the offset that should be used with an ItemView object to retrieve the next page of items.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NextPageOffset { get; }
Public ReadOnly Property NextPageOffset As Integer
    Get

Property Value

Type: Int32
An integer to be used as offset for the next operation to download the next page of items, or -1 if this value is not available.
Remarks
See example in Ews topic.
See Also

Reference

EwsItemList Class
MailBee.EwsMail Namespace


EwsItemList.TotalCount Property

EwsItemListTotalCount Property
Gets the total number of items that match the search criteria that are available in the searched folder.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TotalCount { get; }
Public ReadOnly Property TotalCount As Integer
    Get

Property Value

Type: Int32
An integer value that indicates the total number of items that match the search criteria, or zero if this value is not available.
See Also

Reference

EwsItemList Class
MailBee.EwsMail Namespace


EwsItemParts Enumeration

EwsItemParts Enumeration
Defines message elements available for download using DownloadItem(ItemId, EwsItemParts) or DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) methods.

Namespace: MailBee.EwsMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum EwsItemParts
<FlagsAttribute>
Public Enumeration EwsItemParts
Members
Member name | Value | Description
IdOnly | 0 | Only item ID is requested. This is the fastest option.
GenericItem | 1 | BasePropertySet's FirstClassProperties are requested. For e-mail messages, includes ID, From, Subject, Read/Unread status.
MailMessageRecipients | 2 | To, CC, BCC, Reply-To.
MailMessageBody | 4 | Mail message body and, if MS Exchange version is 2013 or higher, also plain-text version of the body.
MailMessageAttachments | 8 | The attachments to the message.
MailMessageRawData | 16 | The complete MIME source of the message. MailBee uses it to construct MailMessage objects.
MailMessageFull | 31 | Combines GenericItem, MailMessageRecipients, MailMessageBody, MailMessageAttachments, MailMessageRawData.
Remarks

These values control to which extent EwsItem objects returned by DownloadItem(ItemId, EwsItemParts) or DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) methods will be set. For instance, to have MailBeeMessage set, you need to specify MailMessageRawData or MailMessageFull flag when calling these methods.

Item ID is always loaded.

You can combine multiple values to request multiple properties at once.

See Also

Reference

MailBee.EwsMail Namespace


MailBee.Html Namespace

MailBee.Html Namespace
MailBee.Html namespace provides classes and enumerations which can be used to process HTML documents (such as HTML e-mail bodies) in different ways, build and modify DOM (document object model), strip certain tags, find links and images, save/load documents in/from streams.
Classes
 | Class | Description
 | Element | Represents an HTML element or a piece of text in the HTML document and provides properties and methods for examining or altering the contents of this element.
Public class | ElementCollection | Provides properties and methods for managing and examining the collection of Element objects.
Public class | ElementReadOnlyCollection | Provides properties and methods for examining the collection of Element objects.
 | Processor | Helper class which provides properties and methods for loading or saving HTML document from/into a stream and examining its contents.
Public class | Rule | Represents a condition (an HTML tag name and a set of its attributes) and an action to perform when the condition is met.
 | RuleSet | Provides methods for creating rules for processing of HTML tags.
 | TagAttribute | Represents an attribute of an HTML tag.
 | TagAttributeCollection | Provides properties and methods for managing and examining the collection of TagAttribute objects.
Public class | TagAttributeReadOnlyCollection | Provides properties and methods for examining the collection of TagAttribute objects.
Delegates
Delegate | Description
ProcessElementDelegate | Defines the signature (the parameters and the return value) of the application-defined method which can be used as a filter which triggers when a rule condition gets satisfied and controls whether to perform the action defined by this rule.
Enumerations
Enumeration | Description
TagRuleTypes | Defines the available modes of processing of an HTML tag for the Rule object.


Element Class

Element Class
Represents an HTML element or a piece of text in the HTML document and provides properties and methods for examining or altering the contents of this element.
Inheritance Hierarchy
SystemObject
MailBee.HtmlElement

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Element
Public Class Element

The Element type exposes the following members.

Constructors
Name | Description
Element | Initializes a new instance of the Element class
Element(String) | Initializes a new instance of Element object with the specified HTML markup.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAllElements | Returns the current HTML element and all its child elements as a flat list.
Public method | GetAllElementsByName | Returns the current HTML element and all its child elements having the specified tag name as a flat list.
Public method | GetAttributeByName | Returns the HTML attribute with the specified name.
Public method | GetAttributesByName | Returns all attributes with the specified name and contained in the current HTML element.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetInnerElementsByName | Returns the flat list containing elements with the specified tag name and contained in the current HTML element.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Process | Applies the specified tag processing rules to the current element and any its child elements, calling a delegate for every tag which matches the specified rules.
 | ProcessToString | Applies the specified tag processing rules to the copy of the current element and any its child elements, calling a delegate for every tag which matches the specified rules, and returns the resulting OuterHtml as a string.
Public method | Remove | Removes this HTML element from InnerElements collection of its parent.
Public method | Stop | Stops execution of Process(RuleSet, ProcessElementDelegate) and ProcessToString(RuleSet, ProcessElementDelegate) methods.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Attributes | Gets the list of all attributes of the HTML tag.
Public property | InnerElements | Gets the list of HTML elements directly contained in the current HTML element.
 | InnerHtml | Gets or sets the inner HTML contents of the current HTML element.
Public property | OuterHtml | Gets or sets the text representation of the current HTML element.
Public property | TagDefinition | Gets or sets the tag definition of the current HTML element.
 | TagName | Gets or sets the tag name of the current HTML element.
Top
Remarks

Objects of this class are building blocks of DOM (document object model) of the HTML document. MailBee represents the HTML document as a tree of Element objects which can be nested within each other accordingly the HTML markup of the document. The document itself is also represented as Element object.

Each Element object has InnerElements collection of HTML elements nested in the parent one. Alternatively, you can get the list of all elements located inside the parent element, regardless of their nesting level (not important if they are nested directly in the parent element or into any of its child elements). You can use GetAllElements, GetInnerElementsByName(String) and other methods for this.

You can also access various parts of the contents of the HTML element as a string using InnerHtml, OuterHtml, TagDefinition and TagName properties. For instance, you can set TagDefinition to a certain tag definition string and then use Attributes collection to examine the attibutes of this tag.

Use Process(RuleSet, ProcessElementDelegate) or ProcessToString(RuleSet, ProcessElementDelegate) methods for advanced processing of HTML documents. These methods allow the developer to apply a set of content-processing rules to the HTML document. These rules can be both user-defined and predefined (such as GetSafeHtmlRules which defines the rules for making HTML document contents safe and free from any potentially dangerous items such as scripts).

To get the list of links or images in the document represented by Element object, create Processor object and set Dom property to the given Element object reference, and examine AHRefs and Images property values. You can also use Processor class to read/write HTML markup from/into a stream.

Examples
The example is available in AddTagReplacementRule(String, TagAttributeCollection, Element) topic.
See Also

Reference

MailBee.Html Namespace


Element Constructor

Element Constructor
Overload List
Name | Description
Element | Initializes a new instance of the Element class
Element(String) | Initializes a new instance of Element object with the specified HTML markup.
Top
See Also

Reference

Element Class
MailBee.Html Namespace


Element Constructor

Element Constructor
Initializes a new instance of the Element class

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Element()
Public Sub New
Examples
The example is available in AddTagReplacementRule(String, TagAttributeCollection, Element) topic.
See Also

Reference

Element Class
Element Overload
MailBee.Html Namespace


Element Constructor (String)

Element Constructor (String)
Initializes a new instance of Element object with the specified HTML markup.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Element(
    string htmlText
)
Public Sub New (
    htmlText As String
)

Parameters

htmlText
Type: SystemString
The actual HTML markup of the Element.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | htmlText is a null reference (Nothing in Visual Basic).
Remarks
htmlText can contain any string including HTML with broken markup, plain text, etc. MailBee will attempt to parse it even if not all tags are closed, or some tags are closed incorrectly, etc.
Examples
This samples initializes Element object with certain HTML markup and then displays the name of the root tag and the inner HTML contents of the specified markup.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee.Html;

// The actual code (put it into a method of your class).
Element richText = new Element("<html><head><title>Sample header</title></head><body>Short sample<body></html>");
Console.WriteLine("The root tag name is : " + richText.TagName);
Console.WriteLine("The inner HTML source is : " + richText.InnerHtml);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee.Html

' The actual code (put it into a method of your class).
Dim richText As New Element("<html><head><title>Sample header</title></head><body>Short sample<body></html>")
Console.WriteLine("The root tag name is : " & richText.TagName)
Console.WriteLine("The inner HTML source is : " & richText.InnerHtml)
See Also

Reference

Element Class
Element Overload
MailBee.Html Namespace


Element Methods

Element Methods

The Element type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAllElements | Returns the current HTML element and all its child elements as a flat list.
Public method | GetAllElementsByName | Returns the current HTML element and all its child elements having the specified tag name as a flat list.
Public method | GetAttributeByName | Returns the HTML attribute with the specified name.
Public method | GetAttributesByName | Returns all attributes with the specified name and contained in the current HTML element.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetInnerElementsByName | Returns the flat list containing elements with the specified tag name and contained in the current HTML element.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Process | Applies the specified tag processing rules to the current element and any its child elements, calling a delegate for every tag which matches the specified rules.
 | ProcessToString | Applies the specified tag processing rules to the copy of the current element and any its child elements, calling a delegate for every tag which matches the specified rules, and returns the resulting OuterHtml as a string.
Public method | Remove | Removes this HTML element from InnerElements collection of its parent.
Public method | Stop | Stops execution of Process(RuleSet, ProcessElementDelegate) and ProcessToString(RuleSet, ProcessElementDelegate) methods.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Element Class
MailBee.Html Namespace


Element.GetAllElements Method

ElementGetAllElements Method
Returns the current HTML element and all its child elements as a flat list.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementReadOnlyCollection GetAllElements()
Public Function GetAllElements As ElementReadOnlyCollection

Return Value

Type: ElementReadOnlyCollection
A reference to the collection containing the current HTML element and all its child elements (including their own sub-children, etc).
Remarks
The returned collection is never empty (it contains at least the current element itself).
See Also

Reference

Element Class
MailBee.Html Namespace


Element.GetAllElementsByName Method

ElementGetAllElementsByName Method
Returns the current HTML element and all its child elements having the specified tag name as a flat list.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementReadOnlyCollection GetAllElementsByName(
    string tagName
)
Public Function GetAllElementsByName (
    tagName As String
) As ElementReadOnlyCollection

Parameters

tagName
Type: SystemString
The HTML tag name. tagName is case-insensitive.

Return Value

Type: ElementReadOnlyCollection
A reference to the collection containing the current HTML element and all its child elements (including their own sub-children, etc) having the specified tag name.
Remarks

If tagName is a null reference, the returned collection will contain only those child elements which are not tags (i.e. plain-text blocks).

The returned collection is never empty (it contains at least the current element itself).

See Also

Reference

Element Class
MailBee.Html Namespace


Element.GetAttributeByName Method

ElementGetAttributeByName Method
Returns the HTML attribute with the specified name.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttribute GetAttributeByName(
    string attrName
)
Public Function GetAttributeByName (
    attrName As String
) As TagAttribute

Parameters

attrName
Type: SystemString
The name of HTML attribute. attrName is case-insensitive.

Return Value

Type: TagAttribute
A TagAttribute object representing the specified attribute, or a null reference (Nothing in Visual Basic) if the tag definition does not contain the specified attribute.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attrName is a null reference (Nothing in Visual Basic).
Remarks
This method returns the first occurrence of the specified attribute. If you need to examine tags which may contain multiple occurrences of the same attribute, use GetAttributesByName(String) method.
See Also

Reference

Element Class
MailBee.Html Namespace


Element.GetAttributesByName Method

ElementGetAttributesByName Method
Returns all attributes with the specified name and contained in the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttributeReadOnlyCollection GetAttributesByName(
    string attrName
)
Public Function GetAttributesByName (
    attrName As String
) As TagAttributeReadOnlyCollection

Parameters

attrName
Type: SystemString
The name of HTML attribute. attrName is case-insensitive.

Return Value

Type: TagAttributeReadOnlyCollection
A reference to the collection of attrName attributes of the current HTML element.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attrName is a null reference (Nothing in Visual Basic).
Remarks
Usually the returned collection will contain 1 or 0 attributes. It's uncommon for an HTML tag to contain multiple attributes with the same name.
See Also

Reference

Element Class
MailBee.Html Namespace


Element.GetInnerElementsByName Method

ElementGetInnerElementsByName Method
Returns the flat list containing elements with the specified tag name and contained in the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementReadOnlyCollection GetInnerElementsByName(
    string tagName
)
Public Function GetInnerElementsByName (
    tagName As String
) As ElementReadOnlyCollection

Parameters

tagName
Type: SystemString
The HTML tag name. tagName is case-insensitive.

Return Value

Type: ElementReadOnlyCollection
A reference to the collection containing those child elements of the current HTML element (including their own sub-children, etc) which have the specified tag name.
Remarks
If tagName is a null reference, the returned collection will contain only those child elements which are not tags (i.e. plain-text blocks).
See Also

Reference

Element Class
MailBee.Html Namespace


Element.Process Method

ElementProcess Method
Applies the specified tag processing rules to the current element and any its child elements, calling a delegate for every tag which matches the specified rules.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Process(
    RuleSet rules,
    ProcessElementDelegate del
)
Public Sub Process (
    rules As RuleSet,
    del As ProcessElementDelegate
)

Parameters

rules
Type: MailBee.HtmlRuleSet
A set of rules to be applied during processing the element.
del
Type: MailBee.HtmlProcessElementDelegate
The delegate to be called for every HTML element which satisfies conditions of any rule in rules, or a null reference (Nothing in Visual Basic) if no delegate should be called.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | rules is a null reference (Nothing in Visual Basic).
Remarks

This method alters the element during processing. To return the modified version while leaving the element contents intact, use ProcessToString(RuleSet, ProcessElementDelegate) method.

If you specified del delegate, Process(RuleSet, ProcessElementDelegate) method will execute it whenever any rule matches. It's also possible to define a rule which does nothing except calling the delegate. You can add such a rule using AddTagProcessingCondition(String, TagAttributeCollection) method.

Examples
The example is available in AddTagProcessingCondition(String, TagAttributeCollection) topic.
See Also

Reference

Element Class
MailBee.Html Namespace
ElementProcessToString(RuleSet, ProcessElementDelegate)


Element.ProcessToString Method

ElementProcessToString Method
Applies the specified tag processing rules to the copy of the current element and any its child elements, calling a delegate for every tag which matches the specified rules, and returns the resulting OuterHtml as a string.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ProcessToString(
    RuleSet rules,
    ProcessElementDelegate del
)
Public Function ProcessToString (
    rules As RuleSet,
    del As ProcessElementDelegate
) As String

Parameters

rules
Type: MailBee.HtmlRuleSet
A set of rules to be applied during processing the element.
del
Type: MailBee.HtmlProcessElementDelegate
The delegate to be called for every HTML element which satisfies conditions of any rule in rules, or a null reference (Nothing in Visual Basic) if no delegate should be called.

Return Value

Type: String
A string containing OuterHtml of the current Element copy which was modified accordingly the specified rules.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | rules is a null reference (Nothing in Visual Basic).
Remarks

This method does not alter the element during processing (all operations take place on its temporary copy).

If you specified del delegate, ProcessToString(RuleSet, ProcessElementDelegate) method will execute it whenever any rule matches. It's also possible to define a rule which does nothing except calling the delegate. You can add such a rule using AddTagProcessingCondition(String, TagAttributeCollection) method.

Examples
The example is available in AddTagProcessingRule(String, TagAttributeCollection, TagAttributeCollection, TagAttributeCollection, Boolean) topic.
See Also

Reference

Element Class
MailBee.Html Namespace
ElementProcess(RuleSet, ProcessElementDelegate)


Element.Remove Method

ElementRemove Method
Removes this HTML element from InnerElements collection of its parent.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Remove()
Public Sub Remove
Remarks
If this element is not contained in another Element (i.e. does not have a parent), this method does nothing.
See Also

Reference

Element Class
MailBee.Html Namespace


Element.Stop Method

ElementStop Method
Stops execution of Process(RuleSet, ProcessElementDelegate) and ProcessToString(RuleSet, ProcessElementDelegate) methods.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Stop()
Public Sub Stop
Remarks

You can call this method in ProcessElementDelegate method if want to stop processing of the document.

If Process(RuleSet, ProcessElementDelegate) or ProcessToString(RuleSet, ProcessElementDelegate) method is not being running, this method does nothing.

Note Note
You should call Stop method for the same object you earlier called Process(RuleSet, ProcessElementDelegate) or ProcessToString(RuleSet, ProcessElementDelegate) method for. If you call it for another object (such as the object which was passed as elem parameter to your delegate method), this will not have any effect.
See Also

Reference

Element Class
MailBee.Html Namespace


Element Properties

Element Properties

The Element type exposes the following members.

Properties
 | Name | Description
Public property | Attributes | Gets the list of all attributes of the HTML tag.
Public property | InnerElements | Gets the list of HTML elements directly contained in the current HTML element.
 | InnerHtml | Gets or sets the inner HTML contents of the current HTML element.
Public property | OuterHtml | Gets or sets the text representation of the current HTML element.
Public property | TagDefinition | Gets or sets the tag definition of the current HTML element.
 | TagName | Gets or sets the tag name of the current HTML element.
Top
See Also

Reference

Element Class
MailBee.Html Namespace


Element.Attributes Property

ElementAttributes Property
Gets the list of all attributes of the HTML tag.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttributeCollection Attributes { get; }
Public ReadOnly Property Attributes As TagAttributeCollection
    Get

Property Value

Type: TagAttributeCollection
A reference to the collection of attributes of the HTML tag or a null reference (Nothing in Visual Basic) if TagName is a null reference (i.e. the current HTML element does not denote a tag).
See Also

Reference

Element Class
MailBee.Html Namespace


Element.InnerElements Property

ElementInnerElements Property
Gets the list of HTML elements directly contained in the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementCollection InnerElements { get; }
Public ReadOnly Property InnerElements As ElementCollection
    Get

Property Value

Type: ElementCollection
A reference to the collection of sub-elements of the current Element object. It's never a null reference (Nothing in Visual Basic).
Remarks
The returned collection contains only immediate children of the current element. Elements which are nested into child elements (sub-sub-elements, etc) are not included into the returned collection. Also, the collection can be empty if no children exist. To get the list of all contained elements (regardless of their nesting level), use GetAllElements method (it will return all the contained elements including the current element itself and thus will never be empty).
See Also

Reference

Element Class
MailBee.Html Namespace


Element.InnerHtml Property

ElementInnerHtml Property
Gets or sets the inner HTML contents of the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string InnerHtml { get; set; }
Public Property InnerHtml As String
    Get
    Set

Property Value

Type: String
A string containing the inner HTML data enclosed between opening and closing tags of the current element, or an empty string if there is no content in the current HTML element. It's never a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
If the current element is not an HTML tag but rather a block of plain text, InnerHtml and OuterHtml properties will return the same value (the plain text contents).
Examples
The example is available in Element(String) topic.
See Also

Reference

Element Class
MailBee.Html Namespace
ElementOuterHtml


Element.OuterHtml Property

ElementOuterHtml Property
Gets or sets the text representation of the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OuterHtml { get; set; }
Public Property OuterHtml As String
    Get
    Set

Property Value

Type: String
A string containing the current HTML element with its inner content and opening and closing tags if any. It's never a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Element Class
MailBee.Html Namespace
ElementInnerHtml


Element.TagDefinition Property

ElementTagDefinition Property
Gets or sets the tag definition of the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TagDefinition { get; set; }
Public Property TagDefinition As String
    Get
    Set

Property Value

Type: String
A string definition of the current HTML tag or a null reference (Nothing in Visual Basic) if this Element object represents a plain-text block rather than a tag.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is an empty string.
Remarks
The tag definition is a string inside angle brackets of the opening tag. For instance, if the entire tag is <script src="file.js"></script>, the tag definition is script src="file.js".
See Also

Reference

Element Class
MailBee.Html Namespace


Element.TagName Property

ElementTagName Property
Gets or sets the tag name of the current HTML element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TagName { get; set; }
Public Property TagName As String
    Get
    Set

Property Value

Type: String
A string name of the current HTML tag or a null reference (Nothing in Visual Basic) if the current Element object represents a plain-text block rather than a tag.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is an empty string.
Remarks
Tag names are case-insensitive.
Examples
The example is available in Element(String) topic.
See Also

Reference

Element Class
MailBee.Html Namespace


ElementCollection Class

ElementCollection Class
Provides properties and methods for managing and examining the collection of Element objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.HtmlElementCollection

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ElementCollection : CollectionBase
Public Class ElementCollection
    Inherits CollectionBase

The ElementCollection type exposes the following members.

Constructors
 | Name | Description
Public method | ElementCollection | Initializes a new instance of the ElementCollection class
Top
Methods
 | Name | Description
Public method | Add(Element) | Adds the specified Element object to the collection.
Public method | Add(Element, Int32) | Adds the specified Element object to the collection at the specified index.
Public method | AddRange(ElementCollection) | Adds all elements of another collection to the current collection.
Public method | AddRange(ElementCollection, Int32, Int32, Int32) | Adds elements from another ElementCollection object within the specified range.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove | Removes the specified Element object from the collection.
Public method | RemoveAll | Removes all elements from the collection.
Public method | RemoveAt | Removes Element object having the the specified zero-based index from the collection.
Public method | RemoveByName | Removes all elements having the specified tag name from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the Element object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.Html Namespace


ElementCollection Constructor

ElementCollection Constructor
Initializes a new instance of the ElementCollection class

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementCollection()
Public Sub New
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementCollection Methods

ElementCollection Methods

The ElementCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add(Element) | Adds the specified Element object to the collection.
Public method | Add(Element, Int32) | Adds the specified Element object to the collection at the specified index.
Public method | AddRange(ElementCollection) | Adds all elements of another collection to the current collection.
Public method | AddRange(ElementCollection, Int32, Int32, Int32) | Adds elements from another ElementCollection object within the specified range.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove | Removes the specified Element object from the collection.
Public method | RemoveAll | Removes all elements from the collection.
Public method | RemoveAt | Removes Element object having the the specified zero-based index from the collection.
Public method | RemoveByName | Removes all elements having the specified tag name from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementCollection.Add Method

ElementCollectionAdd Method
Overload List
 | Name | Description
Public method | Add(Element) | Adds the specified Element object to the collection.
Public method | Add(Element, Int32) | Adds the specified Element object to the collection at the specified index.
Top
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementCollection.Add Method (Element)

ElementCollectionAdd Method (Element)
Adds the specified Element object to the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    Element elem
)
Public Sub Add (
    elem As Element
)

Parameters

elem
Type: MailBee.HtmlElement
The Element object to be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | elem is a null reference (Nothing in Visual Basic).
See Also

Reference

ElementCollection Class
Add Overload
MailBee.Html Namespace


ElementCollection.Add Method (Element, Int32)

ElementCollectionAdd Method (Element, Int32)
Adds the specified Element object to the collection at the specified index.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    Element elem,
    int index
)
Public Sub Add (
    elem As Element,
    index As Integer
)

Parameters

elem
Type: MailBee.HtmlElement
The Element object to be added to the collection.
index
Type: SystemInt32
The zero-based index where to insert the specified Element object in the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | elem is a null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | The specified index is not valid.
See Also

Reference

ElementCollection Class
Add Overload
MailBee.Html Namespace


ElementCollection.AddRange Method

ElementCollectionAddRange Method
Adds multiple elements to the collection.
Overload List
 | Name | Description
Public method | AddRange(ElementCollection) | Adds all elements of another collection to the current collection.
Public method | AddRange(ElementCollection, Int32, Int32, Int32) | Adds elements from another ElementCollection object within the specified range.
Top
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementCollection.AddRange Method (ElementCollection)

ElementCollectionAddRange Method (ElementCollection)
Adds all elements of another collection to the current collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddRange(
    ElementCollection elems
)
Public Sub AddRange (
    elems As ElementCollection
)

Parameters

elems
Type: MailBee.HtmlElementCollection
The elements from ElementCollection object to be added.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | elems is a null reference (Nothing in Visual Basic).
See Also

Reference

ElementCollection Class
AddRange Overload
MailBee.Html Namespace


ElementCollection.AddRange Method (ElementCollection, Int32, Int32, Int32)

ElementCollectionAddRange Method (ElementCollection, Int32, Int32, Int32)
Adds elements from another ElementCollection object within the specified range.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddRange(
    ElementCollection elems,
    int srcIndex,
    int count,
    int destIndex
)
Public Sub AddRange (
    elems As ElementCollection,
    srcIndex As Integer,
    count As Integer,
    destIndex As Integer
)

Parameters

elems
Type: MailBee.HtmlElementCollection
The source ElementCollection to add elements from.
srcIndex
Type: SystemInt32
The zero-based index in elems collection from which to copy the elements.
count
Type: SystemInt32
Number of elements to be added from elems collection.
destIndex
Type: SystemInt32
The zero-based index in the current collection where to insert the first element from the copied range.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | elems is a null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | The specified index is not valid.
See Also

Reference

ElementCollection Class
AddRange Overload
MailBee.Html Namespace


ElementCollection.Remove Method

ElementCollectionRemove Method
Removes the specified Element object from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    Element elem
)
Public Function Remove (
    elem As Element
) As Boolean

Parameters

elem
Type: MailBee.HtmlElement
The Element object to be removed from the collection.

Return Value

Type: Boolean
true if the specified Element was found and removed; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | elem is a null reference (Nothing in Visual Basic).
See Also

Reference

ElementCollection Class
MailBee.Html Namespace
ElementCollectionRemoveAt(Int32)
ElementCollectionRemoveByName(String)


ElementCollection.RemoveAll Method

ElementCollectionRemoveAll Method
Removes all elements from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAll()
Public Sub RemoveAll
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementCollection.RemoveAt Method

ElementCollectionRemoveAt Method
Removes Element object having the the specified zero-based index from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index of Element to be removed from the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

ElementCollection Class
MailBee.Html Namespace
ElementCollectionRemove(Element)
ElementCollectionRemoveByName(String)


ElementCollection.RemoveByName Method

ElementCollectionRemoveByName Method
Removes all elements having the specified tag name from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveByName(
    string tagName
)
Public Sub RemoveByName (
    tagName As String
)

Parameters

tagName
Type: SystemString
The HTML tag name (case-insensitive) or a null reference (Nothing in Visual Basic) if plain-text elements should be removed.
See Also

Reference

ElementCollection Class
MailBee.Html Namespace
ElementTagName


ElementCollection Properties

ElementCollection Properties

The ElementCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the Element object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementCollection.Item Property

ElementCollectionItem Property
Gets or sets the Element object at the specified zero-based index in the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Element this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As Element
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index number of the element in the collection.

Property Value

Type: Element
An Element object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

ElementCollection Class
MailBee.Html Namespace


ElementReadOnlyCollection Class

ElementReadOnlyCollection Class
Provides properties and methods for examining the collection of Element objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.HtmlElementReadOnlyCollection

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ElementReadOnlyCollection : CollectionBase
Public Class ElementReadOnlyCollection
    Inherits CollectionBase

The ElementReadOnlyCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets Element object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.Html Namespace


ElementReadOnlyCollection Methods

ElementReadOnlyCollection Methods

The ElementReadOnlyCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ElementReadOnlyCollection Class
MailBee.Html Namespace


ElementReadOnlyCollection Properties

ElementReadOnlyCollection Properties

The ElementReadOnlyCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets Element object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

ElementReadOnlyCollection Class
MailBee.Html Namespace


ElementReadOnlyCollection.Item Property

ElementReadOnlyCollectionItem Property
Gets Element object at the specified zero-based index in the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Element this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Element
    Get

Parameters

index
Type: SystemInt32
The zero-based index number of the element in the collection.

Property Value

Type: Element
An Element object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

ElementReadOnlyCollection Class
MailBee.Html Namespace


ProcessElementDelegate Delegate

ProcessElementDelegate Delegate
Defines the signature (the parameters and the return value) of the application-defined method which can be used as a filter which triggers when a rule condition gets satisfied and controls whether to perform the action defined by this rule.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate bool ProcessElementDelegate(
    Element elem,
    Rule rule
)
Public Delegate Function ProcessElementDelegate (
    elem As Element,
    rule As Rule
) As Boolean

Parameters

elem
Type: MailBee.HtmlElement
The element which satisfied conditions of the rule.
rule
Type: MailBee.HtmlRule
The rule which was satisfied.

Return Value

Type: Boolean
Should return true to tell MailBee to apply the action associated with the rule for which this delegate was called, or false to ignore this rule and continue. Has no effect on rules of ProcessingCondition type.
Remarks

This delegate defines a pattern for the callback method MailBee executes when it encounters any matches of HTML processing rule conditions with particular HTML elements. You can implement any custom processing in this method, modify the given HTML element, or decide whether the rule should be applied by returning true of false.

Process(RuleSet, ProcessElementDelegate) method, while being running, executes a delegate method every time when any of the rules gets satisfied. This happens when the rule condition matches a particular HTML tag (for instance, you're using a rule which applies to all <A> tags with HREF attributes and Process(RuleSet, ProcessElementDelegate) method encountered such a tag).

Process(RuleSet, ProcessElementDelegate) method then executes the delegate passing a reference to the matching Element. The delegate method should examine the supplied element and return either true to let MailBee apply the rule action to this element or false to ignore it. The return value of the delegate, however, does not affect whether Process(RuleSet, ProcessElementDelegate) method will continue processing of subsequent elements of the document. To make Process(RuleSet, ProcessElementDelegate) method completely stop processing of the current document, call Stop method for the same object you earlier called Process(RuleSet, ProcessElementDelegate) for.

Rules of all types (defined in TagRuleTypes enumeration) cause the delegate be executed. Moreover, ProcessingCondition rule does not perform any actions except calling the delegate itself.

Examples
The example is available in AddTagProcessingCondition(String, TagAttributeCollection) topic.
See Also

Reference

MailBee.Html Namespace
ElementProcess(RuleSet, ProcessElementDelegate)
MailBee.HtmlRuleSet
MailBee.HtmlRule
MailBee.HtmlTagRuleTypes


Processor Class

Processor Class
Helper class which provides properties and methods for loading or saving HTML document from/into a stream and examining its contents.
Inheritance Hierarchy
SystemObject
MailBee.HtmlProcessor

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Processor
Public Class Processor

The Processor type exposes the following members.

Constructors
 | Name | Description
Public method | Processor | Initializes a new instance of the Processor class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | LoadFromStream | Loads HTML markup from a stream.
Public method | LoadFromStreamAsync | async/await version of LoadFromStream(Stream, Encoding).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | SaveToStream | Saves HTML markup into a stream.
Public method | SaveToStreamAsync | async/await version of SaveToStream(Stream, Encoding).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AHRefs | Gets the list of all links (<A HREF> tags) in Dom HTML document.
Public property | Dom | Gets the root Element object which represents the entire HTML document.
Public property | Images | Gets the list of all <IMG> tags in Dom HTML document.
Public property | LastResult | Gets the code of the last occurred error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks

Use this class if you need to load HTML document from a stream (or save it into a stream) or access the collections of links or images contained in the document. In other cases, you can use Element class on its own.

As alternative to using this class, you can create Element object directly and use the standard stream classes of .NET framework to fill this Element object with data. To access links, images, or any other elements, you can use GetAllElementsByName(String) method.

Examples
The example is available in AddTagRemovalRule(String, TagAttributeCollection) topic.
See Also

Reference

MailBee.Html Namespace


Processor Constructor

Processor Constructor
Initializes a new instance of the Processor class

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Processor()
Public Sub New
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor Methods

Processor Methods

The Processor type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | LoadFromStream | Loads HTML markup from a stream.
Public method | LoadFromStreamAsync | async/await version of LoadFromStream(Stream, Encoding).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | SaveToStream | Saves HTML markup into a stream.
Public method | SaveToStreamAsync | async/await version of SaveToStream(Stream, Encoding).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.LoadFromStream Method

ProcessorLoadFromStream Method
Loads HTML markup from a stream.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LoadFromStream(
    Stream inputStream,
    Encoding enc
)
Public Function LoadFromStream (
    inputStream As Stream,
    enc As Encoding
) As Boolean

Parameters

inputStream
Type: System.IOStream
The stream representing the content of the HTML markup.
enc
Type: System.TextEncoding
The encoding to use for decoding stream data from bytes to string. If a null reference (Nothing in Visual Basic), UTF-8 encoding will be used.

Return Value

Type: Boolean
true if the entire data was successfully read from the stream; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | inputStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred and ThrowExceptions is true.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.LoadFromStreamAsync Method

ProcessorLoadFromStreamAsync Method
async/await version of LoadFromStream(Stream, Encoding).

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoadFromStreamAsync(
    Stream inputStream,
    Encoding enc
)
Public Function LoadFromStreamAsync (
    inputStream As Stream,
    enc As Encoding
) As Task(Of Boolean)

Parameters

inputStream
Type: System.IOStream
The stream representing the content of the HTML markup.
enc
Type: System.TextEncoding
The encoding to use for decoding stream data from bytes to string. If a null reference (Nothing in Visual Basic), UTF-8 encoding will be used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the entire data was successfully read from the stream; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | inputStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred and ThrowExceptions is true.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.SaveToStream Method

ProcessorSaveToStream Method
Saves HTML markup into a stream.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveToStream(
    Stream outputStream,
    Encoding enc
)
Public Function SaveToStream (
    outputStream As Stream,
    enc As Encoding
) As Boolean

Parameters

outputStream
Type: System.IOStream
The stream where the HTML markup should be saved to.
enc
Type: System.TextEncoding
The encoding to use for encoding the HTML data from string into bytes. If a null reference (Nothing in Visual Basic), UTF-8 encoding will be used.

Return Value

Type: Boolean
true if the entire data was successfully encoded and saved into the stream; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | outputStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | The given stream does not support writing or stream I/O error occurred, and ThrowExceptions is true.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.SaveToStreamAsync Method

ProcessorSaveToStreamAsync Method
async/await version of SaveToStream(Stream, Encoding).

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveToStreamAsync(
    Stream outputStream,
    Encoding enc
)
Public Function SaveToStreamAsync (
    outputStream As Stream,
    enc As Encoding
) As Task(Of Boolean)

Parameters

outputStream
Type: System.IOStream
The stream where the HTML markup should be saved to.
enc
Type: System.TextEncoding
The encoding to use for encoding the HTML data from string into bytes. If a null reference (Nothing in Visual Basic), UTF-8 encoding will be used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the entire data was successfully encoded and saved into the stream; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | outputStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | The given stream does not support writing or stream I/O error occurred, and ThrowExceptions is true.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor Properties

Processor Properties

The Processor type exposes the following members.

Properties
 | Name | Description
Public property | AHRefs | Gets the list of all links (<A HREF> tags) in Dom HTML document.
Public property | Dom | Gets the root Element object which represents the entire HTML document.
Public property | Images | Gets the list of all <IMG> tags in Dom HTML document.
Public property | LastResult | Gets the code of the last occurred error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.AHRefs Property

ProcessorAHRefs Property
Gets the list of all links (<A HREF> tags) in Dom HTML document.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementReadOnlyCollection AHRefs { get; }
Public ReadOnly Property AHRefs As ElementReadOnlyCollection
    Get

Property Value

Type: ElementReadOnlyCollection
A reference to the collection containing all the hyperlinks in the current HTML document.
Remarks
To remove links from HTML, use AddTagRemovalRule(String, TagAttributeCollection) method.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.Dom Property

ProcessorDom Property
Gets the root Element object which represents the entire HTML document.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Element Dom { get; }
Public ReadOnly Property Dom As Element
    Get

Property Value

Type: Element
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.Images Property

ProcessorImages Property
Gets the list of all <IMG> tags in Dom HTML document.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ElementReadOnlyCollection Images { get; }
Public ReadOnly Property Images As ElementReadOnlyCollection
    Get

Property Value

Type: ElementReadOnlyCollection
A reference to the collection containing all the images in the current HTML document.
Remarks
To remove images from HTML, use AddTagRemovalRule(String, TagAttributeCollection) method.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.LastResult Property

ProcessorLastResult Property
Gets the code of the last occurred error.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error, or the OK value if no errors occurred. The default value is OK.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Processor Class
MailBee.Html Namespace


Processor.ThrowExceptions Property

ProcessorThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the object will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the object methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee usage will still be thrown.

Typical example of such errors is passing invalid arguments to methods. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

See Also

Reference

Processor Class
MailBee.Html Namespace


Rule Class

Rule Class
Represents a condition (an HTML tag name and a set of its attributes) and an action to perform when the condition is met.
Inheritance Hierarchy
SystemObject
MailBee.HtmlRule

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Rule
Public Class Rule

The Rule type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | RuleType | Gets the type of the action to perform when processing HTML tags which match the rule condition.
Public property | TagAttributes | Gets the list of attributes any of which must exist in the tag definiton in order to satisfy the rule condition for TagName tag.
Public property | TagName | Gets the name of the HTML tag for which to apply the rule.
Top
Remarks

A rule specifies for which tag to apply a certain action. The rule can additionally specify that only tags with certain attributes should be processed (for instance, <A> tags with HREF attributes).

The actions can be pre-defined or user-defined (see TagRuleTypes). To implement user-defined action, create a method of ProcessElementDelegate type and pass a reference to it when calling Process(RuleSet, ProcessElementDelegate) or ProcessToString(RuleSet, ProcessElementDelegate) method.

To define rules, use RuleSet object methods.

To define a set of rules which tells Process(RuleSet, ProcessElementDelegate) method to remove any ponentially unsafe contents from the HTML document, use GetSafeHtmlRules method.

Note Note
A rule, once created and added to the RuleSet, cannot be changed. You can, however, remove an existing rule from the RuleSet and add anonther one.
See Also

Reference

MailBee.Html Namespace
MailBee.HtmlRuleSet


Rule Methods

Rule Methods

The Rule type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Rule Class
MailBee.Html Namespace


Rule Properties

Rule Properties

The Rule type exposes the following members.

Properties
 | Name | Description
Public property | RuleType | Gets the type of the action to perform when processing HTML tags which match the rule condition.
Public property | TagAttributes | Gets the list of attributes any of which must exist in the tag definiton in order to satisfy the rule condition for TagName tag.
Public property | TagName | Gets the name of the HTML tag for which to apply the rule.
Top
See Also

Reference

Rule Class
MailBee.Html Namespace


Rule.RuleType Property

RuleRuleType Property
Gets the type of the action to perform when processing HTML tags which match the rule condition.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagRuleTypes RuleType { get; }
Public ReadOnly Property RuleType As TagRuleTypes
    Get

Property Value

Type: TagRuleTypes
The type of the action to perform when processing HTML tags which match the rule condition.
See Also

Reference

Rule Class
MailBee.Html Namespace


Rule.TagAttributes Property

RuleTagAttributes Property
Gets the list of attributes any of which must exist in the tag definiton in order to satisfy the rule condition for TagName tag.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttributeCollection TagAttributes { get; }
Public ReadOnly Property TagAttributes As TagAttributeCollection
    Get

Property Value

Type: TagAttributeCollection
A reference to the collection of attributes any of which must exist in TagName tag being processed in order to satisfy the rule condition and apply the action, or a null reference (Nothing in Visual Basic) if any tags with TagName name should be processed regardless of which attributes they have.
See Also

Reference

Rule Class
MailBee.Html Namespace
RuleTagName


Rule.TagName Property

RuleTagName Property
Gets the name of the HTML tag for which to apply the rule.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TagName { get; }
Public ReadOnly Property TagName As String
    Get

Property Value

Type: String
The name of the HTML tag for which this rule should be applied.
Remarks
If TagAttributes is not a null reference (Nothing in Visual Basic), the rule's action will be applied only to those HTML tags which have TagName as a tag name and any of TagAttributes as their attributes.
See Also

Reference

Rule Class
MailBee.Html Namespace
RuleTagAttributes


RuleSet Class

RuleSet Class
Provides methods for creating rules for processing of HTML tags.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.HtmlRuleSet

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class RuleSet : CollectionBase
Public Class RuleSet
    Inherits CollectionBase

The RuleSet type exposes the following members.

Constructors
 | Name | Description
Public method | RuleSet | Initializes a new instance of the RuleSet class
Top
Methods
 | Name | Description
 | AddTagProcessingCondition | Adds a rule which represents the condition when ProcessElementDelegate delegate should be executed.
 | AddTagProcessingRule | Adds a rule for changing attributes of HTML tags.
 | AddTagRemovalRule | Adds a rule for removing tags with the given name and attributes.
 | AddTagReplacementRule(String, TagAttributeCollection, Element) | Adds a rule for replacing certain tags with the specified replacement element.
 | AddTagReplacementRule(String, TagAttributeCollection, String, Boolean) | Adds a rule for replacing certain tags with the specified replacement string.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetSafeHtmlRules | Returns a set of rules which specify removing of all potentially unsafe content from the HTML document.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the Rule object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

This class represents a set of rules which describe how certain tags should be processed with Process(RuleSet, ProcessElementDelegate) or ProcessToString(RuleSet, ProcessElementDelegate) methods.

Each Rule in the RuleSet represents a rule to apply to a certain tag having certain attributes.

Examples
The example is available in AddTagProcessingCondition(String, TagAttributeCollection) topic.
See Also

Reference

MailBee.Html Namespace
MailBee.HtmlRule
ElementProcess(RuleSet, ProcessElementDelegate)


RuleSet Constructor

RuleSet Constructor
Initializes a new instance of the RuleSet class

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RuleSet()
Public Sub New
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet Methods

RuleSet Methods

The RuleSet type exposes the following members.

Methods
 | Name | Description
 | AddTagProcessingCondition | Adds a rule which represents the condition when ProcessElementDelegate delegate should be executed.
 | AddTagProcessingRule | Adds a rule for changing attributes of HTML tags.
 | AddTagRemovalRule | Adds a rule for removing tags with the given name and attributes.
 | AddTagReplacementRule(String, TagAttributeCollection, Element) | Adds a rule for replacing certain tags with the specified replacement element.
 | AddTagReplacementRule(String, TagAttributeCollection, String, Boolean) | Adds a rule for replacing certain tags with the specified replacement string.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetSafeHtmlRules | Returns a set of rules which specify removing of all potentially unsafe content from the HTML document.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet.AddTagProcessingCondition Method

RuleSetAddTagProcessingCondition Method
Adds a rule which represents the condition when ProcessElementDelegate delegate should be executed.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddTagProcessingCondition(
    string tagName,
    TagAttributeCollection tagAttrs
)
Public Sub AddTagProcessingCondition (
    tagName As String,
    tagAttrs As TagAttributeCollection
)

Parameters

tagName
Type: SystemString
The name of the tag or for which to execute the delegate. Case-insensitive.
tagAttrs
Type: MailBee.HtmlTagAttributeCollection
The list of attributes any of which must exist in the definition of tagName tags in order to execute the delegate, or a null reference (Nothing in Visual Basic) to execute the delegate for any tags with tagName name (regardless of which attributes they have).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | tagName is a null reference (Nothing in Visual Basic) or an empty string.
Remarks

For instance, if tagName is A and tagAttrs is a null reference, Process(RuleSet, ProcessElementDelegate) method will execute ProcessElementDelegate delegate (specified in del parameter) for all <A> tags in the document.

If tagName is INPUT and tagAttrs contains TYPE=IMAGE and TYPE=FILE attributes, Process(RuleSet, ProcessElementDelegate) method will execute the delegate for all <INPUT TYPE=IMAGE> and <INPUT TYPE=FILE> tags but not for <INPUT TYPE=TEXT> tags.

This method creates a Rule of ProcessingCondition type. Rules of other types have the same conditions (tag name and optional list of attributes). The only difference between rule types is what action to perform when the condition gets satisfied. ProcessingCondition rule simply calls the delegate. Other rules call the delegate first, then check the return value of the delegate and perform the specified action only if the delegate returned true.

Note Note
If Process(RuleSet, ProcessElementDelegate) method was called with del parameter set to a null reference, ProcessingCondition rule will have no effect. Rules of other types will be executed as if the delegate always returned true.

The above applies to both Process(RuleSet, ProcessElementDelegate) and ProcessToString(RuleSet, ProcessElementDelegate) methods.

Examples
This sample demonstrates removing of images from an HTML source and replacing of BR tags with HR tags.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using System.Net;
using MailBee;
using MailBee.Html;

class Sample
{
    // The delegate is used for processing of the HTML source.
    // All IMG tags will be removed and all BR tags will be replaced with HR tags.
    static bool ProcessDelegate(Element elem, Rule rule)
    {
        switch (elem.TagName.ToLower())
        {
            case "img":
                elem.Remove();
                break;
            case "br":
                elem.TagName = "hr";
                return false;
        }
        return true;
    }

    static void Main(string[] args)
    {
        // Create a new stream and load the HTML document into it.
        WebRequest myWebRequest = WebRequest.Create("http://www.afterlogic.com");
        WebResponse myWebResponse = myWebRequest.GetResponse();
        Stream receivingStream = myWebResponse.GetResponseStream();

        Processor htmlProcessor = new Processor();

        // Load the stream into Processor instance.
        htmlProcessor.LoadFromStream(receivingStream, Global.DefaultEncoding);

        ProcessElementDelegate del = new ProcessElementDelegate(ProcessDelegate);

        RuleSet rules = new RuleSet();

        // Add HTML processing rules.
        rules.AddTagProcessingCondition("img", null);
        rules.AddTagProcessingCondition("br", null);

        // Process the delegate and the rules.
        htmlProcessor.Dom.Process(rules, del);

        // Save the resulting HTML to disk.
        FileStream outStream = new FileStream(@"C:\Temp\afterlogic.html", FileMode.Create, FileAccess.Write, FileShare.None);

        htmlProcessor.SaveToStream(outStream, Global.DefaultEncoding);
        outStream.Close();
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports System.Net
Imports MailBee
Imports MailBee.Html

Module Sample
    ' The delegate is used for processing of the HTML source.
    ' All IMG tags will be removed and all BR tags will be replaced with HR tags.
    Function ProcessDelegate(ByVal elem As Element, ByVal rule As Rule) As Boolean
        Select Case (elem.TagName.ToLower())
            Case "img"
                elem.Remove()
            Case "br"
                elem.TagName = "hr"
                Return False
        End Select
        Return True
    End Function

    Sub Main()
        ' Create a new stream and load the HTML document into it.
        Dim myWebRequest As WebRequest = WebRequest.Create("http://www.afterlogic.com")
        Dim myWebResponse As WebResponse = myWebRequest.GetResponse()
        Dim receivingStream As Stream = myWebResponse.GetResponseStream()

        Dim htmlProcessor As New Processor

        ' Load the stream into Processor instance.
        htmlProcessor.LoadFromStream(receivingStream, Global.DefaultEncoding)

        Dim del As ProcessElementDelegate = AddressOf ProcessDelegate

        Dim rules As New RuleSet

        ' Add HTML processing rules.
        rules.AddTagProcessingCondition("img", Nothing)
        rules.AddTagProcessingCondition("br", Nothing)

        ' Process the delegate and the rules.
        htmlProcessor.Dom.Process(rules, del)

        ' Save the resulting HTML to disk.
        Dim outStream As FileStream = New FileStream("C:\Temp\afterlogic.html", FileMode.Create, FileAccess.Write, FileShare.None)

        htmlProcessor.SaveToStream(outStream, Global.DefaultEncoding)
        outStream.Close()
    End Sub
End Module
See Also

Reference

RuleSet Class
MailBee.Html Namespace
ElementProcess(RuleSet, ProcessElementDelegate)


RuleSet.AddTagProcessingRule Method

RuleSetAddTagProcessingRule Method
Adds a rule for changing attributes of HTML tags.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddTagProcessingRule(
    string tagName,
    TagAttributeCollection tagAttrs,
    TagAttributeCollection attrsToAdd,
    TagAttributeCollection attrsToRemove,
    bool replaceMode
)
Public Sub AddTagProcessingRule (
    tagName As String,
    tagAttrs As TagAttributeCollection,
    attrsToAdd As TagAttributeCollection,
    attrsToRemove As TagAttributeCollection,
    replaceMode As Boolean
)

Parameters

tagName
Type: SystemString
The name of the tag for which to change the attributes. Case-insensitive.
tagAttrs
Type: MailBee.HtmlTagAttributeCollection
The list of attributes any of which must exist in the definition of tagName tags in order to trigger the rule's action, or a null reference (Nothing in Visual Basic) to apply the rule for any tags with tagName name (regardless of which attributes they have).
attrsToAdd
Type: MailBee.HtmlTagAttributeCollection
The list of attributes to be added to the tagName tag. Can be a null reference if replaceMode is false.
attrsToRemove
Type: MailBee.HtmlTagAttributeCollection
The list of attributes to be removed from the tagName tag. Can be a null reference if replaceMode is false.
replaceMode
Type: SystemBoolean
If true, attrsToRemove attributes will be replaced with attrsToAdd ones; otherwise, attrsToRemove attributes will simply be removed and attrsToAdd ones will be added.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | tagName is a null reference (Nothing in Visual Basic) or an empty string, or replaceMode is true and attrsToAdd does not match attrsToRemove.
Remarks

The condition when this rule satisfies is the same as for ProcessingCondition rule (created with AddTagProcessingCondition(String, TagAttributeCollection) method). See AddTagProcessingCondition(String, TagAttributeCollection) topic for the details which apply to the HTML processing rules of all types.

Once the matching tag was found and the delegate (if any) returned true, the processing continues as follows (depending on replaceMode value):

  • If replaceMode is false, MailBee searches for any attrsToRemove attributes in the tag definition and removes them. attrsToAdd attributes are added. Any of these actions are optional (and thus attrsToAdd or attrsToRemove can be empty).
  • If replaceMode is true, MailBee compares lengths of attrsToAdd and attrsToRemove collections. If they are equal, MailBee will then iterate through every attribute of the tag and if it finds such attribute in attrsToRemove (let's say, at index i), it replaces i-th attribute in attrsToRemove with i-th attribute in attrsToAdd. In other words, attributes A, B and C will be replaced with X, Y and Z correspondingly. If lengths of attrsToAdd and attrsToRemove are not equal but attrsToAdd length is 1, any attributes contained in attrsToRemove will be replaced with the attribute in attrsToAdd. In other words, attributes A, B and C will be replaced with X, X and X correspondingly. Otherwise (attrsToAdd and/or attrsToRemove is a null reference or their lengths do not match), MailBee will throw an exception.
Note Note
tagAttrs collection is not related with attrsToAdd or attrsToRemove in any way. tagAttrs only specifies attributes any of which the tagName tag must have in order to satisfy the rule condition. However, tagAttrs is not used later when the rule action begins.
Examples
This sample change the background color of the HTML page to black.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using System.Net;
using MailBee;
using MailBee.Html;

class Sample
{
    static void Main(string[] args)
    {
        // Create new stream with an HTML markup.
        WebRequest myWebRequest = WebRequest.Create("http://www.afterlogic.com");
        WebResponse myWebResponse = myWebRequest.GetResponse();
        Stream receivingStream = myWebResponse.GetResponseStream();

        Processor htmlProcessor = new Processor();

        htmlProcessor.LoadFromStream(receivingStream, Global.DefaultEncoding);

        RuleSet rules = new RuleSet();

        // Create new rule for processing.
        TagAttributeCollection attributes = new TagAttributeCollection();
        TagAttribute attribute = new TagAttribute();
        attribute.Definition = "bgcolor = 'black'";

        attributes.Add(attribute);

        rules.AddTagRemovalRule("link", null);
        rules.AddTagProcessingRule("body", null, attributes, null, false);

        // Processing of the rule.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, null));
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports System.IO
Imports System.Net
Imports MailBee
Imports MailBee.Html

Module Sample
    Sub Main()
        ' Create new stream with an HTML markup.
        Dim myWebRequest As WebRequest = WebRequest.Create("http://www.afterlogic.com")
        Dim myWebResponse As WebResponse = myWebRequest.GetResponse()
        Dim receivingStream As Stream = myWebResponse.GetResponseStream()

        Dim htmlProcessor As New Processor

        htmlProcessor.LoadFromStream(receivingStream, Global.DefaultEncoding)

        Dim rules As New RuleSet

        ' Create new rule for processing.
        Dim attributes As TagAttributeCollection = New TagAttributeCollection
        Dim attribute As TagAttribute = New TagAttribute
        attribute.Definition = "bgcolor = 'black'"

        attributes.Add(attribute)

        rules.AddTagRemovalRule("link", Nothing)
        rules.AddTagProcessingRule("body", Nothing, attributes, Nothing, False)

        ' Processing of the rule.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, Nothing))
    End Sub
End Module
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet.AddTagRemovalRule Method

RuleSetAddTagRemovalRule Method
Adds a rule for removing tags with the given name and attributes.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddTagRemovalRule(
    string tagName,
    TagAttributeCollection tagAttrs
)
Public Sub AddTagRemovalRule (
    tagName As String,
    tagAttrs As TagAttributeCollection
)

Parameters

tagName
Type: SystemString
The name of the tag to be removed. Case-insensitive.
tagAttrs
Type: MailBee.HtmlTagAttributeCollection
The list of attributes any of which must exist in the definition of tagName tags in order to trigger the rule's action, or a null reference (Nothing in Visual Basic) to apply the rule for any tags with tagName name (regardless of which attributes they have).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | tagName is a null reference (Nothing in Visual Basic) or an empty string.
Remarks

The condition when this rule satisfies is the same as for ProcessingCondition rule (created with AddTagProcessingCondition(String, TagAttributeCollection) method). See AddTagProcessingCondition(String, TagAttributeCollection) topic for the details which apply to the HTML processing rules of all types.

The action for this rule removes the matching tag with all its inner contents.

Examples
This sample removes all images from the HTML e-mail.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee.Mime;
using MailBee.Html;

class Sample
{
    static void Main(string[] args)
    {
        // Load HTML message from file.
        MailMessage message = new MailMessage();
        message.LoadMessage(@"C:\Temp\message.eml");

        Processor htmlProcessor = new Processor();

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText;

        RuleSet rules = new RuleSet();

        rules.AddTagRemovalRule("img", null);

        htmlProcessor.Dom.Process(rules, null);

        // Process the rule and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, null));
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports MailBee.Mime
Imports MailBee.Html

Module Sample
    Sub Main()
        ' Load HTML message from file.
        Dim message As New MailMessage
        message.LoadMessage("C:\Temp\message.eml")

        Dim htmlProcessor As New Processor

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText

        Dim rules As New RuleSet

        rules.AddTagRemovalRule("img", Nothing)

        htmlProcessor.Dom.Process(rules, Nothing)

        ' Process the rule and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, Nothing))
    End Sub
End Module
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet.AddTagReplacementRule Method

RuleSetAddTagReplacementRule Method
Overload List
Name | Description
AddTagReplacementRule(String, TagAttributeCollection, Element) | Adds a rule for replacing certain tags with the specified replacement element.
AddTagReplacementRule(String, TagAttributeCollection, String, Boolean) | Adds a rule for replacing certain tags with the specified replacement string.
Top
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet.AddTagReplacementRule Method (String, TagAttributeCollection, Element)

RuleSetAddTagReplacementRule Method (String, TagAttributeCollection, Element)
Adds a rule for replacing certain tags with the specified replacement element.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddTagReplacementRule(
    string tagName,
    TagAttributeCollection tagAttrs,
    Element replacement
)
Public Sub AddTagReplacementRule (
    tagName As String,
    tagAttrs As TagAttributeCollection,
    replacement As Element
)

Parameters

tagName
Type: SystemString
The name of the tag to be replaced. Case-insensitive.
tagAttrs
Type: MailBee.HtmlTagAttributeCollection
The list of attributes any of which must exist in the definition of tagName tags in order to trigger the rule's action, or a null reference (Nothing in Visual Basic) to apply the rule for any tags with tagName name (regardless of which attributes they have).
replacement
Type: MailBee.HtmlElement
The element which will replace the original element.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | tagName is a null reference (Nothing in Visual Basic) or an empty string, or replacement is a null reference.
Remarks

The condition when this rule satisfies is the same as for ProcessingCondition rule (created with AddTagProcessingCondition(String, TagAttributeCollection) method). See AddTagProcessingCondition(String, TagAttributeCollection) topic for the details which apply to the HTML processing rules of all types.

The action for this rule removes the matching tag with all its inner contents and puts the replacement tag at the same position in the document.

Examples
This sample replaces all of tables with HTML comments in the HTML source.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee.Mime;
using MailBee.Html;

class Sample
{
    static void Main(string[] args)
    {
        // Load HTML message from file.
        MailMessage message = new MailMessage();
        message.LoadMessage(@"C:\Temp\message.eml");

        Processor htmlProcessor = new Processor();

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText;

        RuleSet rules = new RuleSet();

        Element elem = new Element();
        elem.TagName = "!--table was here--";

        rules.AddTagReplacementRule("table", null, elem);

        htmlProcessor.Dom.Process(rules, null);

        // Process the rule and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, null));
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports MailBee.Mime
Imports MailBee.Html

Module Sample
    Sub Main()
        ' Load HTML message from file.
        Dim message As New MailMessage
        message.LoadMessage("C:\Temp\message.eml")

        Dim htmlProcessor As New Processor

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText

        Dim rules As New RuleSet

        Dim elem As New Element
        elem.TagName = "!--table was here--"

        rules.AddTagReplacementRule("table", Nothing, elem)

        htmlProcessor.Dom.Process(rules, Nothing)

        ' Process the rule and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, Nothing))
    End Sub
End Module
See Also

Reference

RuleSet Class
AddTagReplacementRule Overload
MailBee.Html Namespace


RuleSet.AddTagReplacementRule Method (String, TagAttributeCollection, String, Boolean)

RuleSetAddTagReplacementRule Method (String, TagAttributeCollection, String, Boolean)
Adds a rule for replacing certain tags with the specified replacement string.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddTagReplacementRule(
    string tagName,
    TagAttributeCollection tagAttrs,
    string replacement,
    bool replaceTagDefinitionOnly
)
Public Sub AddTagReplacementRule (
    tagName As String,
    tagAttrs As TagAttributeCollection,
    replacement As String,
    replaceTagDefinitionOnly As Boolean
)

Parameters

tagName
Type: SystemString
The name of the tag to be replaced. Case-insensitive.
tagAttrs
Type: MailBee.HtmlTagAttributeCollection
The list of attributes any of which must exist in the definition of tagName tags in order to trigger the rule's action, or a null reference (Nothing in Visual Basic) to apply the rule for any tags with tagName name (regardless of which attributes they have).
replacement
Type: SystemString
The string which will replace TagDefinition or OuterHtml of the the original element.
replaceTagDefinitionOnly
Type: SystemBoolean
If true, only the tag definition (opening tag and closing tag if any) will be replaced; otherwise, the entire Element with all inner contents will be replaced.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | tagName is a null reference (Nothing in Visual Basic) or an empty string, or replacement is a null reference (or an empty string if replaceTagDefinitionOnly is true).
Remarks

The condition when this rule satisfies is the same as for ProcessingCondition rule (created with AddTagProcessingCondition(String, TagAttributeCollection) method). See AddTagProcessingCondition(String, TagAttributeCollection) topic for the details which apply to the HTML processing rules of all types.

The action for this rule replaces the matching tag either completely (OuterHtml gets replaced) or partially (only TagDefinition gets replaced) depending on replaceTagDefinitionOnly value. If replaceTagDefinitionOnly is true, this rule simply renames the matching tags removing the original name and attributes with supplied ones while leaving InnerHtml intact.

Examples
This sample replaces BR tag definitions with HR tag definitions.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee.Mime;
using MailBee.Html;

class Sample
{
    static void Main(string[] args)
    {
        // Load HTML message from file.
        MailMessage message = new MailMessage();
        message.LoadMessage(@"C:\Temp\message.eml");

        Processor htmlProcessor = new Processor();

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText;

        RuleSet rules = new RuleSet();

        rules.AddTagReplacementRule("br", null, "hr", true);

        htmlProcessor.Dom.Process(rules, null);

        // Process the rule and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, null));
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports MailBee.Mime
Imports MailBee.Html

Module Sample
    Sub Main()
        ' Load HTML message from file.
        Dim message As New MailMessage
        message.LoadMessage("C:\Temp\message.eml")

        Dim htmlProcessor As New Processor

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText

        Dim rules As New RuleSet

        rules.AddTagReplacementRule("br", Nothing, "hr", True)

        htmlProcessor.Dom.Process(rules, Nothing)

        ' Process the rule and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, Nothing))
    End Sub
End Module
See Also

Reference

RuleSet Class
AddTagReplacementRule Overload
MailBee.Html Namespace


RuleSet.GetSafeHtmlRules Method

RuleSetGetSafeHtmlRules Method
Returns a set of rules which specify removing of all potentially unsafe content from the HTML document.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static RuleSet GetSafeHtmlRules()
Public Shared Function GetSafeHtmlRules As RuleSet

Return Value

Type: RuleSet
A RuleSet object containing the rules which cause all potentially unsafe content be removed during processing.
Remarks
If you pass the returned object to Process(RuleSet, ProcessElementDelegate) or ProcessToString(RuleSet, ProcessElementDelegate) method, it will perform the following actions:
  • remove <SCRIPT>...</SCRIPT> tags with all their contents
  • remove <IFRAME>...</IFRAME> tags with all their contents
  • remove <BGSOUND> tags
  • remove <EMBED> tags
  • remove <FRAME> tags
  • remove <FRAMESET>...</FRAMESET> tags with all their contents
  • remove <OBJECT>...</OBJECT> tags with all their contents
  • remove <APPLET>...</APPLET> tags with all their contents
  • remove SRC/LOWSRC attributes from <IMG> and <INPUT> tags if these attributes contain scripts (i.e. the attribute value starts with javascript, vbscript or about)
  • remove HREF attribute from <A> tags if this attribute contains scripts
  • remove contenteditable attribute from any tag
  • remove data* (e.g. dataSrc) attributes from any tag
  • remove on* (e.g. onclick) attributes from any tag
Examples
This sample applies the safe-HTML rules to clean up the HTML message.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee.Mime;
using MailBee.Html;

class Sample
{
    static void Main(string[] args)
    {
        // Load HTML message from file.
        MailMessage message = new MailMessage();
        message.LoadMessage(@"C:\Temp\message.eml");

        Processor htmlProcessor = new Processor();

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText;

        // Get rules for removing all uneasy things (such as scripts) from the body.
        RuleSet rules = RuleSet.GetSafeHtmlRules();

        // Process the rules and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, null));
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports MailBee.Mime
Imports MailBee.Html

Module Sample
    Sub Main()
        ' Load HTML message from file.
        Dim message As New MailMessage
        message.LoadMessage("C:\Temp\message.eml")

        Dim htmlProcessor As New Processor

        htmlProcessor.Dom.OuterHtml = message.BodyHtmlText

        ' Get rules for removing all uneasy things (such as scripts) from the body.
        Dim rules As RuleSet = RuleSet.GetSafeHtmlRules()

        ' Process the rules and display the results.
        Console.WriteLine(htmlProcessor.Dom.ProcessToString(rules, Nothing))
    End Sub
End Module
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet Properties

RuleSet Properties

The RuleSet type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the Rule object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

RuleSet Class
MailBee.Html Namespace


RuleSet.Item Property

RuleSetItem Property
Gets the Rule object at the specified zero-based index in the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Rule this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Rule
    Get

Parameters

index
Type: SystemInt32
The zero-based index number of the attachment in the collection.

Property Value

Type: Rule
An Rule object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

RuleSet Class
MailBee.Html Namespace


TagAttribute Class

TagAttribute Class
Represents an attribute of an HTML tag.
Inheritance Hierarchy
SystemObject
MailBee.HtmlTagAttribute

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TagAttribute
Public Class TagAttribute

The TagAttribute type exposes the following members.

Constructors
 | Name | Description
Public method | TagAttribute | Initializes a new instance of the TagAttribute class
Public method | TagAttribute(String) | Initializes a new instance of TagAttribute object with the specified attribute definition.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetProtocol | Gets the protocol of the HTML attribute value.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Remove | Removes this attribute from the HTML tag definition.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Definition | Gets or sets the definition of the HTML tag attribute.
Public property | Name | Gets or sets the name of the HTML tag attribute.
Public property | Value | Gets or sets the value of the HTML tag attribute.
Top
Remarks
To access attributes of an HTML Element, use Attributes property.
Examples
The example is available in AddTagProcessingRule(String, TagAttributeCollection, TagAttributeCollection, TagAttributeCollection, Boolean) topic.
See Also

Reference

MailBee.Html Namespace


TagAttribute Constructor

TagAttribute Constructor
Overload List
 | Name | Description
Public method | TagAttribute | Initializes a new instance of the TagAttribute class
Public method | TagAttribute(String) | Initializes a new instance of TagAttribute object with the specified attribute definition.
Top
See Also

Reference

TagAttribute Class
MailBee.Html Namespace


TagAttribute Constructor

TagAttribute Constructor
Initializes a new instance of the TagAttribute class

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttribute()
Public Sub New
See Also

Reference

TagAttribute Class
TagAttribute Overload
MailBee.Html Namespace


TagAttribute Constructor (String)

TagAttribute Constructor (String)
Initializes a new instance of TagAttribute object with the specified attribute definition.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttribute(
    string attribute
)
Public Sub New (
    attribute As String
)

Parameters

attribute
Type: SystemString
The definition of the HTML tag attribute.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attribute is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
attribute examples: img="picture.gif", TYPE=BUTTON, SELECTED, onclick='javascript:void(0)'.
See Also

Reference

TagAttribute Class
TagAttribute Overload
MailBee.Html Namespace


TagAttribute Methods

TagAttribute Methods

The TagAttribute type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetProtocol | Gets the protocol of the HTML attribute value.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Remove | Removes this attribute from the HTML tag definition.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TagAttribute Class
MailBee.Html Namespace


TagAttribute.GetProtocol Method

TagAttributeGetProtocol Method
Gets the protocol of the HTML attribute value.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetProtocol()
Public Function GetProtocol As String

Return Value

Type: String
The string containing the protocol name (http, javascript, about, etc), or an empty string if there is no protocol name in the attribute value.
See Also

Reference

TagAttribute Class
MailBee.Html Namespace


TagAttribute.Remove Method

TagAttributeRemove Method
Removes this attribute from the HTML tag definition.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Remove()
Public Sub Remove
See Also

Reference

TagAttribute Class
MailBee.Html Namespace


TagAttribute Properties

TagAttribute Properties

The TagAttribute type exposes the following members.

Properties
 | Name | Description
Public property | Definition | Gets or sets the definition of the HTML tag attribute.
Public property | Name | Gets or sets the name of the HTML tag attribute.
Public property | Value | Gets or sets the value of the HTML tag attribute.
Top
See Also

Reference

TagAttribute Class
MailBee.Html Namespace


TagAttribute.Definition Property

TagAttributeDefinition Property
Gets or sets the definition of the HTML tag attribute.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Definition { get; set; }
Public Property Definition As String
    Get
    Set

Property Value

Type: String
The definition of the HTML tag attribute.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic) or an empty string.
Remarks
See Value topic for examples of attribute definitions.
See Also

Reference

TagAttribute Class
MailBee.Html Namespace
TagAttributeValue


TagAttribute.Name Property

TagAttributeName Property
Gets or sets the name of the HTML tag attribute.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; set; }
Public Property Name As String
    Get
    Set

Property Value

Type: String
The name of the HTML attribute.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic) or an empty string.
See Also

Reference

TagAttribute Class
MailBee.Html Namespace


TagAttribute.Value Property

TagAttributeValue Property
Gets or sets the value of the HTML tag attribute.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Value { get; set; }
Public Property Value As String
    Get
    Set

Property Value

Type: String
A string with the value of the HTML attribute, or a null reference if this attribute has no value at all.
Remarks
Definition of an attribute with a value looks like name=value or name="value" or name='value'. Definition of an attribute without a value looks like name.
See Also

Reference

TagAttribute Class
MailBee.Html Namespace
TagAttributeDefinition


TagAttributeCollection Class

TagAttributeCollection Class
Provides properties and methods for managing and examining the collection of TagAttribute objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.HtmlTagAttributeCollection

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TagAttributeCollection : CollectionBase
Public Class TagAttributeCollection
    Inherits CollectionBase

The TagAttributeCollection type exposes the following members.

Constructors
 | Name | Description
Public method | TagAttributeCollection | Initializes a new instance of the TagAttributeCollection class
Top
Methods
 | Name | Description
Public method | Add(TagAttribute) | Adds the specified TagAttribute object to the collection.
Public method | Add(TagAttribute, Int32) | Adds the specified TagAttribute object to the collection at the specified index.
Public method | AddRange(TagAttributeCollection) | Adds all attributes from the TagAttributeCollection object.
Public method | AddRange(TagAttributeCollection, Int32, Int32, Int32) | Adds elements from the TagAttributeCollection object with specified range.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove | Removes the specified TagAttribute object from the collection.
Public method | RemoveAll | Removes all attributes from the collection.
Public method | RemoveAt | Removes the TagAttribute object having the the specified zero-based index from the collection.
Public method | RemoveByName | Removes all attributes having the specified name from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the TagAttribute object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

To access attributes of an HTML Element, use Attributes property.

To define a list of HTML attributes (for instance, when creating an HTML processing rule using RuleSet class methods), use TagAttributeCollection constructor to create the collection, then create attributes using TagAttribute constructor, set their definitions or names with Definition or Name properties, and add them to the collection using Add(TagAttribute) method.

Examples
The example is available in AddTagProcessingRule(String, TagAttributeCollection, TagAttributeCollection, TagAttributeCollection, Boolean) topic.
See Also

Reference

MailBee.Html Namespace


TagAttributeCollection Constructor

TagAttributeCollection Constructor
Initializes a new instance of the TagAttributeCollection class

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttributeCollection()
Public Sub New
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeCollection Methods

TagAttributeCollection Methods

The TagAttributeCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add(TagAttribute) | Adds the specified TagAttribute object to the collection.
Public method | Add(TagAttribute, Int32) | Adds the specified TagAttribute object to the collection at the specified index.
Public method | AddRange(TagAttributeCollection) | Adds all attributes from the TagAttributeCollection object.
Public method | AddRange(TagAttributeCollection, Int32, Int32, Int32) | Adds elements from the TagAttributeCollection object with specified range.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove | Removes the specified TagAttribute object from the collection.
Public method | RemoveAll | Removes all attributes from the collection.
Public method | RemoveAt | Removes the TagAttribute object having the the specified zero-based index from the collection.
Public method | RemoveByName | Removes all attributes having the specified name from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeCollection.Add Method

TagAttributeCollectionAdd Method
Overload List
 | Name | Description
Public method | Add(TagAttribute) | Adds the specified TagAttribute object to the collection.
Public method | Add(TagAttribute, Int32) | Adds the specified TagAttribute object to the collection at the specified index.
Top
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeCollection.Add Method (TagAttribute)

TagAttributeCollectionAdd Method (TagAttribute)
Adds the specified TagAttribute object to the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    TagAttribute attr
)
Public Sub Add (
    attr As TagAttribute
)

Parameters

attr
Type: MailBee.HtmlTagAttribute
The TagAttribute object to be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attr is a null reference (Nothing in Visual Basic).
See Also

Reference

TagAttributeCollection Class
Add Overload
MailBee.Html Namespace


TagAttributeCollection.Add Method (TagAttribute, Int32)

TagAttributeCollectionAdd Method (TagAttribute, Int32)
Adds the specified TagAttribute object to the collection at the specified index.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    TagAttribute attr,
    int index
)
Public Sub Add (
    attr As TagAttribute,
    index As Integer
)

Parameters

attr
Type: MailBee.HtmlTagAttribute
The TagAttribute object to be added to the collection.
index
Type: SystemInt32
The zero-based index where to insert the specified TagAttribute object in the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attr is a null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | The specified index is not valid.
See Also

Reference

TagAttributeCollection Class
Add Overload
MailBee.Html Namespace


TagAttributeCollection.AddRange Method

TagAttributeCollectionAddRange Method
Adds multiple attributes to the collection.
Overload List
 | Name | Description
Public method | AddRange(TagAttributeCollection) | Adds all attributes from the TagAttributeCollection object.
Public method | AddRange(TagAttributeCollection, Int32, Int32, Int32) | Adds elements from the TagAttributeCollection object with specified range.
Top
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeCollection.AddRange Method (TagAttributeCollection)

TagAttributeCollectionAddRange Method (TagAttributeCollection)
Adds all attributes from the TagAttributeCollection object.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddRange(
    TagAttributeCollection attrs
)
Public Sub AddRange (
    attrs As TagAttributeCollection
)

Parameters

attrs
Type: MailBee.HtmlTagAttributeCollection
The attributes from TagAttributeCollection object to be added.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attrs is a null reference (Nothing in Visual Basic).
See Also

Reference

TagAttributeCollection Class
AddRange Overload
MailBee.Html Namespace


TagAttributeCollection.AddRange Method (TagAttributeCollection, Int32, Int32, Int32)

TagAttributeCollectionAddRange Method (TagAttributeCollection, Int32, Int32, Int32)
Adds elements from the TagAttributeCollection object with specified range.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddRange(
    TagAttributeCollection attrs,
    int srcIndex,
    int count,
    int destIndex
)
Public Sub AddRange (
    attrs As TagAttributeCollection,
    srcIndex As Integer,
    count As Integer,
    destIndex As Integer
)

Parameters

attrs
Type: MailBee.HtmlTagAttributeCollection
The source TagAttributeCollection to add elements from.
srcIndex
Type: SystemInt32
The zero-based index in attrs collection from which to copy the attributes.
count
Type: SystemInt32
Number of attributes to be added from attrs collection.
destIndex
Type: SystemInt32
The zero-based index in the current collection where to insert the first attribute from the copied range.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attrs is a null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | The specified index is not valid.
See Also

Reference

TagAttributeCollection Class
AddRange Overload
MailBee.Html Namespace


TagAttributeCollection.Remove Method

TagAttributeCollectionRemove Method
Removes the specified TagAttribute object from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    TagAttribute attr
)
Public Function Remove (
    attr As TagAttribute
) As Boolean

Parameters

attr
Type: MailBee.HtmlTagAttribute
The TagAttribute to be removed from the collection.

Return Value

Type: Boolean
true if the specified TagAttribute was found and removed; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attr is a null reference (Nothing in Visual Basic).
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace
TagAttributeCollectionRemoveAt(Int32)
TagAttributeCollectionRemoveByName(String)


TagAttributeCollection.RemoveAll Method

TagAttributeCollectionRemoveAll Method
Removes all attributes from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAll()
Public Sub RemoveAll
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeCollection.RemoveAt Method

TagAttributeCollectionRemoveAt Method
Removes the TagAttribute object having the the specified zero-based index from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index of TagAttribute to be removed from the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace
TagAttributeCollectionRemove(TagAttribute)
TagAttributeCollectionRemoveByName(String)


TagAttributeCollection.RemoveByName Method

TagAttributeCollectionRemoveByName Method
Removes all attributes having the specified name from the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveByName(
    string attrName
)
Public Sub RemoveByName (
    attrName As String
)

Parameters

attrName
Type: SystemString
The name of the attribute (case-insensitive) to be removed from the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attrName is a null reference (Nothing in Visual Basic).
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace
TagAttributeCollectionRemove(TagAttribute)
TagAttributeCollectionRemoveAt(Int32)


TagAttributeCollection Properties

TagAttributeCollection Properties

The TagAttributeCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the TagAttribute object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeCollection.Item Property

TagAttributeCollectionItem Property
Gets or sets the TagAttribute object at the specified zero-based index in the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttribute this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As TagAttribute
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index number of the attribute in the collection.

Property Value

Type: TagAttribute
A TagAttribute object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

TagAttributeCollection Class
MailBee.Html Namespace


TagAttributeReadOnlyCollection Class

TagAttributeReadOnlyCollection Class
Provides properties and methods for examining the collection of TagAttribute objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.HtmlTagAttributeReadOnlyCollection

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TagAttributeReadOnlyCollection : CollectionBase
Public Class TagAttributeReadOnlyCollection
    Inherits CollectionBase

The TagAttributeReadOnlyCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the TagAttribute object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.Html Namespace


TagAttributeReadOnlyCollection Methods

TagAttributeReadOnlyCollection Methods

The TagAttributeReadOnlyCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TagAttributeReadOnlyCollection Class
MailBee.Html Namespace


TagAttributeReadOnlyCollection Properties

TagAttributeReadOnlyCollection Properties

The TagAttributeReadOnlyCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the TagAttribute object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

TagAttributeReadOnlyCollection Class
MailBee.Html Namespace


TagAttributeReadOnlyCollection.Item Property

TagAttributeReadOnlyCollectionItem Property
Gets the TagAttribute object at the specified zero-based index in the collection.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TagAttribute this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As TagAttribute
    Get

Parameters

index
Type: SystemInt32
The zero-based index number of the attribute in the collection.

Property Value

Type: TagAttribute
A TagAttribute object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

TagAttributeReadOnlyCollection Class
MailBee.Html Namespace


TagRuleTypes Enumeration

TagRuleTypes Enumeration
Defines the available modes of processing of an HTML tag for the Rule object.

Namespace: MailBee.Html
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum TagRuleTypes
Public Enumeration TagRuleTypes
Members
Member name | Value | Description
ProcessingCondition | 0 | Just execute the delegate.
ProcessingRule | 1 | Execute the delegate (if defined). If the delegate returned true or was not defined, process the HTML element.
RemovalRule | 2 | Execute the delegate (if defined). If the delegate returned true or was not defined, remove the HTML element with its inner contents.
ReplacementRule | 3 | Execute the delegate (if defined). If the delegate returned true or was not defined, replace the HTML element with another tag definition or entire HTML element. The degree of the replacement (replace just the tag defintion or the entire tag including its inner contents) depends on the rule settings.
Remarks

These modes define actions to be performed when Process(RuleSet, ProcessElementDelegate) method encounters HTML tag matching certain Rule in the RuleSet (denoted by rules parameter).

Rules of all types cause execution of the delegate when their conditions are met. Rules of all types except ProcessingCondition honor returned value of the delegate and do not apply the rule if the delegate returned false. ProcessingCondition does not do anything itself anyway and thus returned value is not important.

The delegate will only be executed if it was defined (del parameter of Process(RuleSet, ProcessElementDelegate) method is not a null reference).

The above also applies to ProcessToString(RuleSet, ProcessElementDelegate) method in the same way as to Process(RuleSet, ProcessElementDelegate) method.

Examples
The example is available in AddTagProcessingCondition(String, TagAttributeCollection) topic.
See Also

Reference

MailBee.Html Namespace
RuleSetAddTagProcessingCondition(String, TagAttributeCollection)
RuleSetAddTagProcessingRule(String, TagAttributeCollection, TagAttributeCollection, TagAttributeCollection, Boolean)
RuleSetAddTagRemovalRule(String, TagAttributeCollection)
RuleSetAddTagReplacementRule(String, TagAttributeCollection, Element)


MailBee.ImapMail Namespace

MailBee.ImapMail Namespace

MailBee.ImapMail namespace contains classes and enumerations which can be used by your applications to manipulate mails and folders on an IMAP4 server. This includes downloading messages and IMAP4 envelopes (including customized download of certain parts of messages), uploading, deleting, copying and moving messages between folders, setting flags, search for messages matching the given criteria, folders management, sending custom commands to the server, authenticating using secure methods, and more.

MailBee supports a number of IMAP4 extensions which increase performance and expand the set of available features.

ImapMail.Imap (main class of this namespace) is declared as a component, which means you can also just drop it onto your application form instead of creating an instance in the code.

"Quick" methods are also supported, which allows you to download mail from the server in a single line of code.

The component has built-in support for secure connections (TLS/SSL) and proxy servers (SOCKS4/SOCKS5/HTTP).

In UWP apps, use async methods. This platform has very limited sync I/O support.

Classes
 | Class | Description
 | Envelope | Represents an IMAP4 envelope of a mail message (including any other related information such as body structure, message flags, the mail message itself, etc).
Public class | EnvelopeCollection | Provides properties and methods for examining, extending, and reversing the collection of the Envelope objects.
Public class | Folder | Represents a folder (mailbox in IMAP4 terms) of the account on the mail server.
Public class | FolderCollection | Provides properties and methods for examining the collection of the Folder objects.
Public class | FolderQuota | Represents a resource usage and quota indicator for the entire account or a single folder of this account.
Public class | FolderStatus | Provides properties used to examine the status of a single folder of the mail account.
 | Imap | Provides properties and methods for connecting to an IMAP4 server, downloading, searching, and managing folders and e-mail messages in a user account.
Public class | ImapBodyStructure | Represents a structure of a MIME part of a mail message.
Public class | ImapBodyStructureCollection | Provides properties and methods for examining the collection of the ImapBodyStructure objects.
Public class | ImapEnvelopeDataChunkReceivedEventArgs | Contains the event data for EnvelopeDataChunkReceived event.
Public class | ImapEnvelopeDownloadedEventArgs | Contains the event data for EnvelopeDownloaded event.
Public class | ImapIdlingEventArgs | Contains the event data for Idling event.
Public class | ImapMessageStatusEventArgs | Contains the event data for MessageStatus event.
Public class | ImapNamespace | Represents the description of a single IMAP namespace.
Public class | ImapNamespaceCollection | Provides properties and methods for examining the collection of ImapNamespace objects.
Public class | ImapNamespaceCollectionSet | Provides access to the lists of namespaces defined for the current e-mail account.
Public class | ImapServerStatusEventArgs | Contains the event data for ServerStatus event.
Public class | ImapUtils | Provides static methods useful for processing IMAP4 strings, dates, folder names, etc.
Public class | MailBeeImapInvalidEnvelopeException | The exception that is thrown when MailBee encounters FETCH response which could not be completely parsed.
Public class | MailBeeImapLoginBadCredentialsException | The exception that is thrown when the IMAP server reports the given user account name and/or password is incorrect.
Public class | MailBeeImapLoginBadMethodException | The exception that is thrown when the IMAP server reports the given SASL authentication method is not supported and use of another authentication methods is not allowed by the application.
Public class | MailBeeImapLoginNegativeResponseException | An abstract parent for all exceptions which indicate the IMAP server replied with a negative response during authentication of the user.
Public class | MailBeeImapMessageIndexNotFoundException | The exception that is thrown when the message with the specified index cannot be downloaded because this index does not correspond to any message in the currently selected folder on the server.
Public class | MailBeeImapNegativeResponseException | The exception that is thrown when the IMAP server responds with a negative reply (i.e. "BAD" or "NO").
Public class | MailBeeImapResponseNotFoundException | The exception that is thrown when the IMAP server did not return the expected response.
Public class | MessageFlagSet | Represents a set of flags of a mail message.
Public class | MessageIndexCollection | Represents an abstract list of indices (such as ordinal message numbers or UIDs) of mail messages.
Public class | MessageNumberCollection | Represents a list of ordinal message numbers of mail messages.
Public class | UidCollection | Represents a list of UIDs of mail messages.
Public class | UidPlusResult | Represents a set of UIDs assigned to the copied or uploaded messages and other related information returned by the IMAP4 server which supports UIDPLUS extension.
Delegates
 | Delegate | Description
Public delegate | ImapEnvelopeDataChunkReceivedEventHandler | Represents the method that will handle EnvelopeDataChunkReceived event.
Public delegate | ImapEnvelopeDownloadedEventHandler | Represents the method that will handle EnvelopeDownloaded event.
Public delegate | ImapIdlingEventHandler | Represents the method that will handle Idling event.
Public delegate | ImapMessageStatusEventHandler | Represents the method that will handle MessageStatus event.
Public delegate | ImapServerStatusEventHandler | Represents the method that will handle ServerStatus event.
Enumerations
 | Enumeration | Description
Public enumeration | EnvelopeParts | Defines message elements available for download using DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.
Public enumeration | FolderFlags | Defines the standard flags which can be set or examined for IMAP4 folders (mailboxes).
Public enumeration | MessageFlagAction | Defines actions to be performed with the message flags.
Public enumeration | SystemMessageFlags | Defines the standard (system) flags which can be set or examined for mail messages in the folder.


ImapEnvelopeDataChunkReceivedEventArgs Class

ImapEnvelopeDataChunkReceivedEventArgs Class
Contains the event data for EnvelopeDataChunkReceived event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.ImapMailImapEnvelopeDataChunkReceivedEventArgs

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapEnvelopeDataChunkReceivedEventArgs : CommonEventArgs
Public Class ImapEnvelopeDataChunkReceivedEventArgs
    Inherits CommonEventArgs

The ImapEnvelopeDataChunkReceivedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | BytesJustReceived | Gets the number of bytes received from the server during the operation which raised the current event.
Public property | MessageNumber | Gets the message number (ordinal position in the folder) of the envelope the downloaded data chunk corresponds to.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | TotalBytesReceived | Gets the total length (in bytes) of the already received data of the series of FETCH responses currently being downloaded.
Top
See Also

Reference

MailBee.ImapMail Namespace


ImapEnvelopeDataChunkReceivedEventArgs Methods

ImapEnvelopeDataChunkReceivedEventArgs Methods

The ImapEnvelopeDataChunkReceivedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapEnvelopeDataChunkReceivedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDataChunkReceivedEventArgs Properties

ImapEnvelopeDataChunkReceivedEventArgs Properties

The ImapEnvelopeDataChunkReceivedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | BytesJustReceived | Gets the number of bytes received from the server during the operation which raised the current event.
Public property | MessageNumber | Gets the message number (ordinal position in the folder) of the envelope the downloaded data chunk corresponds to.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | TotalBytesReceived | Gets the total length (in bytes) of the already received data of the series of FETCH responses currently being downloaded.
Top
See Also

Reference

ImapEnvelopeDataChunkReceivedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDataChunkReceivedEventArgs.BytesJustReceived Property

ImapEnvelopeDataChunkReceivedEventArgsBytesJustReceived Property
Gets the number of bytes received from the server during the operation which raised the current event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int BytesJustReceived { get; }
Public ReadOnly Property BytesJustReceived As Integer
    Get

Property Value

Type: Int32
The number of bytes received from the server during the operation which raised the current event.
See Also

Reference

ImapEnvelopeDataChunkReceivedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDataChunkReceivedEventArgs.MessageNumber Property

ImapEnvelopeDataChunkReceivedEventArgsMessageNumber Property
Gets the message number (ordinal position in the folder) of the envelope the downloaded data chunk corresponds to.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageNumber { get; }
Public ReadOnly Property MessageNumber As Integer
    Get

Property Value

Type: Int32
An integer value in the range 1 to MessageCount, representing the message number of the envelope being downloaded.
See Also

Reference

ImapEnvelopeDataChunkReceivedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDataChunkReceivedEventArgs.TotalBytesReceived Property

ImapEnvelopeDataChunkReceivedEventArgsTotalBytesReceived Property
Gets the total length (in bytes) of the already received data of the series of FETCH responses currently being downloaded.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TotalBytesReceived { get; }
Public ReadOnly Property TotalBytesReceived As Integer
    Get

Property Value

Type: Int32
The total length (in bytes) of the already received data of the series of FETCH responses currently being downloaded, including the bytes just received.
See Also

Reference

ImapEnvelopeDataChunkReceivedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDataChunkReceivedEventHandler Delegate

ImapEnvelopeDataChunkReceivedEventHandler Delegate
Represents the method that will handle EnvelopeDataChunkReceived event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ImapEnvelopeDataChunkReceivedEventHandler(
    Object sender,
    ImapEnvelopeDataChunkReceivedEventArgs e
)
Public Delegate Sub ImapEnvelopeDataChunkReceivedEventHandler (
    sender As Object,
    e As ImapEnvelopeDataChunkReceivedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.ImapMailImapEnvelopeDataChunkReceivedEventArgs
See Also

Reference

MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventArgs Class

ImapEnvelopeDownloadedEventArgs Class
Contains the event data for EnvelopeDownloaded event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.ImapMailImapEnvelopeDownloadedEventArgs

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapEnvelopeDownloadedEventArgs : CommonEventArgs
Public Class ImapEnvelopeDownloadedEventArgs
    Inherits CommonEventArgs

The ImapEnvelopeDownloadedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DataLength | Gets the length (in bytes) of the FETCH response containing the downloaded envelope data.
Public property | DownloadedEnvelope | Gets or sets the envelope which had been downloaded.
Public property | MessageNumber | Gets the message number (ordinal position in the folder) of the downloaded envelope.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventArgs Methods

ImapEnvelopeDownloadedEventArgs Methods

The ImapEnvelopeDownloadedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapEnvelopeDownloadedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventArgs Properties

ImapEnvelopeDownloadedEventArgs Properties

The ImapEnvelopeDownloadedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | DataLength | Gets the length (in bytes) of the FETCH response containing the downloaded envelope data.
Public property | DownloadedEnvelope | Gets or sets the envelope which had been downloaded.
Public property | MessageNumber | Gets the message number (ordinal position in the folder) of the downloaded envelope.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

ImapEnvelopeDownloadedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventArgs.DataLength Property

ImapEnvelopeDownloadedEventArgsDataLength Property
Gets the length (in bytes) of the FETCH response containing the downloaded envelope data.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int DataLength { get; }
Public ReadOnly Property DataLength As Integer
    Get

Property Value

Type: Int32
The length (in bytes) of the server response containing the downloaded envelope data.
See Also

Reference

ImapEnvelopeDownloadedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventArgs.DownloadedEnvelope Property

ImapEnvelopeDownloadedEventArgsDownloadedEnvelope Property
Gets or sets the envelope which had been downloaded.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Envelope DownloadedEnvelope { get; set; }
Public Property DownloadedEnvelope As Envelope
    Get
    Set

Property Value

Type: Envelope
A reference to the mail message envelope which had been just downloaded, or a null reference (Nothing in Visual Basic) if there had been no message data in the server response.
Remarks

When this property value is a null reference, this usually means the mail server replied with a response which could not be completely parsed (i.e. the mail server produces incorrect IMAP4 responses). In this case, the correspodning method of Imap class which had been used to download message(s) will throw an exception after the method has finished receiving data from the IMAP4 server.

The developer can also manually set this property value to a null reference to avoid inclusion of this envelope into the resulting EnvelopeCollection. For methods returning a single envelope (such as DownloadEntireMessage(Int64, Boolean)), the result will be a null reference.

Setting this property to a null reference is also useful for downloading very large number of messages at once (when they won't fit in memory). In this case, the developer can save each message to database/disk in EnvelopeDownloaded event handler and then set DownloadedEnvelope to a null reference to free the resources. This is efficient and memory conservative appoach.

See Also

Reference

ImapEnvelopeDownloadedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventArgs.MessageNumber Property

ImapEnvelopeDownloadedEventArgsMessageNumber Property
Gets the message number (ordinal position in the folder) of the downloaded envelope.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageNumber { get; }
Public ReadOnly Property MessageNumber As Integer
    Get

Property Value

Type: Int32
An integer value in the range 1 to MessageCount, representing the message number of the downloaded envelope.
See Also

Reference

ImapEnvelopeDownloadedEventArgs Class
MailBee.ImapMail Namespace


ImapEnvelopeDownloadedEventHandler Delegate

ImapEnvelopeDownloadedEventHandler Delegate
Represents the method that will handle EnvelopeDownloaded event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ImapEnvelopeDownloadedEventHandler(
    Object sender,
    ImapEnvelopeDownloadedEventArgs e
)
Public Delegate Sub ImapEnvelopeDownloadedEventHandler (
    sender As Object,
    e As ImapEnvelopeDownloadedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.ImapMailImapEnvelopeDownloadedEventArgs
See Also

Reference

MailBee.ImapMail Namespace


ImapIdlingEventArgs Class

ImapIdlingEventArgs Class
Contains the event data for Idling event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.ImapMailImapIdlingEventArgs

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapIdlingEventArgs : CommonEventArgs
Public Class ImapIdlingEventArgs
    Inherits CommonEventArgs

The ImapIdlingEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.ImapMail Namespace


ImapIdlingEventArgs Methods

ImapIdlingEventArgs Methods

The ImapIdlingEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapIdlingEventArgs Class
MailBee.ImapMail Namespace


ImapIdlingEventArgs Properties

ImapIdlingEventArgs Properties

The ImapIdlingEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

ImapIdlingEventArgs Class
MailBee.ImapMail Namespace


ImapIdlingEventHandler Delegate

ImapIdlingEventHandler Delegate
Represents the method that will handle Idling event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ImapIdlingEventHandler(
    Object sender,
    ImapIdlingEventArgs e
)
Public Delegate Sub ImapIdlingEventHandler (
    sender As Object,
    e As ImapIdlingEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.ImapMailImapIdlingEventArgs
See Also

Reference

MailBee.ImapMail Namespace


ImapMessageStatusEventArgs Class

ImapMessageStatusEventArgs Class
Contains the event data for MessageStatus event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.ImapMailImapMessageStatusEventArgs

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapMessageStatusEventArgs : CommonEventArgs
Public Class ImapMessageStatusEventArgs
    Inherits CommonEventArgs

The ImapMessageStatusEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Flags | Gets the new value of the message flags.
Public property | MessageCountOrIndex | Gets the count or index of message(s) mentioned in the current response.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | StatusID | Gets the status string of the current response.
Top
See Also

Reference

MailBee.ImapMail Namespace


ImapMessageStatusEventArgs Methods

ImapMessageStatusEventArgs Methods

The ImapMessageStatusEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapMessageStatusEventArgs Class
MailBee.ImapMail Namespace


ImapMessageStatusEventArgs Properties

ImapMessageStatusEventArgs Properties

The ImapMessageStatusEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Flags | Gets the new value of the message flags.
Public property | MessageCountOrIndex | Gets the count or index of message(s) mentioned in the current response.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | StatusID | Gets the status string of the current response.
Top
See Also

Reference

ImapMessageStatusEventArgs Class
MailBee.ImapMail Namespace


ImapMessageStatusEventArgs.Flags Property

ImapMessageStatusEventArgsFlags Property
Gets the new value of the message flags.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageFlagSet Flags { get; }
Public ReadOnly Property Flags As MessageFlagSet
    Get

Property Value

Type: MessageFlagSet
For "FETCH" response, returns a reference to the MessageFlagSet object containing the flags of the message; otherwise, a null reference (Nothing in Visual Basic).
See Also

Reference

ImapMessageStatusEventArgs Class
MailBee.ImapMail Namespace
ImapMessageStatusEventArgsStatusID


ImapMessageStatusEventArgs.MessageCountOrIndex Property

ImapMessageStatusEventArgsMessageCountOrIndex Property
Gets the count or index of message(s) mentioned in the current response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageCountOrIndex { get; }
Public ReadOnly Property MessageCountOrIndex As Integer
    Get

Property Value

Type: Int32
For "EXISTS" and "RECENT" responses, returns the count of all or recent messages in the folder; for "EXPUNGE" or "FETCH" responses, returns the index of the message which was purged or whose flags were modified.
See Also

Reference

ImapMessageStatusEventArgs Class
MailBee.ImapMail Namespace
ImapMessageStatusEventArgsStatusID


ImapMessageStatusEventArgs.StatusID Property

ImapMessageStatusEventArgsStatusID Property
Gets the status string of the current response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string StatusID { get; }
Public ReadOnly Property StatusID As String
    Get

Property Value

Type: String
The string containing the status response string in uppercase form.
Remarks
This can be one of the following values: "EXISTS", "RECENT", "EXPUNGE", "FETCH".
See Also

Reference

ImapMessageStatusEventArgs Class
MailBee.ImapMail Namespace


ImapMessageStatusEventHandler Delegate

ImapMessageStatusEventHandler Delegate
Represents the method that will handle MessageStatus event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ImapMessageStatusEventHandler(
    Object sender,
    ImapMessageStatusEventArgs e
)
Public Delegate Sub ImapMessageStatusEventHandler (
    sender As Object,
    e As ImapMessageStatusEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.ImapMailImapMessageStatusEventArgs
See Also

Reference

MailBee.ImapMail Namespace


ImapServerStatusEventArgs Class

ImapServerStatusEventArgs Class
Contains the event data for ServerStatus event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.ImapMailImapServerStatusEventArgs

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapServerStatusEventArgs : CommonEventArgs
Public Class ImapServerStatusEventArgs
    Inherits CommonEventArgs

The ImapServerStatusEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Details | Gets the response body.
Public property | HumanReadable | Gets the human readable part of the status response.
Public property | IsAlert | Gets whether the status response is "[ALERT]" response.
Public property | OptionalData | Gets the contents of the optional response code of the response.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | StatusID | Gets the status string of the current response.
Top
See Also

Reference

MailBee.ImapMail Namespace


ImapServerStatusEventArgs Methods

ImapServerStatusEventArgs Methods

The ImapServerStatusEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace


ImapServerStatusEventArgs Properties

ImapServerStatusEventArgs Properties

The ImapServerStatusEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | Details | Gets the response body.
Public property | HumanReadable | Gets the human readable part of the status response.
Public property | IsAlert | Gets whether the status response is "[ALERT]" response.
Public property | OptionalData | Gets the contents of the optional response code of the response.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | StatusID | Gets the status string of the current response.
Top
See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace


ImapServerStatusEventArgs.Details Property

ImapServerStatusEventArgsDetails Property
Gets the response body.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Details { get; }
Public ReadOnly Property Details As String
    Get

Property Value

Type: String
The string containing the rest of the status response beyond the status string and the optional response code, or a null reference (Nothing in Visual Basic) if the response is a status response or it does not have any data beyond the status code or the optional response code.
Remarks

The status responses are "OK", "NO", "BAD", "PREAUTH", "BYE". In these responses, any additional data beyond the status code or the optional response code is treated as HumanReadable text. For other responses ("FLAGS"), the rest of the response will contain information specific to this response (for instance, a set of flags for "FLAGS" response). This information is in IMAP4 format and is not directly intended to be read by humans, and will be available in Details property value.

Thus, both Details and HumanReadable properties cannot be non-null for the same response. If one of these properties is non-null, another will be null. Both properties can be null, however.

See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace


ImapServerStatusEventArgs.HumanReadable Property

ImapServerStatusEventArgsHumanReadable Property
Gets the human readable part of the status response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HumanReadable { get; }
Public ReadOnly Property HumanReadable As String
    Get

Property Value

Type: String
The string containing the human readable part of the status response, or a null reference (Nothing in Visual Basic) if the response does not have the human readable part.
Remarks
If IsAlert is true, the application must present HumanReadable to the user.
See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace
ImapServerStatusEventArgsIsAlert


ImapServerStatusEventArgs.IsAlert Property

ImapServerStatusEventArgsIsAlert Property
Gets whether the status response is "[ALERT]" response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsAlert { get; }
Public ReadOnly Property IsAlert As Boolean
    Get

Property Value

Type: Boolean
true if the response contains "[ALERT]" optional response code; otherwise, false.
Remarks
If this property returns true, the HumanReadable property value MUST be presented to the user. For instance, the server may warn its clients that it's going to shutdown soon.
See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace
ImapServerStatusEventArgsHumanReadable
ImapServerStatusEventArgsOptionalData


ImapServerStatusEventArgs.OptionalData Property

ImapServerStatusEventArgsOptionalData Property
Gets the contents of the optional response code of the response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OptionalData { get; }
Public ReadOnly Property OptionalData As String
    Get

Property Value

Type: String
The string containing the inner contents of the optional response (the part of the status response enclosed in square brackets), or a null reference (Nothing in Visual Basic) if the response does not have the optional response code.
Remarks
For instance, if the optional response code is "[alert]", this property returns "alert". The square brackets themselves are not returned.
See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace


ImapServerStatusEventArgs.StatusID Property

ImapServerStatusEventArgsStatusID Property
Gets the status string of the current response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string StatusID { get; }
Public ReadOnly Property StatusID As String
    Get

Property Value

Type: String
The string containing the status response string in uppercase form.
Remarks
This can be one of the following values: "OK", "NO", "BAD", "PREAUTH", "BYE", "FLAGS".
See Also

Reference

ImapServerStatusEventArgs Class
MailBee.ImapMail Namespace


ImapServerStatusEventHandler Delegate

ImapServerStatusEventHandler Delegate
Represents the method that will handle ServerStatus event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void ImapServerStatusEventHandler(
    Object sender,
    ImapServerStatusEventArgs e
)
Public Delegate Sub ImapServerStatusEventHandler (
    sender As Object,
    e As ImapServerStatusEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.ImapMailImapServerStatusEventArgs
See Also

Reference

MailBee.ImapMail Namespace


MailBeeImapInvalidEnvelopeException Class

MailBeeImapInvalidEnvelopeException Class
The exception that is thrown when MailBee encounters FETCH response which could not be completely parsed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.ImapMailMailBeeImapInvalidEnvelopeException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImapInvalidEnvelopeException : MailBeeEmailProtocolException
<SerializableAttribute>
Public Class MailBeeImapInvalidEnvelopeException
    Inherits MailBeeEmailProtocolException

The MailBeeImapInvalidEnvelopeException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapInvalidEnvelopeException | Initializes a new instance of the MailBeeImapInvalidEnvelopeException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | InvalidEnvelope | Gets the invalid envelope which could not parsed.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

If this exception occurs, the IsValid property of the corresponding Envelope object will be set to false. The common reason of occurrence of this exception is errors in the mail server implementation.

This exception is thrown to the application code only when it occurs during execution of methods which return a single object (such as DownloadEntireMessage(Int64, Boolean)). Methods which return collections of objects (such as DownloadEntireMessages(String, Boolean), DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String), etc) only raise ErrorOccurred event passing this exception as Reason value. The execution then continues. This allows the application to skip the invalid envelope or message and proceed with subsequent messages if any.

See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope


MailBeeImapInvalidEnvelopeException Constructor

MailBeeImapInvalidEnvelopeException Constructor
Initializes a new instance of the MailBeeImapInvalidEnvelopeException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapInvalidEnvelopeException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapInvalidEnvelopeException Class
MailBee.ImapMail Namespace


MailBeeImapInvalidEnvelopeException Methods

MailBeeImapInvalidEnvelopeException Methods

The MailBeeImapInvalidEnvelopeException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapInvalidEnvelopeException Class
MailBee.ImapMail Namespace


MailBeeImapInvalidEnvelopeException Properties

MailBeeImapInvalidEnvelopeException Properties

The MailBeeImapInvalidEnvelopeException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | InvalidEnvelope | Gets the invalid envelope which could not parsed.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapInvalidEnvelopeException Class
MailBee.ImapMail Namespace


MailBeeImapInvalidEnvelopeException.InvalidEnvelope Property

MailBeeImapInvalidEnvelopeExceptionInvalidEnvelope Property
Gets the invalid envelope which could not parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Envelope InvalidEnvelope { get; }
Public ReadOnly Property InvalidEnvelope As Envelope
    Get

Property Value

Type: Envelope
A reference to the Envelope object representing the FETCH response which could not be completely parsed.
Remarks
Methods which download mail messages (such as DownloadEntireMessages(String, Boolean)) internally call DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) to get envelopes, and then return mail messages by extracting them from MessagePreview property of the Envelope objects. Thus, MailBeeImapInvalidEnvelopeException can be thrown not only with DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) methods, but also with the methods which download entire messages or message headers, including DownloadEntireMessage(Int64, Boolean), DownloadMessageHeaders(String, Boolean), etc.
See Also

Reference

MailBeeImapInvalidEnvelopeException Class
MailBee.ImapMail Namespace


MailBeeImapInvalidEnvelopeException Events

MailBeeImapInvalidEnvelopeException Events

The MailBeeImapInvalidEnvelopeException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapInvalidEnvelopeException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException Class

MailBeeImapLoginBadCredentialsException Class
The exception that is thrown when the IMAP server reports the given user account name and/or password is incorrect.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.ImapMailMailBeeImapNegativeResponseException
MailBee.ImapMailMailBeeImapLoginNegativeResponseException
MailBee.ImapMailMailBeeImapLoginBadCredentialsException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImapLoginBadCredentialsException : MailBeeImapLoginNegativeResponseException,
    IMailBeeLoginBadCredentialsException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeeImapLoginBadCredentialsException
    Inherits MailBeeImapLoginNegativeResponseException
    Implements IMailBeeLoginBadCredentialsException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException

The MailBeeImapLoginBadCredentialsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapLoginBadCredentialsException | Initializes a new instance of the MailBeeImapLoginBadCredentialsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used during the authentication.
Public property | CompletionResult | Gets the response status code. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Password | Gets the account password which was used during the authentication.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException Constructor

MailBeeImapLoginBadCredentialsException Constructor
Initializes a new instance of the MailBeeImapLoginBadCredentialsException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapLoginBadCredentialsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapLoginBadCredentialsException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException Methods

MailBeeImapLoginBadCredentialsException Methods

The MailBeeImapLoginBadCredentialsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapLoginBadCredentialsException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException Properties

MailBeeImapLoginBadCredentialsException Properties

The MailBeeImapLoginBadCredentialsException type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used during the authentication.
Public property | CompletionResult | Gets the response status code. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Password | Gets the account password which was used during the authentication.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapLoginBadCredentialsException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException.AccountName Property

MailBeeImapLoginBadCredentialsExceptionAccountName Property
Gets the account name which was used during the authentication.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; }
Public ReadOnly Property AccountName As String
    Get

Property Value

Type: String
The account name which was used during the authentication.

Implements

IMailBeeLoginBadCredentialsExceptionAccountName
See Also

Reference

MailBeeImapLoginBadCredentialsException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException.Password Property

MailBeeImapLoginBadCredentialsExceptionPassword Property
Gets the account password which was used during the authentication.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; }
Public ReadOnly Property Password As String
    Get

Property Value

Type: String
The account password which was used during the authentication.

Implements

IMailBeeLoginBadCredentialsExceptionPassword
See Also

Reference

MailBeeImapLoginBadCredentialsException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadCredentialsException Events

MailBeeImapLoginBadCredentialsException Events

The MailBeeImapLoginBadCredentialsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapLoginBadCredentialsException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadMethodException Class

MailBeeImapLoginBadMethodException Class
The exception that is thrown when the IMAP server reports the given SASL authentication method is not supported and use of another authentication methods is not allowed by the application.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.ImapMailMailBeeImapNegativeResponseException
MailBee.ImapMailMailBeeImapLoginNegativeResponseException
MailBee.ImapMailMailBeeImapLoginBadMethodException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImapLoginBadMethodException : MailBeeImapLoginNegativeResponseException,
    IMailBeeLoginBadMethodException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeeImapLoginBadMethodException
    Inherits MailBeeImapLoginNegativeResponseException
    Implements IMailBeeLoginBadMethodException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException

The MailBeeImapLoginBadMethodException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapLoginBadMethodException | Initializes a new instance of the MailBeeImapLoginBadMethodException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | CompletionResult | Gets the response status code. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
By default, if a particular SASL authentication method is not supported by the server, MailBee switches to the previous method listed in authMethods parameter of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method. If no more methods left, MailBeeLoginNoSupportedMethodsException is thrown. However, if UseSingleMethodOnly flag is set in authOptions parameter of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method, MailBee will not try other methods. Instead, if will immediately throw MailBeeImapLoginBadMethodException.
Note Note
This exception does not indicate that authentication using the given method failed. Instead, it indicates the method itself is not supported by the server. When the method is supported but the authentication using this method fails (invalid account name/password), MailBee does not try another methods (there would be no sense if it did), and throws MailBeeImapLoginBadCredentialsException.
This exception may also occur if FipsMode is enabled and the given authentication method is not FIPS-compliant.
See Also

Reference

MailBee.ImapMail Namespace
MailBeeAuthenticationMethods
MailBeeAuthenticationOptions
MailBee.ImapMailMailBeeImapLoginBadCredentialsException


MailBeeImapLoginBadMethodException Constructor

MailBeeImapLoginBadMethodException Constructor
Initializes a new instance of the MailBeeImapLoginBadMethodException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapLoginBadMethodException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapLoginBadMethodException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadMethodException Methods

MailBeeImapLoginBadMethodException Methods

The MailBeeImapLoginBadMethodException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapLoginBadMethodException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadMethodException Properties

MailBeeImapLoginBadMethodException Properties

The MailBeeImapLoginBadMethodException type exposes the following members.

Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | CompletionResult | Gets the response status code. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapLoginBadMethodException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadMethodException.BadMethod Property

MailBeeImapLoginBadMethodExceptionBadMethod Property
Gets the authentication method which was rejected by the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods BadMethod { get; }
Public ReadOnly Property BadMethod As AuthenticationMethods
    Get

Property Value

Type: AuthenticationMethods
A AuthenticationMethods value having only a single bit set, which indicates the method which is requested by the application but not supported by the server.

Implements

IMailBeeLoginBadMethodExceptionBadMethod
Remarks
Although AuthenticationMethods allows bitwise combination of its member values, the result returned by this property always contains a single member value indicating the specific method which was rejected.
See Also

Reference

MailBeeImapLoginBadMethodException Class
MailBee.ImapMail Namespace


MailBeeImapLoginBadMethodException Events

MailBeeImapLoginBadMethodException Events

The MailBeeImapLoginBadMethodException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapLoginBadMethodException Class
MailBee.ImapMail Namespace


MailBeeImapLoginNegativeResponseException Class

MailBeeImapLoginNegativeResponseException Class
An abstract parent for all exceptions which indicate the IMAP server replied with a negative response during authentication of the user.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.ImapMailMailBeeImapNegativeResponseException
MailBee.ImapMailMailBeeImapLoginNegativeResponseException
MailBee.ImapMailMailBeeImapLoginBadCredentialsException
MailBee.ImapMailMailBeeImapLoginBadMethodException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeImapLoginNegativeResponseException : MailBeeImapNegativeResponseException,
    IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public MustInherit Class MailBeeImapLoginNegativeResponseException
    Inherits MailBeeImapNegativeResponseException
    Implements IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The MailBeeImapLoginNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapLoginNegativeResponseException | Initializes a new instance of the MailBeeImapLoginNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | CompletionResult | Gets the response status code. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.ImapMail Namespace


MailBeeImapLoginNegativeResponseException Constructor

MailBeeImapLoginNegativeResponseException Constructor
Initializes a new instance of the MailBeeImapLoginNegativeResponseException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapLoginNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapLoginNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapLoginNegativeResponseException Methods

MailBeeImapLoginNegativeResponseException Methods

The MailBeeImapLoginNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapLoginNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapLoginNegativeResponseException Properties

MailBeeImapLoginNegativeResponseException Properties

The MailBeeImapLoginNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | CompletionResult | Gets the response status code. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response. (Inherited from MailBeeImapNegativeResponseException.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapLoginNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapLoginNegativeResponseException Events

MailBeeImapLoginNegativeResponseException Events

The MailBeeImapLoginNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapLoginNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException Class

MailBeeImapMessageIndexNotFoundException Class
The exception that is thrown when the message with the specified index cannot be downloaded because this index does not correspond to any message in the currently selected folder on the server.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.ImapMailMailBeeImapMessageIndexNotFoundException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImapMessageIndexNotFoundException : MailBeeEmailProtocolException
<SerializableAttribute>
Public Class MailBeeImapMessageIndexNotFoundException
    Inherits MailBeeEmailProtocolException

The MailBeeImapMessageIndexNotFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapMessageIndexNotFoundException | Initializes a new instance of the MailBeeImapMessageIndexNotFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | IndexIsUid | Gets whether MessageIndex designates a UID rather than an ordinal message number.
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | MessageIndex | Gets the message index of the non-existent message.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
If this exception occurs, it indicates that the specified index (ordinal message number or UID) is not valid in the current folder state.
See Also

Reference

MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException Constructor

MailBeeImapMessageIndexNotFoundException Constructor
Initializes a new instance of the MailBeeImapMessageIndexNotFoundException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapMessageIndexNotFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapMessageIndexNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException Methods

MailBeeImapMessageIndexNotFoundException Methods

The MailBeeImapMessageIndexNotFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapMessageIndexNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException Properties

MailBeeImapMessageIndexNotFoundException Properties

The MailBeeImapMessageIndexNotFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | IndexIsUid | Gets whether MessageIndex designates a UID rather than an ordinal message number.
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | MessageIndex | Gets the message index of the non-existent message.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapMessageIndexNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException.IndexIsUid Property

MailBeeImapMessageIndexNotFoundExceptionIndexIsUid Property
Gets whether MessageIndex designates a UID rather than an ordinal message number.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IndexIsUid { get; }
Public ReadOnly Property IndexIsUid As Boolean
    Get

Property Value

Type: Boolean
If true, MessageIndex designates a UID; otherwise, an ordinal message number.
See Also

Reference

MailBeeImapMessageIndexNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException.MessageIndex Property

MailBeeImapMessageIndexNotFoundExceptionMessageIndex Property
Gets the message index of the non-existent message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long MessageIndex { get; }
Public ReadOnly Property MessageIndex As Long
    Get

Property Value

Type: Int64
The UID (if IndexIsUid is true) or the message number (if IndexIsUid is false) of the non-existent message.
Remarks
Valid message numbers are positive integer values. Valid UIDs are positive 32-bit values.
See Also

Reference

MailBeeImapMessageIndexNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapMessageIndexNotFoundException Events

MailBeeImapMessageIndexNotFoundException Events

The MailBeeImapMessageIndexNotFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapMessageIndexNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException Class

MailBeeImapNegativeResponseException Class
The exception that is thrown when the IMAP server responds with a negative reply (i.e. "BAD" or "NO").
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.ImapMailMailBeeImapNegativeResponseException
MailBee.ImapMailMailBeeImapLoginNegativeResponseException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImapNegativeResponseException : MailBeeEmailProtocolNegativeResponseException
<SerializableAttribute>
Public Class MailBeeImapNegativeResponseException
    Inherits MailBeeEmailProtocolNegativeResponseException

The MailBeeImapNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapNegativeResponseException | Initializes a new instance of the MailBeeImapNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | CompletionResult | Gets the response status code.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response.
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException Constructor

MailBeeImapNegativeResponseException Constructor
Initializes a new instance of the MailBeeImapNegativeResponseException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException Methods

MailBeeImapNegativeResponseException Methods

The MailBeeImapNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException Properties

MailBeeImapNegativeResponseException Properties

The MailBeeImapNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | CompletionResult | Gets the response status code.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | HumanReadable | Gets the human readable part of the status response.
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | OptionalResponse | Gets the contents of the optional response code of the response.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException.CompletionResult Property

MailBeeImapNegativeResponseExceptionCompletionResult Property
Gets the response status code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string CompletionResult { get; }
Public ReadOnly Property CompletionResult As String
    Get

Property Value

Type: String
The string containing uppercased value of the negative status response code: "BAD" or "NO".
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException.HumanReadable Property

MailBeeImapNegativeResponseExceptionHumanReadable Property
Gets the human readable part of the status response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HumanReadable { get; }
Public ReadOnly Property HumanReadable As String
    Get

Property Value

Type: String
The string containing the human readable part of the status response, or a null reference (Nothing in Visual Basic) if the response does not have the human readable part.
Remarks
For instance, if the entire status response string is "MBN00000002 NO incorrect password or account name", this property returns "incorrect password or account name".
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException.OptionalResponse Property

MailBeeImapNegativeResponseExceptionOptionalResponse Property
Gets the contents of the optional response code of the response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string OptionalResponse { get; }
Public ReadOnly Property OptionalResponse As String
    Get

Property Value

Type: String
The string containing the inner contents of the optional response (the part of the status response enclosed in square brackets), or a null reference (Nothing in Visual Basic) if the response does not have the optional response code.
Remarks
For instance, if the optional response code is "[alert]", this property returns "alert". The square brackets themselves are not returned.
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapNegativeResponseException Events

MailBeeImapNegativeResponseException Events

The MailBeeImapNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapNegativeResponseException Class
MailBee.ImapMail Namespace


MailBeeImapResponseNotFoundException Class

MailBeeImapResponseNotFoundException Class
The exception that is thrown when the IMAP server did not return the expected response.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.ImapMailMailBeeImapResponseNotFoundException

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImapResponseNotFoundException : MailBeeEmailProtocolException
<SerializableAttribute>
Public Class MailBeeImapResponseNotFoundException
    Inherits MailBeeEmailProtocolException

The MailBeeImapResponseNotFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImapResponseNotFoundException | Initializes a new instance of the MailBeeImapResponseNotFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
If this exception occurs, it indicates the IMAP4 server returned wrong response (not that one which was expected). This can only happen if there are serious errors in the mail server implementation (for instance, certain command is not properly implemented).
See Also

Reference

MailBee.ImapMail Namespace


MailBeeImapResponseNotFoundException Constructor

MailBeeImapResponseNotFoundException Constructor
Initializes a new instance of the MailBeeImapResponseNotFoundException class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImapResponseNotFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImapResponseNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapResponseNotFoundException Methods

MailBeeImapResponseNotFoundException Methods

The MailBeeImapResponseNotFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapResponseNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapResponseNotFoundException Properties

MailBeeImapResponseNotFoundException Properties

The MailBeeImapResponseNotFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeImapResponseNotFoundException Class
MailBee.ImapMail Namespace


MailBeeImapResponseNotFoundException Events

MailBeeImapResponseNotFoundException Events

The MailBeeImapResponseNotFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImapResponseNotFoundException Class
MailBee.ImapMail Namespace


Envelope Class

Envelope Class
Represents an IMAP4 envelope of a mail message (including any other related information such as body structure, message flags, the mail message itself, etc).
Inheritance Hierarchy
SystemObject
MailBee.ImapMailEnvelope

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Envelope
Public Class Envelope

The Envelope type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAllRecipients | Returns the list of all recipients of the mail message.
 | GetEnvelopeItem | Returns a reference to the specified item of the FETCH response.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | GetUtf7DecodedGmailLabels | Gets the list of Gmail-specific labels of the message decoded from UTF-7M encoding.
Public method | HasSystemFlag | Checks if the message has a certain system flag set.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Bcc | Gets EmailAddressCollection object representing "BCC:" recipients of the message.
Public property | BodyStructure | Gets the information about structure of the message.
Public property | Cc | Gets EmailAddressCollection object representing "CC:" recipients of the message.
Public property | Date | Gets the date and time when the message was composed.
Public property | DateReceived | Gets the date and time when the message was received by the mail server.
Public property | DatesAsUtc | Indicates if MailBee should return date and time according to UTC standard.
Public property | ExtraHeaders | Gets a collection of additional message headers which have been explicitly requested from the server.
Public property | Flags | Gets MessageFlagSet object containing system and custom flags of the message.
Public property | From | Gets EmailAddress object representing "From:" field of the message.
Public property | GmailLabels | Gets the list of Gmail-specific labels associated with the message.
Public property | GmailMessageID | Gets the Gmail-specific message-id.
Public property | GmailThreadID | Gets the Gmail-specific thread-id.
Public property | InReplyTo | Gets the value of "In-Reply-To" header of the message.
Public property | IsValid | Indicates if the envelope data has been successfully parsed.
Public property | MessageID | Gets the value of "Message-ID" header of the message.
Public property | MessageNumber | Gets the ordinal number of the message in the folder.
Public property | MessagePreview | Gets the entire or partial mail message.
Public property | ReplyTo | Gets EmailAddress object representing "Reply-To:" field of the message.
Public property | SafeMode | Gets or sets whether empty values instead of a null reference (Nothing in Visual Basic) should be returned when the corresponding fields are not available in the data received from the server.
Public property | Sender | Gets EmailAddress object representing the information about the actual sender of the message.
Public property | Size | Gets the length of the entire message (in bytes) on the mail server.
Public property | Subject | Gets the subject line of the message.
Public property | To | Gets EmailAddressCollection object representing "To:" recipients of the message.
Public property | Uid | Gets UID (Unique-ID) assigned to the message in the folder on the mail server.
Top
Remarks

An instance of this class represents the information about the mail message returned by the IMAP4 server in a single FETCH response. This may contain information about an IMAP4 envelope (which is a collection of common properties of a mail message such as "Subject:", "From:", "To:", etc), a body structure of the mail message, the mail message itself, its flags, ordinal message number, UID, and size, the date when the message was received by the IMAP4 server, and other message attributes including user-specified ones.

MailBee allows the developer to specify which attributes/parts of mail messages must be downloaded resulting in a greater flexibility and smaller network traffic (unnecessary items are not downloaded).

All methods of Imap object which return MailMessage or MailMessageCollection objects actually download envelopes and then extract mail messages from MessagePreview property of Envelope object.

Note Note
Due to complexity of the IMAP4 protocol, many IMAP4 server implementations cannot always produce correct FETCH responses. If MailBee detects the particular FETCH response cannot be parsed, it raises ErrorOccurred event for this response, and sets IsValid property for the corresponding response to false. No exception is thrown, however.
Most fields of the envelope may be missing (if they were not requested from the server or they are missing in the message itself). For instance, if the message has no subject, Subject property may return a null reference (Nothing in Visual Basic). To make using Envelope object easier, MailBee returns empty values instead of null references by default. To force MailBee return a null reference for a missing field, the developer should set SafeMode to false.
Examples
This sample downloads essential information about the messages in the inbox (such as IMAP4 envelope, date of receiving by the server, flags, and size), and its body structure. The messages themselves are not downloaded. The body structure information is used to count attachments of the message (this approach is more reliable than downloading message header and relying on HasAttachments property which might not be 100% correct). To notify user about particular envelopes which cannot be parsed, ErrorOccurred event handler is used.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // ErrorOccurred event handler
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        // Filter only those errors which correspond to envelopes which cannot be parsed.
        MailBeeImapInvalidEnvelopeException ex =
            e.Reason as MailBeeImapInvalidEnvelopeException;

        if (ex != null)
        {
            Console.WriteLine("WARNING: IMAP response for message #" +
                ex.InvalidEnvelope.MessageNumber + " is incorrect.");
        }
}

    // The actual code
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Attach ErrorOccurred event handler.
        imp.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Get to inbox.
        imp.Connect("imap.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("Inbox");

        // Get envelopes, body structures, message flags, etc for all messages in the inbox.
        EnvelopeCollection envelopes = imp.DownloadEnvelopes(
            Imap.AllMessages, false, EnvelopeParts.MailBeeEnvelope | EnvelopeParts.BodyStructure, 0);

        // Demonstrate that we can work with downloaded envelopes even in offline mode.
        imp.Disconnect();

        foreach (Envelope envelope in envelopes)
        {
            if (envelope.IsValid)
            {
                Console.WriteLine("Message #" + envelope.MessageNumber +
                    ", Received at: " + envelope.DateReceived + ", Created at: " + envelope.Date);
                Console.WriteLine("  Flags: " + envelope.Flags.ToString());
                Console.WriteLine("  From: " + envelope.From.ToString());
                Console.WriteLine("  To: " + envelope.To.ToString());
                Console.WriteLine("  Subject: " + envelope.Subject);
                System.Text.StringBuilder strBuffer = new System.Text.StringBuilder();
                ImapBodyStructureCollection parts = envelope.BodyStructure.GetAllParts();
                foreach (ImapBodyStructure part in parts)
                {
                    // Detect if this part is attachment.
                    if ((part.Disposition != null && part.Disposition.ToLower() == "attachment") ||
                        (part.Filename != null && part.Filename != string.Empty) ||
                        (part.ContentType != null && part.ContentType.ToLower() == "message/rfc822"))
                    {
                        string filename;
                        if (part.Filename != null && part.Filename.Length > 0)
                        {
                            filename = part.Filename;
                        }
                        else
                        {
                            filename = "untitled";
                        }

                        // Important: Size property returns the length of part data in encoded form
                        // (such as base64). There is no way to learn the exact length unless to
                        // download the entire message. However, you may improve precision by examining
                        // MailEncodingName property value. If it's "base64", decoded data is about 70%
                        // in size of mail-encoded data. However, it's hard to estimate if it's
                        // "quoted-printable" because decoded size/encoded size ratio highly depends on
                        // the actual data contents in this case. Fortunately, "quoted-printable" is
                        // quite rarely used for attachments. If MailEncodingName is "", "binary", "7bit",
                        // or "8bit", then the data is not encoded, and Size property strictly matches
                        // the actual data length.
                        strBuffer.Append("[" + filename + " of approx. " + part.Size + " bytes]");
                    }
                }
                if (strBuffer.Length > 0)
                {
                    Console.WriteLine("  Attachments: " + strBuffer.ToString());
                }
                else
                {
                    Console.WriteLine("  Attachments: none");
                }
            }
            else
            {
                Console.WriteLine("Could not parse envelope for message #" + envelope.MessageNumber);
            }
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' ErrorOccurred event handler
    Private Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        ' Filter only those errors which correspond to envelopes which cannot be parsed.
        Dim ex As MailBeeImapInvalidEnvelopeException = e.Reason

        If Not ex Is Nothing Then
            Console.WriteLine("WARNING: IMAP response for message #" & _
                ex.InvalidEnvelope.MessageNumber & " is incorrect.")
        End If
    End Sub

    ' The actual code
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Attach ErrorOccurred event handler.
        AddHandler imp.ErrorOccurred, AddressOf OnErrorOccurred

        ' Get to inbox.
        imp.Connect("imap.domain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("Inbox")

        ' Get envelopes, body structures, message flags, etc for all messages in the inbox.
        Dim envelopes As EnvelopeCollection

        envelopes = imp.DownloadEnvelopes(Imap.AllMessages, False, EnvelopeParts.MailBeeEnvelope _
            Or EnvelopeParts.BodyStructure, 0)

        ' Demonstrate that we can work with downloaded envelopes even in offline mode.
        imp.Disconnect()

        For Each env As Envelope In envelopes
            If env.IsValid Then
                Console.WriteLine("Message #" & env.MessageNumber & ", Received at: " & _
                    env.DateReceived & ", Created at: " & env.Date)
                Console.WriteLine(" Flags: " & env.Flags.ToString())
                Console.WriteLine(" From: " & env.From.ToString())
                Console.WriteLine(" To: " & env.To.ToString())
                Console.WriteLine(" Subject: " & env.Subject)

                Dim strBuffer As New System.Text.StringBuilder
                Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()

                For Each part As ImapBodyStructure In parts
                    ' Detect if this part is attachment.
                    If (Not part.Disposition Is Nothing AndAlso part.Disposition.ToLower() = "attachment") OrElse _
                        (Not part.Filename Is Nothing AndAlso part.Filename <> String.Empty) OrElse _
                        (Not part.ContentType Is Nothing AndAlso part.ContentType.ToLower() = "message/rfc822") Then

                        Dim filename As String

                        If (Not part.Filename Is Nothing) And (part.Filename.Length > 0) Then
                            filename = part.Filename
                        Else
                            filename = "untitled"
                        End If

                        ' Important: Size property returns the length of part data in encoded form
                        ' (such as base64). There is no way to learn the exact length unless to
                        ' download the entire message. However, you may improve precision by examining
                        ' MailEncodingName property value. If it's "base64", decoded data is about 70%
                        ' in size of mail-encoded data. However, it's hard to estimate if it's
                        ' "quoted-printable" because decoded size/encoded size ratio highly depends on
                        ' the actual data contents in this case. Fortunately, "quoted-printable" is
                        ' quite rarely used for attachments. If MailEncodingName is "", "binary", "7bit",
                        ' or "8bit", then the data is not encoded, and Size property strictly matches
                        ' the actual data length.
                        strBuffer.Append("[" & filename & " of approx. " & part.Size & " bytes]")
                    End If
                Next

                If strBuffer.Length > 0 Then
                    Console.WriteLine(" Attachments: " & strBuffer.ToString())
                Else
                    Console.WriteLine(" Attachments: none")
                End If
            Else
                Console.WriteLine("Could not parse envelope for message #" & env.MessageNumber)
            End If
        Next
    End Sub
End Module
See Also

Reference

MailBee.ImapMail Namespace
ImapDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)


Envelope Methods

Envelope Methods

The Envelope type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAllRecipients | Returns the list of all recipients of the mail message.
 | GetEnvelopeItem | Returns a reference to the specified item of the FETCH response.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | GetUtf7DecodedGmailLabels | Gets the list of Gmail-specific labels of the message decoded from UTF-7M encoding.
Public method | HasSystemFlag | Checks if the message has a certain system flag set.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.GetAllRecipients Method

EnvelopeGetAllRecipients Method
Returns the list of all recipients of the mail message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection GetAllRecipients()
Public Function GetAllRecipients As EmailAddressCollection

Return Value

Type: EmailAddressCollection
A reference to EmailAddressCollection object containing all of the recipients of the mail message.
Remarks
This method never returns a null reference (Nothing in Visual Basic), even if SafeMode is false and To, Cc, and Bcc return a null reference.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.GetEnvelopeItem Method

EnvelopeGetEnvelopeItem Method
Returns a reference to the specified item of the FETCH response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object GetEnvelopeItem(
    string name,
    bool stringsAsBytes
)
Public Function GetEnvelopeItem (
    name As String,
    stringsAsBytes As Boolean
) As Object

Parameters

name
Type: SystemString
The name of the specified element of the response.
stringsAsBytes
Type: SystemBoolean
If true and the specified item was not recognized by MailBee as predefined object, all strings within the item data will be returned as byte arrays; if false, all strings in a non-predefined object will be returned as String.

Return Value

Type: Object
If the specified item was found in the response data, the method returns a reference to the object representing this item; otherwise, the method returns a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
Remarks

This method can return objects of many different types depending on whether the specified item is predefined and whether it's a list of sub-items or a single item. In particular, if certain item is predefined (such as BODYSTRUCTURE, UID, FLAGS, RFC822.SIZE, etc) the corresponding object or value type will be returned (such as ImapBodyStructure, Int64, MessageFlagSet, Int32, etc).

If name is not recognized, the method returns ArrayList object if the item is a list of sub-items, or byte[]/string depending on stringsAsBytes value. In the case if ArrayList is returned, its sub-items will conform the same rule: if sub-item is a list, it will be returned as ArrayList, otherwise, byte[] or string. Thus, GetEnvelopeItem(String, Boolean) method allows the developer to examine both simple FETCH items and complex nested structures with unlimited depth of hierarchy.

The common use of setting stringsAsBytes to true is when the application needs the item data as byte array. Otherwise, the developer should set stringsAsBytes to false.

The developer can use this method to obtain user-specified items of the FETCH response (for instance, the common use is getting certain MIME part of the message). To have the particular item listed in the FETCH response, the developer should first specify its key in extraItems parameter of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.

If you need to extract different items for different e-mails, you can either call DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method multiple times specifying different items each time or use DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) method. DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) is faster as it executes as a single command (pipelining mode). The difference is especially noticable if you download many small items.

Note Note
Keys to be specified in extraItems parameters of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method can be different from their corresponding item names in FETCH responses. For instance, if BODY.PEEK[1] was requested, its name in the FETCH response would be BODY[1]. See IMAP4 protocol specification (RFC3501) for more information regarding FETCH requests and responses.
Examples

This sample completely downloads all image files attached or embedded into the last message in the inbox, and saves them into C:\Temp folder. The IMAP4 server is queried twice: first, we download the body structure of the message to learn which parts as images, and then we download these parts. The entire message itself is not downloaded.

To demonstrate that key names in FETCH requests and FETCH responses can be different, this sample downloads images in read-only mode (BODY.PEEK is used instead of BODY). Thus, running this sample won't cause the server to set "\Seen" flag for the message.

This sample can extract items for one message per command If you want to use it with multiple messages, see more advanced samples in DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) and BeginDownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object) topics. Also, that advanced samples show how to extract text bodies (not only attachments).

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.company.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Download body structure.
        EnvelopeCollection envs = imp.DownloadEnvelopes(imp.MessageCount.ToString(), false,
            EnvelopeParts.BodyStructure, 0);

        // The list of FETCH keys to request from the server.
        System.Collections.ArrayList fetchRequestKeys = new System.Collections.ArrayList();

        // The list of FETCH keys to expect from the server in return to the request of
        // items listed in fetchRequestKeys.
        System.Collections.ArrayList fetchResponseKeys = new System.Collections.ArrayList();

        // UID of the message for which we received the body structure.
        long uid = 0;

        if (envs.Count > 0)
        {
            Envelope env = envs[0];

            // Get body structures of all MIME parts as flat list.
            ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
            foreach (ImapBodyStructure part in parts)
            {
                if (part.ContentType.ToLower().IndexOf("image/") > -1)
                {
                    // For each image, we request its MIME part header and body
                    // (the IMAP4 protocol does not support getting the entire MIME
                    // part as a single block of data). Also note using .MIME instead of .HEADER
                    // because some mail servers don't support .HEADER syntax.
                    fetchRequestKeys.Add("BODY.PEEK[" + part.PartID + ".MIME]");
                    fetchRequestKeys.Add("BODY.PEEK[" + part.PartID + "]");

                    // For BODY.PEEK[...] request the server will return BODY[...] response.
                    fetchResponseKeys.Add("BODY[" + part.PartID + ".MIME]");
                    fetchResponseKeys.Add("BODY[" + part.PartID + "]");
                }
            }

            // Second time, we'll get message by its UID. This will avoid the situation
            // when new message arrives between two queries (and thus it could be possible
            // to download wrong message second time).
            uid = env.Uid;
        }

        if (uid > 0)
        {
            // Download images.
            envs = imp.DownloadEnvelopes(uid.ToString(), true,
                EnvelopeParts.Uid, 0, null,
                (string[])fetchRequestKeys.ToArray(typeof(string)));

            if (envs.Count > 0)
            {
                Envelope env = envs[0];

                for (int i = 0; i < fetchRequestKeys.Count; i += 2)
                {
                    // Get MIME part header data.
                    byte[] mimePartHeader = (byte[])env.GetEnvelopeItem(
                        (string)fetchResponseKeys[i], true);

                    // Get MIME part body data.
                    byte[] mimePartBody = (byte[])env.GetEnvelopeItem(
                        (string)fetchResponseKeys[i + 1], true);

                    // Build MIME part data from header data and body data.
                    byte[] mimePartData = new byte[mimePartHeader.Length + mimePartBody.Length];
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length);
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData,
                        mimePartHeader.Length, mimePartBody.Length);
                    mimePartHeader = null;
                    mimePartBody = null;

                    // Build Attachment object from the MIME part data.
                    MimePart part = MimePart.Parse(mimePartData);
                    Attachment picture = new Attachment(part);

                    // Save the image into C:\Temp folder.
                    picture.SaveToFolder(@"C:\Temp", false);
                }
            }
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.company.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Download body structure.
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(imp.MessageCount.ToString(), _
            False, EnvelopeParts.BodyStructure, 0)

        ' The list of FETCH keys to request from the server.
        Dim fetchRequestKeys As New System.Collections.ArrayList

        ' The list of FETCH keys to expect from the server in return to the request of
        ' items listed in fetchRequestKeys.
        Dim fetchResponseKeys As New System.Collections.ArrayList

        ' UID of the message for which we received the body structure.
        Dim uid As Long = 0
        If envs.Count > 0 Then
            Dim env As Envelope = envs(0)

            ' Get body structures of all MIME parts as flat list.
            Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()
            For Each part As ImapBodyStructure In parts
                If part.ContentType.ToLower().IndexOf("image/") > -1 Then
                    ' For each image, we request its MIME part header and body
                    ' (the IMAP4 protocol does not support getting the entire MIME
                    ' part as a single block of data). Also note using .MIME instead of .HEADER
                    ' because some mail servers don't support .HEADER syntax.
                    fetchRequestKeys.Add("BODY.PEEK[" & part.PartID & ".MIME]")
                    fetchRequestKeys.Add("BODY.PEEK[" & part.PartID & "]")

                    ' For BODY.PEEK[...] request the server will return BODY[...] response.
                    fetchResponseKeys.Add("BODY[" & part.PartID & ".MIME]")
                    fetchResponseKeys.Add("BODY[" & part.PartID & "]")
                End If
            Next

            ' Second time, we'll get message by its UID. This will avoid the situation
            ' when new message arrives between two queries (and thus it could be possible
            ' to download wrong message second time).
            uid = env.Uid
        End If

        If uid > 0 Then
            ' Download images.
            envs = imp.DownloadEnvelopes(uid.ToString(), True, EnvelopeParts.Uid, 0, _
                Nothing, CType(fetchRequestKeys.ToArray(GetType(String)), String()))

            If envs.Count > 0 Then
                Dim env As Envelope = envs(0)

                Dim i As Integer
                For i = 0 To fetchRequestKeys.Count - 1 Step 2
                    ' Get MIME part header data.
                    Dim mimePartHeader, mimePartBody As Byte()
                    mimePartHeader = env.GetEnvelopeItem(CType(fetchResponseKeys(i), String), True)

                    ' Get MIME part body data.
                    mimePartBody = env.GetEnvelopeItem(CType(fetchResponseKeys(i + 1), String), True)

                    ' Build MIME part data from header data and body data.
                    Dim mimePartData As Byte()
                    ReDim mimePartData(mimePartHeader.Length + mimePartBody.Length)
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length)
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData, mimePartHeader.Length, mimePartBody.Length)
                    mimePartHeader = Nothing
                    mimePartBody = Nothing

                    ' Build Attachment object from the MIME part data.
                    Dim part As MimePart = MimePart.Parse(mimePartData)
                    Dim picture As New Attachment(part)

                    ' Save the image into C:\Temp folder.
                    picture.SaveToFolder("C:\Temp", False)
                Next
            End If
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace
ImapDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)


Envelope.GetUtf7DecodedGmailLabels Method

EnvelopeGetUtf7DecodedGmailLabels Method
Gets the list of Gmail-specific labels of the message decoded from UTF-7M encoding.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GetUtf7DecodedGmailLabels()
Public Function GetUtf7DecodedGmailLabels As String()

Return Value

Type: String
The list of strings, or or a null reference (Nothing in Visual Basic) in case if this value is not available (usually, if the server is not Gmail or GmailLabels was not requested when downloading envelopes).
Remarks
This method does not change the value of GmailLabels, it modifies only the returned copy.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.HasSystemFlag Method

EnvelopeHasSystemFlag Method
Checks if the message has a certain system flag set.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool HasSystemFlag(
    SystemMessageFlags flag
)
Public Function HasSystemFlag (
    flag As SystemMessageFlags
) As Boolean

Parameters

flag
Type: MailBee.ImapMailSystemMessageFlags
A system flag to check.

Return Value

Type: Boolean
true if the message flags include the flag provided; otherwise, false.
Remarks
It's a helper method. Alternatively, you can easily check system flags by using logical AND operation against [!:SystemFlags] value of Flags property. E.g. if ((envelope.Flags.SystemFlags & SystemMessageFlags.Answered) > 0) would be equivalent to if (envelope.HasSystemFlag(SystemMessageFlags.Answered)) (in C# syntax).
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope Properties

Envelope Properties

The Envelope type exposes the following members.

Properties
 | Name | Description
Public property | Bcc | Gets EmailAddressCollection object representing "BCC:" recipients of the message.
Public property | BodyStructure | Gets the information about structure of the message.
Public property | Cc | Gets EmailAddressCollection object representing "CC:" recipients of the message.
Public property | Date | Gets the date and time when the message was composed.
Public property | DateReceived | Gets the date and time when the message was received by the mail server.
Public property | DatesAsUtc | Indicates if MailBee should return date and time according to UTC standard.
Public property | ExtraHeaders | Gets a collection of additional message headers which have been explicitly requested from the server.
Public property | Flags | Gets MessageFlagSet object containing system and custom flags of the message.
Public property | From | Gets EmailAddress object representing "From:" field of the message.
Public property | GmailLabels | Gets the list of Gmail-specific labels associated with the message.
Public property | GmailMessageID | Gets the Gmail-specific message-id.
Public property | GmailThreadID | Gets the Gmail-specific thread-id.
Public property | InReplyTo | Gets the value of "In-Reply-To" header of the message.
Public property | IsValid | Indicates if the envelope data has been successfully parsed.
Public property | MessageID | Gets the value of "Message-ID" header of the message.
Public property | MessageNumber | Gets the ordinal number of the message in the folder.
Public property | MessagePreview | Gets the entire or partial mail message.
Public property | ReplyTo | Gets EmailAddress object representing "Reply-To:" field of the message.
Public property | SafeMode | Gets or sets whether empty values instead of a null reference (Nothing in Visual Basic) should be returned when the corresponding fields are not available in the data received from the server.
Public property | Sender | Gets EmailAddress object representing the information about the actual sender of the message.
Public property | Size | Gets the length of the entire message (in bytes) on the mail server.
Public property | Subject | Gets the subject line of the message.
Public property | To | Gets EmailAddressCollection object representing "To:" recipients of the message.
Public property | Uid | Gets UID (Unique-ID) assigned to the message in the folder on the mail server.
Top
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Bcc Property

EnvelopeBcc Property
Gets EmailAddressCollection object representing "BCC:" recipients of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Bcc { get; }
Public ReadOnly Property Bcc As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to EmailAddressCollection object representing "BCC:" recipients of the message.
Remarks
In most cases, this property will return empty EmailAddressCollection object (or a null reference if SafeMode is false) because BCC information is usually stripped away from mail messages when they are sent.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.BodyStructure Property

EnvelopeBodyStructure Property
Gets the information about structure of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapBodyStructure BodyStructure { get; }
Public ReadOnly Property BodyStructure As ImapBodyStructure
    Get

Property Value

Type: ImapBodyStructure
A reference to ImapBodyStructure object containing the information about the message structure if it was requested, or a null reference (Nothing in Visual Basic) if this information is not available or was not requested.
Remarks
The common use of body structures is obtaining attachment names without downloading entire messages (see the code sample in Envelope topic). Also, the body structure contains charset information of the message which is needed for correct parsing of envelopes of international messages.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Cc Property

EnvelopeCc Property
Gets EmailAddressCollection object representing "CC:" recipients of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Cc { get; }
Public ReadOnly Property Cc As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to EmailAddressCollection object representing "CC:" recipients of the message.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Date Property

EnvelopeDate Property
Gets the date and time when the message was composed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime Date { get; }
Public ReadOnly Property Date As DateTime
    Get

Property Value

Type: DateTime
A DateTime value indicating when the message was created, or MinValue if this information is not available.
Remarks
The server obtains this value from "Date:" header of the mail message.
Note Note
DatesAsUtc property can be set to force this property return UTC (GMT) date.

In case if you encounter a message with invalid values in Date (for instance, 79 seconds while 59 is the maximum allowed limit), you can consider enabling FixBadDates to let MailBee tolerate such errors if they are not significant.

See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.DateReceived Property

EnvelopeDateReceived Property
Gets the date and time when the message was received by the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime DateReceived { get; }
Public ReadOnly Property DateReceived As DateTime
    Get

Property Value

Type: DateTime
A DateTime value indicating when the message was received by the mail server, or MinValue if this information is not available.
Remarks
This value is obtained from INTERNALDATE field of IMAP4 FETCH response. This differs from behavior of DateReceived property which determines this date from timestamps of the message (this allows MailMessage object to determine receipt date even if the message was received from other source than IMAP4 server).
Note Note
DatesAsUtc property can be set to force this property return UTC (GMT) date.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.DatesAsUtc Property

EnvelopeDatesAsUtc Property
Indicates if MailBee should return date and time according to UTC standard.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DatesAsUtc { get; set; }
Public Property DatesAsUtc As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, Date and DateReceived properties will return date and time according to UTC (GMT) standard; otherwise, the returned date is timezone-corrected to match local time of the computer running MailBee. The default value is false.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.ExtraHeaders Property

EnvelopeExtraHeaders Property
Gets a collection of additional message headers which have been explicitly requested from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection ExtraHeaders { get; }
Public ReadOnly Property ExtraHeaders As HeaderCollection
    Get

Property Value

Type: HeaderCollection
A reference to HeaderCollection object containing extra headers of the message if they were requested, or a null reference (Nothing in Visual Basic) if this information is not available or was not requested.
Remarks
See DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) topic on how to obtain non-standard message headers within the envelope.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Flags Property

EnvelopeFlags Property
Gets MessageFlagSet object containing system and custom flags of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageFlagSet Flags { get; }
Public ReadOnly Property Flags As MessageFlagSet
    Get

Property Value

Type: MessageFlagSet
A reference to the MessageFlagSet object containing system and custom flags of the message.
Remarks
You can use HasSystemFlag(SystemMessageFlags) method to check if the message has a certain system flag (like Seen, Flagged, etc).
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.From Property

EnvelopeFrom Property
Gets EmailAddress object representing "From:" field of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress From { get; }
Public ReadOnly Property From As EmailAddress
    Get

Property Value

Type: EmailAddress
A reference to EmailAddress object representing "From:" field of the message.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.GmailLabels Property

EnvelopeGmailLabels Property
Gets the list of Gmail-specific labels associated with the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GmailLabels { get; }
Public ReadOnly Property GmailLabels As String()
    Get

Property Value

Type: String
A string array containing Gmail labels of the message, or a null reference (Nothing in Visual Basic) in case if this value is not available (usually, if the server is not Gmail or GmailLabels was not requested when downloading envelopes).
Remarks
Gmail treats labels as folders for the purposes of IMAP. Thus, labels can be folder names but also there can be custom labels and therefore the message can have multiple labels attached while it cannot be in multiple folders. To use this value, make sure the mail server is Gmail-compatible ("x-gm-ext-1" capability must be listed in GetExtensions results).
Note Note
By default, labels names are UTF7M-encoded (for instance, when they contain international characters). To get human-readable version of these labels, use GetUtf7DecodedGmailLabels method.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.GmailMessageID Property

EnvelopeGmailMessageID Property
Gets the Gmail-specific message-id.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GmailMessageID { get; }
Public ReadOnly Property GmailMessageID As String
    Get

Property Value

Type: String
A string containing a positive 64-bit number, or a null reference (Nothing in Visual Basic) in case if this value is not available (usually, if the server is not Gmail or GmailMessageID was not requested when downloading envelopes).
Remarks
Gmail provides a unique message ID for each email so that a unique message may be identified across multiple folders. To use this value, make sure the mail server is Gmail-compatible ("x-gm-ext-1" capability must be listed in GetExtensions results).
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.GmailThreadID Property

EnvelopeGmailThreadID Property
Gets the Gmail-specific thread-id.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GmailThreadID { get; }
Public ReadOnly Property GmailThreadID As String
    Get

Property Value

Type: String
A string containing a positive 64-bit number, or a null reference (Nothing in Visual Basic) in case if this value is not available (usually, if the server is not Gmail or GmailThreadID was not requested when downloading envelopes).
Remarks
Gmail provides a thread ID to associate groups of messages in the same manner as in the Gmail web interface. To use this value, make sure the mail server is Gmail-compatible ("x-gm-ext-1" capability must be listed in GetExtensions results).
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.InReplyTo Property

EnvelopeInReplyTo Property
Gets the value of "In-Reply-To" header of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string InReplyTo { get; }
Public ReadOnly Property InReplyTo As String
    Get

Property Value

Type: String
The string containing the value of "In-Reply-To" header of the message.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.IsValid Property

EnvelopeIsValid Property
Indicates if the envelope data has been successfully parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if the envelope data requested from the server has been successfully parsed; otherwise, false.
Remarks

This property exists for compatibility with not fully IMAP4-compliant servers. Due to complexity of IMAP4 responses, some implementation still fail to produce syntactically correct IMAP4 responses in some cases.

The developer can use this property (or subscribe to ErrorOccurred event, see code sample in Envelope topic) to determine if all the data is correct.

Note Note
This property (if true) does not indicate all properties of Envelope object return actual values. It only relates to the properties for which the data was requested from the server. For instance, if DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method was called with parts parameter set to Uid, only Uid (and MessageNumber, which is always available) properties will be set and IsValid will still return true. However, if UID value could not be parsed in the last case, IsValid would return false.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.MessageID Property

EnvelopeMessageID Property
Gets the value of "Message-ID" header of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MessageID { get; }
Public ReadOnly Property MessageID As String
    Get

Property Value

Type: String
The string containing the value of "Message-ID" header of the message.
Remarks

The server obtains this value from the header section of the message. This is not Unique-ID value (Uid) assigned by the server to each message in the folder. For instance, if the message is moved between folders, its UID changes while Message-ID does not.

Usually, Message-ID is assigned to the message when it's composed. Thus, Message-ID identifies the message content. For instance, if the same message is placed into the IMAP4 folder twice, both copies will have the same Message-ID (while their Uid values will be different).

See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.MessageNumber Property

EnvelopeMessageNumber Property
Gets the ordinal number of the message in the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageNumber { get; }
Public ReadOnly Property MessageNumber As Integer
    Get

Property Value

Type: Int32
A positive integer value representing the ordinal index of the message in the IMAP4 folder.
Remarks
Unlike Uid values, ordinal message numbers can change due to deleting and expunging messages from the folder.
Note Note
MessageNumber value is guaranteed to be correct even if the envelope could not be parsed (IsValid is true). Thus, the developer can always locate the message whose envelope could not be parsed and which needs to be examined in some other way.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.MessagePreview Property

EnvelopeMessagePreview Property
Gets the entire or partial mail message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MessagePreview { get; }
Public ReadOnly Property MessagePreview As MailMessage
    Get

Property Value

Type: MailMessage
A reference to MailMessage object containing the entire message or its initial part (preview), or a null reference (Nothing in Visual Basic) if this information is not available or was not requested.
Remarks
Depending on parameter values of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method, this property may return the entire message, its header section, its header section + part of the body section, or a null reference. See DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) topic on how to obtain the mail message within the envelope.
Note Note
To obtain just mail messages or message headers (without flags, etc), it's convenient to use methods such as DownloadEntireMessage(Int64, Boolean) and DownloadMessageHeaders(String, Boolean), which call DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) inside, filter the results, and return MailMessage and MailMessageCollection objects.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.ReplyTo Property

EnvelopeReplyTo Property
Gets EmailAddress object representing "Reply-To:" field of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ReplyTo { get; }
Public ReadOnly Property ReplyTo As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to EmailAddress object representing "Reply-To:" field of the message.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.SafeMode Property

EnvelopeSafeMode Property
Gets or sets whether empty values instead of a null reference (Nothing in Visual Basic) should be returned when the corresponding fields are not available in the data received from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SafeMode { get; set; }
Public Property SafeMode As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, string properties of Envelope object will return empty string and e-mail address and flags related properties will return empty objects when the corresponding information is not available in the envelope data; otherwise, a null reference will be returned in such cases. The default value is true.
Remarks

The developer may set this property to false if the application needs to distinguish empty values from missing values.

This property may affect return values of the following properties:

  • Bcc
  • Cc
  • Flags
  • From
  • InReplyTo
  • MessageID
  • ReplyTo
  • Sender
  • Subject
  • To

Note Note
This property is not connected with Global.SafeMode property in any way.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Sender Property

EnvelopeSender Property
Gets EmailAddress object representing the information about the actual sender of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress Sender { get; }
Public ReadOnly Property Sender As EmailAddress
    Get

Property Value

Type: EmailAddress
A reference to EmailAddress object representing the information about the actual sender of the message.
Remarks
Usually, this property will return the same information as From property. However, if the message was sent from the address other than "From:", these properties will return different results.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Size Property

EnvelopeSize Property
Gets the length of the entire message (in bytes) on the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Size { get; }
Public ReadOnly Property Size As Integer
    Get

Property Value

Type: Int32
The length of the entire message contents (in bytes) on the mail server, or -1 if this information is not available.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Subject Property

EnvelopeSubject Property
Gets the subject line of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Subject { get; }
Public ReadOnly Property Subject As String
    Get

Property Value

Type: String
The string containing the message subject.
Remarks
If the subject line is encoded, MailBee decodes it in human-readable form.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.To Property

EnvelopeTo Property
Gets EmailAddressCollection object representing "To:" recipients of the message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection To { get; }
Public ReadOnly Property To As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to EmailAddressCollection object representing "To:" recipients of the message.
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


Envelope.Uid Property

EnvelopeUid Property
Gets UID (Unique-ID) assigned to the message in the folder on the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long Uid { get; }
Public ReadOnly Property Uid As Long
    Get

Property Value

Type: Int64
A positive 32-bit numeric value indicating UID of the message, or -1 if this information is not available.
Remarks
Unlike ordinal message numbers (MessageNumber property), UIDs persist between operations which re-order messages in a folder (such as deleting and expunging messages). Also, UIDs should persist between different IMAP sessions (some old IMAP4 implementations, however, may violate this rule, see UidValidity topic for details).
See Also

Reference

Envelope Class
MailBee.ImapMail Namespace


EnvelopeCollection Class

EnvelopeCollection Class
Provides properties and methods for examining, extending, and reversing the collection of the Envelope objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailEnvelopeCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EnvelopeCollection : CollectionBase
Public Class EnvelopeCollection
    Inherits CollectionBase

The EnvelopeCollection type exposes the following members.

Constructors
 | Name | Description
Public method | EnvelopeCollection | Initializes a new instance of the EnvelopeCollection class
Top
Methods
 | Name | Description
Public method | Add(Envelope) | Adds the specified Envelope object to the collection.
Public method | Add(EnvelopeCollection) | Adds another EnvelopeCollection to the current collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | Reverse | Reverses the order of the list of the messages that are stored in the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the Envelope object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope


EnvelopeCollection Constructor

EnvelopeCollection Constructor
Initializes a new instance of the EnvelopeCollection class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection()
Public Sub New
See Also

Reference

EnvelopeCollection Class
MailBee.ImapMail Namespace


EnvelopeCollection Methods

EnvelopeCollection Methods

The EnvelopeCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add(Envelope) | Adds the specified Envelope object to the collection.
Public method | Add(EnvelopeCollection) | Adds another EnvelopeCollection to the current collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | Reverse | Reverses the order of the list of the messages that are stored in the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

EnvelopeCollection Class
MailBee.ImapMail Namespace


EnvelopeCollection.Add Method

EnvelopeCollectionAdd Method
Overload List
 | Name | Description
Public method | Add(Envelope) | Adds the specified Envelope object to the collection.
Public method | Add(EnvelopeCollection) | Adds another EnvelopeCollection to the current collection.
Top
See Also

Reference

EnvelopeCollection Class
MailBee.ImapMail Namespace


EnvelopeCollection.Add Method (Envelope)

EnvelopeCollectionAdd Method (Envelope)
Adds the specified Envelope object to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    Envelope item
)
Public Sub Add (
    item As Envelope
)

Parameters

item
Type: MailBee.ImapMailEnvelope
The Envelope object that should be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | item is a null reference (Nothing in Visual Basic).
See Also

Reference

EnvelopeCollection Class
Add Overload
MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope


EnvelopeCollection.Add Method (EnvelopeCollection)

EnvelopeCollectionAdd Method (EnvelopeCollection)
Adds another EnvelopeCollection to the current collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    EnvelopeCollection items
)
Public Sub Add (
    items As EnvelopeCollection
)

Parameters

items
Type: MailBee.ImapMailEnvelopeCollection
The EnvelopeCollection object whose items should be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | items is a null reference (Nothing in Visual Basic).
See Also

Reference

EnvelopeCollection Class
Add Overload
MailBee.ImapMail Namespace


EnvelopeCollection.Reverse Method

EnvelopeCollectionReverse Method
Reverses the order of the list of the messages that are stored in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reverse()
Public Sub Reverse
Remarks

For instance, this method can be used to display the list of message envelopes received from mail server in descending order (from new to old ones). By default, mail server returns message envelopes in ascending order (from old to new ones). This method allows the developer to have this collection re-sorted in descending order.

This method is a counterpart of the similar Reverse method of MailMessageCollection class.

See Also

Reference

EnvelopeCollection Class
MailBee.ImapMail Namespace
Pop3DownloadMessageHeaders(Int32, Int32, Int32)


EnvelopeCollection Properties

EnvelopeCollection Properties

The EnvelopeCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the Envelope object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

EnvelopeCollection Class
MailBee.ImapMail Namespace


EnvelopeCollection.Item Property

EnvelopeCollectionItem Property
Gets the Envelope object at the specified zero-based index in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Envelope this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Envelope
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the Envelope object in the collection.

Property Value

Type: Envelope
A Envelope object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

EnvelopeCollection Class
MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope


EnvelopeParts Enumeration

EnvelopeParts Enumeration
Defines message elements available for download using DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum EnvelopeParts
<FlagsAttribute>
Public Enumeration EnvelopeParts
Members
Member name | Value | Description
Uid | 0 | Request UID of the message. Since this value is 0, the UID is always requested. Also, the server always returns the ordinal number of the message in the folder (MessageNumber).
Flags | 1 | Request the message flags.
InternalDate | 2 | Request the datetime value assigned by the server to message (usually, it's the date when the message was received by the server).
Rfc822Size | 4 | Request the length of the entire message in bytes.
Envelope | 8 | Request the ENVELOPE information of the message.
BodyStructure | 16 | Request the body structure of the message.
MessagePreview | 32 | Request the message header or the entire message. This item can be used in conjunction with bodyPreviewSize parameter of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.
MailBeeEnvelope | 15 | The combination of Flags, InternalDate, Rfc822Size, and Envelope.
All | 63 | The combination of MailBeeEnvelope, BodyStructure, and MessagePreview. Note that Gmail-specific fields are not included.
GmailMessageID | 64 | Request the Gmail-specific message-id (with it, unique message may be identified across multiple folders). This message-id is a string containing 64-bit positive number.
GmailThreadID | 128 | Request the Gmail-specific thread-id (with it, you can group multiple messages in conversations). This thread-id is a string containing 64-bit positive number.
GmailLabels | 256 | Request the Gmail-specific list of labels associated with the message.
Remarks

In the IMAP4 protocol, all message related information is downloaded using FETCH command. DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method issues FETCH command, processes its responses, and represents it to the application as the EnvelopeCollection of Envelope objects where each object represents a single FETCH response (one response corresponds to a single message).

With FETCH commands, it's possible to download any parts or attributes of mail messages. The most common attribute is ENVELOPE (that's why MailBee's object which encapsulates FETCH response is called Envelope). However, with FETCH response, it's also possible to download any other elements of mail messages (and it's even not necessary to download ENVELOPE element itself).

Depending on which elements of FETCH response were requested during DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method call, certain properties of the Envelope objects within the returned collection may contain empty values or useful information. For instance, if only Uid was requested, the only property values which will be set in the Envelope object are Uid and MessageNumber.

Uid and MessageNumber property values are always available. To obtain other message-related information, the developer should request the corresponding items from the server when calling DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method. The items to be downloaded need to be specified in parts parameter of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.

The following list shows relationships beetween EnvelopeParts elements and Envelope object properties which are set when the corresponding elements have been requested during DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method call:

EnvelopeParts element | Envelope property
Flags | Flags
InternalDate | DateReceived
Rfc822Size | Size
Envelope | Bcc, Cc, Date, From, InReplyTo, MessageID, ReplyTo, Sender, Subject, To
BodyStructure | BodyStructure
MessagePreview | MessagePreview
MailBeeEnvelope | Combination of effects of Flags, InternalDate, Rfc822Size, and Envelope
All | Combination of effects of MailBeeEnvelope, BodyStructure, and MessagePreview
Gmail specific message-id, thread-id, label list | Can be used only with Gmail-compatible server (The mail server must support Gmail search syntax ("x-gm-ext-1" capability must be listed in GetExtensions results).

Note Note
DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method also allows the application to download FETCH items by their names. The developer can use this to download the specific MIME parts of the message, the specific headers, or if the particular server supports non-standard FETCH elements the developer interested in.
See Also

Reference

MailBee.ImapMail Namespace
ImapDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)
MailBee.ImapMailEnvelope


Folder Class

Folder Class
Represents a folder (mailbox in IMAP4 terms) of the account on the mail server.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailFolder

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Folder
Public Class Folder

The Folder type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Delimiter | Gets the character which is used as a hierarchy delimiter of separate levels of folder names.
Public property | Flags | Gets the set of flags associated with the folder.
Public property | IsValid | Gets if the server response containing the folder information has been successfully parsed.
Public property | Name | Gets the full name of the folder including parent folder names if any.
Public property | NestingLevel | Gets the level of nesting of this folder into parent folders.
Public property | RawName | Gets the full name of the folder as was returned by the server including parent folder names if any.
Public property | ShortName | Gets the short name (without parent folder names if any) of the folder.
Top
Remarks
The list of folders can be obtained using DownloadFolders(Boolean, String, String) method of Imap component. In any case, an account on the mail server is guaranteed to contain at least "INBOX" folder (case-insensitive). Also, IMAP4 accounts often contain folders such as "Sent", "Drafts", etc.
See Also

Reference

MailBee.ImapMail Namespace
ImapDownloadFolders(Boolean, String, String)
MailBee.ImapMailFolderCollection


Folder Methods

Folder Methods

The Folder type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Folder Class
MailBee.ImapMail Namespace


Folder Properties

Folder Properties

The Folder type exposes the following members.

Properties
 | Name | Description
Public property | Delimiter | Gets the character which is used as a hierarchy delimiter of separate levels of folder names.
Public property | Flags | Gets the set of flags associated with the folder.
Public property | IsValid | Gets if the server response containing the folder information has been successfully parsed.
Public property | Name | Gets the full name of the folder including parent folder names if any.
Public property | NestingLevel | Gets the level of nesting of this folder into parent folders.
Public property | RawName | Gets the full name of the folder as was returned by the server including parent folder names if any.
Public property | ShortName | Gets the short name (without parent folder names if any) of the folder.
Top
See Also

Reference

Folder Class
MailBee.ImapMail Namespace


Folder.Delimiter Property

FolderDelimiter Property
Gets the character which is used as a hierarchy delimiter of separate levels of folder names.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Delimiter { get; }
Public ReadOnly Property Delimiter As String
    Get

Property Value

Type: String
The string containing a single character used to separate levels of hierarchy of folder names, or a null reference (Nothing in Visual Basic) if folder names are flat and nested folders are not supported.
Remarks
The typical values returned by this property are: "/", ".", "\".
Note Note
This property returns a null reference (Nothing in Visual Basic) if IsValid is false.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace


Folder.Flags Property

FolderFlags Property
Gets the set of flags associated with the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderFlags Flags { get; }
Public ReadOnly Property Flags As FolderFlags
    Get

Property Value

Type: FolderFlags
A FolderFlags value containing the set of flags associated with the folder.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace


Folder.IsValid Property

FolderIsValid Property
Gets if the server response containing the folder information has been successfully parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if the server response containing the folder information was correct; false otherwise.
Remarks
Due to complexity of IMAP4 responses, some server implementations fail to produce 100% correct responses sometimes. If MailBee cannot parse certain folder response, it returns Folder object having IsValid set to false.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace


Folder.Name Property

FolderName Property
Gets the full name of the folder including parent folder names if any.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; }
Public ReadOnly Property Name As String
    Get

Property Value

Type: String
The string containing the full name of the folder including parent folder names if any.
Remarks

The typical values returned by this property are: "Inbox", "Sent.Orders", "INBOX\From John Doe".

To get short name of the folder (without parent path), the developer can use ShortName property. For instance, the full folder names from the paragraph above correspond to the following short names: "Inbox", "Orders", "From John Doe".

To get a character which is used to delimit folder levels on the current server, the developer can use Delimiter property. For instance, ShortName of "Sent.Orders" is "Sent" only if Delimiter is ".". If, however, the delimiter is another character, ShortName will return "Sent.Orders". The most popular delimiter nowadays is "/".

MailBee automatically decodes international folder names presented in UTF-7 Modified encoding (see IMAP4 protocol specification in RFC3501 for details on UTF-7 Modified encoding). However, the original name (not decoded from UTF-7 Modified) is still available via RawName property.

Note Note
This property returns a null reference (Nothing in Visual Basic) if IsValid is false.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace
FolderShortName
FolderRawName
FolderDelimiter
FolderNestingLevel


Folder.NestingLevel Property

FolderNestingLevel Property
Gets the level of nesting of this folder into parent folders.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NestingLevel { get; }
Public ReadOnly Property NestingLevel As Integer
    Get

Property Value

Type: Int32
A zero-based integer value indicating the level of nesting of this folder into parent folders if any. If the folder is a top level folder, this value is 0.
Remarks

For instance, if the full name of the folder is "Inbox/Orders/April 2006" and Delimiter is "/", this property will return 2.

The common use of this property is displaying folder list with indentations according to folder nesting levels. You can find the corresponding code sample in DownloadFolders topic.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace


Folder.RawName Property

FolderRawName Property
Gets the full name of the folder as was returned by the server including parent folder names if any.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RawName { get; }
Public ReadOnly Property RawName As String
    Get

Property Value

Type: String
The string containing the full name of the folder as was returned by the server including parent folder names if any.
Remarks
Unlike Name, RawName is not automatically decoded from UTF-7 Modified encoding. The developer can use RawName in conjuction with Utf7EncodeFolderNames set to false to preserve the original names of folders when passing them back to the server. This can be useful if the account contains some folder names encoded with the encoding different from UTF-7M. In this case, automatic re-encoding them into UTF-7M would cause problems.
Note Note
This property returns a null reference (Nothing in Visual Basic) if IsValid is false.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace
FolderName


Folder.ShortName Property

FolderShortName Property
Gets the short name (without parent folder names if any) of the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ShortName { get; }
Public ReadOnly Property ShortName As String
    Get

Property Value

Type: String
The string containing the folder's short name without any delimiters or parent folder names.
Remarks
If the folder is a top level folder, its short name is equal to its full name.
See Also

Reference

Folder Class
MailBee.ImapMail Namespace
FolderNestingLevel


FolderCollection Class

FolderCollection Class
Provides properties and methods for examining the collection of the Folder objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailFolderCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class FolderCollection : CollectionBase
Public Class FolderCollection
    Inherits CollectionBase

The FolderCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | Reverse | Reverses the order of the list of the folders that are stored in the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the Folder object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope


FolderCollection Methods

FolderCollection Methods

The FolderCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | Reverse | Reverses the order of the list of the folders that are stored in the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

FolderCollection Class
MailBee.ImapMail Namespace


FolderCollection.Reverse Method

FolderCollectionReverse Method
Reverses the order of the list of the folders that are stored in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reverse()
Public Sub Reverse
Remarks
For instance, this method can be used to optimize deleting of folders with their subfolders. Because it's not usually permitted to delete a folder which contains subfolders, these subfolders must be removed first. However, mail servers usually place subfolders after their parent folders in the returned folder list. Thus, it's more efficient to iterate through this collection in descending order, removing subfolders first and their parent folders last. See DeleteFolder(String) topic for the sample code.
See Also

Reference

FolderCollection Class
MailBee.ImapMail Namespace
ImapDownloadFolders(Boolean, String, String)
ImapDeleteFolder(String)


FolderCollection Properties

FolderCollection Properties

The FolderCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the Folder object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

FolderCollection Class
MailBee.ImapMail Namespace


FolderCollection.Item Property

FolderCollectionItem Property
Gets the Folder object at the specified zero-based index in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Folder this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Folder
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the Folder object in the collection.

Property Value

Type: Folder
A Folder object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

FolderCollection Class
MailBee.ImapMail Namespace
MailBee.ImapMailFolder


FolderFlags Enumeration

FolderFlags Enumeration
Defines the standard flags which can be set or examined for IMAP4 folders (mailboxes).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum FolderFlags
<FlagsAttribute>
Public Enumeration FolderFlags
Members
Member name | Value | Description
None | 0 | No flags set.
Noinferiors | 1 | It is not possible for any child levels of hierarchy to exist under this name; no child levels exist now and none can be created in the future.
Noselect | 2 | It is not possible to use this name as a selectable folder.
Marked | 4 | The folder has been marked "interesting" by the server; the folder probably contains messages that have been added since the last time the folder was selected. Note: marked folder is not the same as subscribed folder. It's up to the client to subscribe/unsubscribe folders; it's up to the server to mark/unmark folders.
Unmarked | 8 | The folder does not contain any additional messages since the last time the folder was selected.
Inbox | 16 | The folder is INBOX. Only available in Gmail (XLIST command can return localized INBOX name, this flag lets the client find which folder is actually INBOX).
Drafts | 32 | The folder is used for draft items. Specifc to XLIST and SPECIAL-USE extensions.
Sent | 64 | The folder stores sent items. Specifc to XLIST and SPECIAL-USE extensions.
Spam | 128 | The folder stores junk e-mails. The actual flag name is "\Junk" or "\Spam". Specifc to XLIST and SPECIAL-USE extensions.
Trash | 256 | The folder stores deleted e-mails. Specific to XLIST and SPECIAL-USE extensions.
Starred | 512 | The folder is an alias folder which includes some "favorite" e-mails from other folders, you should check e-mail in this folder with care as you may get doubles of some e-mails from other folders if you do. The actual flag name is "\Flagged" or "\Starred". Specifc to XLIST and SPECIAL-USE extensions.
AllMail | 1024 | The folder is an alias folder which includes e-mail from all other folders, you should not check e-mail in it as you'll get doubles of the e-mails in other folders if you do. The actual flag name is "\AllMail" or "\All". Specific to XLIST and SPECIAL-USE extensions.
Important | 2048 | The folder is an alias folder which includes some "important" e-mails from other folders, you should check e-mail in this folder with care as you may get doubles of some e-mails from other folders if you do. Specific to Gmail.
Archive | 4096 | This folder is used to archive messages. The meaning of an "archival" mailbox is server-dependent. Specific to SPECIAL-USE extension.
HasChildren | 8192 | The folder has sub-folders. Specific to CHILDREN extension.
HasNoChildren | 16384 | The folder does not have sub-folders, but they can be created there. If the folder cannot have sub-folders at all, it will bear Noinferiors flag instead of HasNoChildren. Specific to CHILDREN extension.
Remarks
To examine folder flags, the developer can use DownloadFolders(Boolean, String, String) method to obtain the collection of folders, and then iterate through returned collection and examine Flags property value for each Folder object in the collection.

Some flags which denote well-known folder types (like Sent, Drafts) can only be returned in response to XLIST command (only supported by some servers) or by the server which supports SPECIAL-USE extension. Gmail supports both XLIST and SPECIAL-USE (although it does not actually advertize SPECIAL-USE support in the capabilities). See UseXList property for details.

Standard LIST command will return flags for well-known folder types only if SPECIAL-USE extension is supported by the IMAP server. LSUB command (list subscribed folders only) MAY return these extended flags if SPECIAL-USE is supported (Gmail does, for instance) but it's up to the server implementation.

HasChildren and HasNoChildren flags can only be returned if the server supports CHILDREN extension. Gmail, Yahoo, Microsoft (Outlook.com, Hotmail.com, Live.com) and most other major providers support it.

See Also

Reference

MailBee.ImapMail Namespace
FolderFlags


FolderQuota Class

FolderQuota Class
Represents a resource usage and quota indicator for the entire account or a single folder of this account.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailFolderQuota

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class FolderQuota
Public Class FolderQuota

The FolderQuota type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | CurrentMessageCount | Gets the number of messages currently existing in the account or folder the quota applies to.
Public property | CurrentStorageSize | Gets the size (in bytes) of the currently used space in the account or folder the quota applies to.
Public property | MaxMessageCount | Gets the maximum message number limit for the account or folder the quota applies to.
Public property | MaxStorageSize | Gets the storage limit (in bytes) for the account or folder the quota applies to.
Public property | QuotaName | Gets the name of the quota.
Top
Remarks

Quotas provide the convenient way of determining the maximum and used size of account/folder storage. To obtain quotas, the developer can use GetAccountQuota or GetFolderQuota(String) methods.

However, the IMAP4 server must support QUOTA capability in order to take advantage of quotas. The developer may check if the server supports QUOTA using GetExtension(String) method passing "QUOTA" as name parameter value. See GetAccountQuota topic for the sample code.

Note Note
Even if the servers supports QUOTA capability, there is no guarantee all the properties of FolderQuota object will be set. This is not error, it just means the account or folder has no restrictions on the particular resource usage. For instance, MaxMessageCount and CurrentMessageCount may return -1 which means the mail server does not care about number of messages in the account. Also, QuotaName can return a null reference (Nothing in Visual Basic) if there is no quota set for this particular account or folder.
See Also

Reference

MailBee.ImapMail Namespace
ImapGetAccountQuota
ImapGetFolderQuota(String)
ImapGetExtension(String)


FolderQuota Methods

FolderQuota Methods

The FolderQuota type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderQuota Properties

FolderQuota Properties

The FolderQuota type exposes the following members.

Properties
 | Name | Description
Public property | CurrentMessageCount | Gets the number of messages currently existing in the account or folder the quota applies to.
Public property | CurrentStorageSize | Gets the size (in bytes) of the currently used space in the account or folder the quota applies to.
Public property | MaxMessageCount | Gets the maximum message number limit for the account or folder the quota applies to.
Public property | MaxStorageSize | Gets the storage limit (in bytes) for the account or folder the quota applies to.
Public property | QuotaName | Gets the name of the quota.
Top
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderQuota.CurrentMessageCount Property

FolderQuotaCurrentMessageCount Property
Gets the number of messages currently existing in the account or folder the quota applies to.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int CurrentMessageCount { get; }
Public ReadOnly Property CurrentMessageCount As Integer
    Get

Property Value

Type: Int32
The non-negative Int32 value containing the number of messages currently existing in the account or folder the quota applies to, or -1 if this information is not available.
Remarks
Nowadays, most servers limit maximum storage size only (maximum number of messages is not limited). Due to this, CurrentMessageCount and MaxMessageCount properties usually return -1.
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderQuota.CurrentStorageSize Property

FolderQuotaCurrentStorageSize Property
Gets the size (in bytes) of the currently used space in the account or folder the quota applies to.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long CurrentStorageSize { get; }
Public ReadOnly Property CurrentStorageSize As Long
    Get

Property Value

Type: Int64
The non-negative Int64 value containing the size (in bytes) of the currently used space in the account or folder the quota applies to, or -1 if this information is not available.
Remarks
This value, if non-negative, is a multiple of 1024 (this is because the mail server actually returns this value in kilobytes). Thus, the developer can divide it by 1024 to get the value returned by the server.
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderQuota.MaxMessageCount Property

FolderQuotaMaxMessageCount Property
Gets the maximum message number limit for the account or folder the quota applies to.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxMessageCount { get; }
Public ReadOnly Property MaxMessageCount As Integer
    Get

Property Value

Type: Int32
The non-negative Int32 value containing the maximum message number limit for the account or folder the quota applies to, or -1 if this information is not available.
Remarks
Nowadays, most servers limit maximum storage size only (maximum number of messages is not limited). Due to this, CurrentMessageCount and MaxMessageCount properties usually return -1.
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderQuota.MaxStorageSize Property

FolderQuotaMaxStorageSize Property
Gets the storage limit (in bytes) for the account or folder the quota applies to.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long MaxStorageSize { get; }
Public ReadOnly Property MaxStorageSize As Long
    Get

Property Value

Type: Int64
The non-negative Int64 value containing the storage limit (in bytes) for the account or folder the quota applies to, or -1 if this information is not available.
Remarks
This value, if non-negative, is a multiple of 1024 (this is because the mail server actually returns this value in kilobytes). Thus, the developer can divide it by 1024 to get the value returned by the server.
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderQuota.QuotaName Property

FolderQuotaQuotaName Property
Gets the name of the quota.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string QuotaName { get; }
Public ReadOnly Property QuotaName As String
    Get

Property Value

Type: String
The string containing the name assigned by the mail server to the quota, or a null reference (Nothing in Visual Basic) if there is no quota assigned for this accout or a folder.
Remarks
Since the account can have multiple quotas assigned (for instance, one quota per folder), it's possible to distinguish between individual quota objects using the quota name. Most applications, however, can safely ignore this property value.
See Also

Reference

FolderQuota Class
MailBee.ImapMail Namespace


FolderStatus Class

FolderStatus Class
Provides properties used to examine the status of a single folder of the mail account.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailFolderStatus

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class FolderStatus
Public Class FolderStatus

The FolderStatus type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | FolderName | Gets the full name of the folder including parent folder names if any.
Public property | IsValid | Gets if the server response containing the folder status information has been successfully parsed.
Public property | MessageCount | Gets the number of messages in the folder.
Public property | RawFolderName | Gets the full name of the folder as was returned by the server including parent folder names if any.
Public property | RecentCount | Gets the number of recent messages in the folder.
Public property | UidNext | Gets the next UID value to be assigned to a new message.
Public property | UidValidity | Gets the UID validity value of the folder.
Public property | UnseenCount | Gets the number of unseen messages in the folder.
Top
Remarks
To obtain the status of a particular folder, the developer can call GetFolderStatus(String) method.
Note Note
GetFolderStatus(String) method obtains the status information about the requested folder without selecting it. The currently selected folder (if any) remains selected after calling this method.
See Also

Reference

MailBee.ImapMail Namespace
ImapGetFolderStatus(String)


FolderStatus Methods

FolderStatus Methods

The FolderStatus type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus Properties

FolderStatus Properties

The FolderStatus type exposes the following members.

Properties
 | Name | Description
Public property | FolderName | Gets the full name of the folder including parent folder names if any.
Public property | IsValid | Gets if the server response containing the folder status information has been successfully parsed.
Public property | MessageCount | Gets the number of messages in the folder.
Public property | RawFolderName | Gets the full name of the folder as was returned by the server including parent folder names if any.
Public property | RecentCount | Gets the number of recent messages in the folder.
Public property | UidNext | Gets the next UID value to be assigned to a new message.
Public property | UidValidity | Gets the UID validity value of the folder.
Public property | UnseenCount | Gets the number of unseen messages in the folder.
Top
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus.FolderName Property

FolderStatusFolderName Property
Gets the full name of the folder including parent folder names if any.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string FolderName { get; }
Public ReadOnly Property FolderName As String
    Get

Property Value

Type: String
The string containing the full name of the folder including parent folder names if any, or a null reference (Nothing in Visual Basic) if the folder name is not available.
Remarks

The typical values returned by this property are: "Inbox", "Sent.Orders", "INBOX\From John Doe".

MailBee automatically decodes international folder names presented in UTF-7 Modified encoding (see IMAP4 protocol specification in RFC3501 for details on UTF-7 Modified encoding). RawFolderName provides access to the original name as it was returned by the server.

See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace
FolderStatusRawFolderName


FolderStatus.IsValid Property

FolderStatusIsValid Property
Gets if the server response containing the folder status information has been successfully parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if the server response containing the folder status information was correct; false otherwise.
Remarks

Due to complexity of IMAP4 responses, some server implementations fail to produce 100% correct responses sometimes. If MailBee cannot parse the folder status response, it sets IsValid to false.

When the folder status response is correct (IsValid is true), all numeric values are non-negative, and FolderName is not a null reference (Nothing in Visual Basic).

See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus.MessageCount Property

FolderStatusMessageCount Property
Gets the number of messages in the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageCount { get; }
Public ReadOnly Property MessageCount As Integer
    Get

Property Value

Type: Int32
The non-negative Int32 value containing the number of messages in the folder, or -1 if this information is not available.
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus.RawFolderName Property

FolderStatusRawFolderName Property
Gets the full name of the folder as was returned by the server including parent folder names if any.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RawFolderName { get; }
Public ReadOnly Property RawFolderName As String
    Get

Property Value

Type: String
The string containing the full name of the folder as was returned by the server including parent folder names if any, or a null reference (Nothing in Visual Basic) if the folder name is not available.
Remarks
Unlike FolderName, RawFolderName is not automatically decoded from UTF-7 Modified encoding. The developer can use RawFolderName in conjuction with Utf7EncodeFolderNames set to false to preserve the original names of folders when passing them back to the server. This can be useful if the account contains some folder names encoded with the encoding different from UTF-7M. In this case, automatic re-encoding them into UTF-7M would cause problems.
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace
FolderStatusFolderName


FolderStatus.RecentCount Property

FolderStatusRecentCount Property
Gets the number of recent messages in the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int RecentCount { get; }
Public ReadOnly Property RecentCount As Integer
    Get

Property Value

Type: Int32
The non-negative Int32 value containing the number of recent messages in the folder, or -1 if this information is not available.
Remarks
Recent messages are messages having "\Recent" flag set. See Recent topic for more information regarding recent messages.
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus.UidNext Property

FolderStatusUidNext Property
Gets the next UID value to be assigned to a new message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long UidNext { get; }
Public ReadOnly Property UidNext As Long
    Get

Property Value

Type: Int64
The positive 32-bit Int64 value containing the next UID value of the folder, or -1 if this information is not available.
Remarks
This is the UID value which will be assigned to a new message when it's gets placed to the folder. UidNext value conforms the following conditions: first, the next UID value WILL NOT change unless new messages are added to the mailbox; and second, the next UID value WILL change whenever new messages are added to the folder, even if those new messages are subsequently expunged.
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus.UidValidity Property

FolderStatusUidValidity Property
Gets the UID validity value of the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long UidValidity { get; }
Public ReadOnly Property UidValidity As Long
    Get

Property Value

Type: Int64
The positive 32-bit Int64 value containing the UID validity value of the folder, or -1 if this information is not available.
Remarks

If UIDs from an earlier session fail to persist in this session, the UidValidity value will be greater than the one used in the earlier session.

The client may save this property value for each folder and then, on each new session, compare saved value with the value obtained from the server. If UID validity value returned by the server in the current session is larger than saved value, the client cannot rely the UIDs of messages in the folder are the same as they were during the earlier session. However, mail servers which fail to persist UIDs between sessions are very uncommon nowadays.

See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


FolderStatus.UnseenCount Property

FolderStatusUnseenCount Property
Gets the number of unseen messages in the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int UnseenCount { get; }
Public ReadOnly Property UnseenCount As Integer
    Get

Property Value

Type: Int32
The non-negative Int32 value containing the number of messages which have not been read, or -1 if this information is not available.
Remarks
Unseen (unread) messages are messages not having "\Seen" flag set. See Seen topic for more information regarding unread messages.
Note Note
This value is different from Unseen which returns the ordinal message number of the first unseen message in the folder, not the count of the unseen messages.
See Also

Reference

FolderStatus Class
MailBee.ImapMail Namespace


Imap Class

Imap Class
Provides properties and methods for connecting to an IMAP4 server, downloading, searching, and managing folders and e-mail messages in a user account.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailImap

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Imap : IComponent, IDisposable
Public Class Imap
    Implements IComponent, IDisposable

The Imap type exposes the following members.

Constructors
 | Name | Description
Public method | Imap | Creates an instance of Imap class.
Public method | Imap(String) | Creates and unlocks an instance of Imap class.
Top
Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | BeginClose | Obsolete. Begins an asynchronous request for closing (unselecting) the currently selected folder and optional removing of messages marked as deleted from this folder.
 | BeginConnect | Obsolete. Begins an asynchronous request for a connecting to an IMAP4 server.
 | BeginCopyOrMoveMessages | Obsolete. Begins an asynchronous request for copying or moving the specified messages from the currently selected folder to the specified folder.
Public method | BeginDisconnect | Obsolete. Begins an asynchronous request for a disconnection from the mail server.
 | BeginDownloadEnvelopes | Obsolete. Begins an asynchronous request for downloading the specified message elements (envelopes, flags, body structures, entire messages or message headers, etc) from the currently selected folder.
 | BeginDownloadEnvelopesEx | Obsolete. Begins an asynchronous request for downloading the specified sets of message items (for each message, its own set of items can be requested) from the currently selected folder.
 | BeginDownloadFolders | Obsolete. Begins an asynchronous request for downloading IMAP folders matching the specified criteria.
 | BeginExecuteCustomCommand | Obsolete. Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.
 | BeginIdle | Obsolete. Begins an asynchronous request for starting idling mode.
 | BeginLogin | Obsolete. Begins an asynchronous request for a logging in an account on an IMAP4 server.
 | BeginSearch | Obsolete. Begins an asynchronous request for searching the currently selected folder for messages meeting the specified criteria.
 | BeginSelectFolder | Obsolete. Begins an asynchronous request for selecting a folder in an account on an IMAP4 server.
 | BeginSetMessageFlags | Obsolete. Begins an asynchronous request to set or reset the specified message flags for the specified messages in the currently selected folder.
 | BeginSortedSearch | Obsolete. Begins an asynchronous request for searching the currently selected folder for messages meeting the specified criteria and sorting them accordingly the specified sort condition.
 | BeginStartTls | Obsolete. Begins an asynchronous request to start TLS/SSL negotiation with the server.
 | BeginUploadMessage | Obsolete. Begins an asynchronous request for uploading the message into the specified folder on the server.
 | Close | Unselects the currently selected folder and removes all messages having \Deleted flag set from the folder.
Public method | Close(Boolean) | Unselects the currently selected folder and optionally removes all messages having \Deleted flag set from the folder.
Public method | CloseAsync | async/await version of Close.
Public method | CloseAsync(Boolean) | async/await version of Close(Boolean).
 | Connect(String) | Connects to an IMAP4 server on the standard IMAP4 port (143).
 | Connect(String, Int32) | Connects to an IMAP4 server.
 | Connect(String, Int32, Socket, EndPoint) | Connects to an IMAP4 server.
Public method | ConnectAsync(String) | async/await version of Connect(String).
Public method | ConnectAsync(String, Int32) | async/await version of Connect(String, Int32).
Public method | ConnectAsync(String, Int32, Socket, EndPoint) | async/await version of Connect(String, Int32, Socket, EndPoint).
 | CopyMessages(String, Boolean, String) | Copies the specified messages from the currently selected folder to the specified folder.
 | CopyMessages(String, Boolean, String, UidPlusResult) | Copies the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the copied messages in the destination folder.
Public method | CopyMessagesAsync(String, Boolean, String) | async/await version of CopyMessages(String, Boolean, String).
Public method | CopyMessagesAsync(String, Boolean, String, UidPlusResult) | async/await version of CopyMessages(String, Boolean, String, UidPlusResult).
 | CreateFolder | Creates a new folder (mailbox in IMAP4 terms) in the IMAP4 account.
Public method | CreateFolderAsync | async/await version of CreateFolder(String).
 | DeleteFolder | Deletes an existing folder (mailbox in IMAP4 terms) from the IMAP4 account.
Public method | DeleteFolderAsync | async/await version of DeleteFolder(String).
 | DeleteMessages | Marks the specified messages in the currently selected folder as deleted.
Public method | DeleteMessagesAsync | async/await version of DeleteMessages(String, Boolean).
 | Disconnect | Disconnects from the IMAP4 server and releases any used resources.
Public method | DisconnectAsync | async/await version of Disconnect.
Public method | Dispose | Closes all opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.
 | DownloadEntireMessage | Completely downloads the specified message from the server.
Public method | DownloadEntireMessageAsync | async/await version of DownloadEntireMessage(Int64, Boolean).
 | DownloadEntireMessages | Completely downloads the specified messages from the server.
Public method | DownloadEntireMessagesAsync | async/await version of DownloadEntireMessages(String, Boolean).
 | DownloadEnvelopes(String, Boolean) | Fetches message envelopes from the server.
 | DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32) | Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.
 | DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) | Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.
Public method | DownloadEnvelopesAsync(String, Boolean) | async/await version of DownloadEnvelopes(String, Boolean).
Public method | DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32) | async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32).
Public method | DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32, String, String) | async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String).
 | DownloadEnvelopesEx | Fetches message envelopes, bodies, headers, flags, attributes, etc from the server allowing you to request different items for every message in the list.
Public method | DownloadEnvelopesExAsync | async/await version of DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String).
 | DownloadFolders | Downloads the list of all IMAP folders of the mail account.
 | DownloadFolders(Boolean) | Downloads the list of IMAP folders of the mail account.
 | DownloadFolders(Boolean, String, String) | Downloads the list of IMAP folders matching the specified criteria.
Public method | DownloadFoldersAsync | async/await version of DownloadFolders.
Public method | DownloadFoldersAsync(Boolean) | async/await version of DownloadFolders(Boolean).
Public method | DownloadFoldersAsync(Boolean, String, String) | async/await version of DownloadFolders(Boolean, String, String).
 | DownloadMessageHeaders | Downloads the header of each message in the specified set from the server.
Public method | DownloadMessageHeadersAsync | async/await version of DownloadMessageHeaders(String, Boolean).
Public method | EndClose | Ends the pending asynchronous close folder request.
Public method | EndConnect | Ends the pending asynchronous connection request.
Public method | EndCopyOrMoveMessages | Ends a pending asynchronous request for copying or moving messages.
Public method | EndDisconnect | Ends a pending asynchronous disconnection request.
Public method | EndDownloadEnvelopes | Ends the pending asynchronous download envelopes request.
Public method | EndDownloadEnvelopesEx | Ends the pending asynchronous request of pipelined downloading envelopes.
Public method | EndDownloadFolders | Ends the pending asynchronous download folders request.
Public method | EndExecuteCustomCommand | Ends the pending asynchronous request for sending user-defined command to the server.
Public method | EndIdle | Ends the pending asynchronous request for idling termination.
Public method | EndLogin | Ends the pending asynchronous login request.
Public method | EndSearch | Ends the pending asynchronous search request.
Public method | EndSelectFolder | Ends the pending asynchronous select folder request.
Public method | EndSetMessageFlags | Ends a pending asynchronous setting message flags request.
Public method | EndSortedSearch | Ends the pending asynchronous sorted search request.
Public method | EndStartTls | Ends a pending asynchronous TLS/SSL negotiation request.
Public method | EndUploadMessage | Ends the pending asynchronous upload message request.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | ExamineFolder | Selects the specified folder (mailbox in IMAP4 terms) for read-only access.
Public method | ExamineFolderAsync | async/await version of ExamineFolder(String).
 | ExecuteCustomCommand | Sends user-defined command to the server and receives the server response to this command.
Public method | ExecuteCustomCommandAsync | async/await version of ExecuteCustomCommand(String, String).
 | Expunge | Permanently removes all the messages marked as deleted from the currently selected folder.
 | Expunge(String, Boolean) | Permanently removes the messages marked as deleted from the currently selected folder.
Public method | ExpungeAsync | async/await version of Expunge.
Public method | ExpungeAsync(String, Boolean) | async/await version of Expunge(String, Boolean).
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAccountQuota | Gets the quota (resource usage limit) of the entire mail account on the server.
Public method | GetAccountQuotaAsync | async/await version of GetAccountQuota.
Public method | GetErrorDescription | Returns a textual description of the last occurred error.
 | GetExtension | Returns the name of the specified IMAP4 capability if it's supported by the mail server.
 | GetExtensions | Returns a reference to the key-value list of the mail server capabilities.
 | GetFolderQuota | Gets the quota (resource usage limit) of the specified folder.
Public method | GetFolderQuotaAsync | async/await version of GetFolderQuota(String).
 | GetFolderSize | Downloads the size of each message in the currently selected folder and returns the total size occupied by all messages in this folder.
Public method | GetFolderSizeAsync | async/await version of GetFolderSize.
 | GetFolderStatus | Gets the status of the specified folder without selecting it.
Public method | GetFolderStatusAsync | async/await version of GetFolderStatus(String).
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetNamespaces | Downloads the list of IMAP4 namespaces available for the currently logged mail user.
Public method | GetNamespacesAsync | async/await version of GetNamespaces.
Public method | GetServerResponse | Returns the last response from the server.
Public method | GetServerResponses | Returns the specified individual responses from the last group of responses received from the server.
Public method | GetSocket | Returns the underlying Socket MailBee uses for the current network connection.
Public method | GetSocketError | Returns a Win32 error code of the last socket-related error.
 | GetSpecialFolder | Gets a reference to the special folder of the specified kind.
Public method | GetStream | Returns the underlying Stream MailBee uses for the current network connection.
 | GetSupportedAuthMethods | Returns a set of flags indicating which authentication methods are supported by the server.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | Idle | Attempts to start idling mode which makes the client wait for any notifications from the server regarding the currently selected folder.
Public method | IdleAsync | async/await version of Idle.
 | Login(String, String) | Logs in a mail account on the IMAP4 server.
 | Login(String, String, AuthenticationMethods) | Logs in a mail account on the IMAP4 server.
 | Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mail account on the IMAP4 server.
 | Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mail account on the IMAP4 server.
Public method | LoginAsync(String, String) | async/await version of Login(String, String).
Public method | LoginAsync(String, String, AuthenticationMethods) | async/await version of Login(String, String, AuthenticationMethods).
Public method | LoginAsync(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Public method | LoginAsync(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | MoveMessages(String, Boolean, String) | Moves the specified messages from the currently selected folder to the specified folder.
 | MoveMessages(String, Boolean, String, UidPlusResult) | Moves the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the moved messages in the destination folder.
Public method | MoveMessagesAsync(String, Boolean, String) | async/await version of MoveMessages(String, Boolean, String).
Public method | MoveMessagesAsync(String, Boolean, String, UidPlusResult) | async/await version of MoveMessages(String, Boolean, String, UidPlusResult).
Public method | Noop | Sends a NOOP command to the mail server.
Public method | NoopAsync | async/await version of Noop.
Protected method | OnConnected | Used by MailBee to raise Connected event.
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnDisconnected | Used by MailBee to raise Disconnected event.
Protected method | OnEnvelopeDataChunkReceived | Used by MailBee to raise EnvelopeDataChunkReceived event.
Protected method | OnEnvelopeDownloaded | Used by MailBee to raise EnvelopeDownloaded event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnHostResolved | Used by MailBee to raise HostResolved event.
Protected method | OnIdling | Used by MailBee to raise Idling event.
Protected method | OnLoggedIn | Used by MailBee to raise LoggedIn event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnLowLevelDataReceived | Used by MailBee to raise LowLevelDataReceived event.
Protected method | OnLowLevelDataSent | Used by MailBee to raise LowLevelDataSent event.
Protected method | OnMessageStatus | Used by MailBee to raise MessageStatus event.
Protected method | OnServerStatus | Used by MailBee to raise ServerStatus event.
Protected method | OnSocketConnected | Used by MailBee to raise SocketConnected event.
Protected method | OnSocketCreating | Used by MailBee to raise SocketCreating event.
Protected method | OnTlsStarted | Used by MailBee to raise TlsStarted event.
 | QuickDownloadMessage(String, String, String, String, Int32) | Completely downloads the specified message from the specified folder on the server, in a single line of code.
 | QuickDownloadMessage(String, String, String, String, Int32, Int32) | Downloads the specified message (entire message or message header only) from the specified folder on the server, in a single line of code.
 | QuickDownloadMessages(String, String, String, String) | Completely downloads all the messages in the specified folder on the server, in a single line of code.
 | QuickDownloadMessages(String, String, String, String, Int32) | Downloads all the messages (entire messages or message headers only) in the specified folder on the server, in a single line of code.
 | RenameFolder | Renames an existing folder (mailbox in IMAP4 terms) of the IMAP4 account.
Public method | RenameFolderAsync | async/await version of RenameFolder(String, String).
Public method | ResetState | Resets the internal state of the component.
 | Search | Returns the collection of UIDs of all messages in the currently selected folder.
 | Search(Boolean, String, String) | Searches the currently selected folder for messages that meet the specified criteria.
Public method | SearchAsync | async/await version of Search.
 | SearchAsync(Boolean, String, String) | async/await version of Search(Boolean, String, String).
 | SelectFolder | Selects the specified folder (mailbox in IMAP4 terms) for read-write access.
Public method | SelectFolderAsync | async/await version of SelectFolder(String).
 | SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction) | Sets or resets the specified flags for the specified messages in the currently selected folder.
 | SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) | Sets or resets the specified flags for the specified messages in the currently selected folder.
Public method | SetMessageFlagsAsync(String, Boolean, SystemMessageFlags, MessageFlagAction) | async/await version of SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction).
Public method | SetMessageFlagsAsync(String, Boolean, String, MessageFlagAction, Boolean) | async/await version of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean).
 | SortedSearch | Searches the currently selected folder for messages that meet the specified criteria and returns them as a collection sorted by the specified condition.
Public method | SortedSearchAsync | async/await version of SortedSearch(Boolean, String, String, String).
 | StartTls | Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.
Public method | StartTlsAsync | async/await version of StartTls.
Public method | StopIdle | Notifies MailBee to terminate idling when appropriate.
Public method | SubscribeFolder | Subscribes to the specified folder (mailbox in IMAP4 terms) of the IMAP4 account.
Public method | SubscribeFolderAsync | async/await version of SubscribeFolder(String).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | UnsubscribeFolder | Unsubscribes the previously subscribed folder (mailbox in IMAP4 terms) of the IMAP4 account.
Public method | UnsubscribeFolderAsync | async/await version of UnsubscribeFolder(String).
 | UploadMessage(MailMessage, String) | Uploads a mail message to the specified folder.
 | UploadMessage(MailMessage, String, SystemMessageFlags) | Uploads a mail message to the specified folder and assigns the specified flags to this message.
 | UploadMessage(MailMessage, String, String, DateTime) | Uploads a mail message to the specified folder and assigns the specified date and flags to this message.
 | UploadMessage(MailMessage, String, String, String) | Uploads a mail message to the specified folder and assigns the specified date and flags to this message.
 | UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) | Uploads a mail message to the specified folder, assigns the specified date and flags to this message, and retrieves UID assigned to the uploaded message by the server.
Public method | UploadMessageAsync(MailMessage, String) | async/await version of UploadMessage(MailMessage, String).
Public method | UploadMessageAsync(MailMessage, String, SystemMessageFlags) | async/await version of UploadMessage(MailMessage, String, SystemMessageFlags).
Public method | UploadMessageAsync(MailMessage, String, String, DateTime) | async/await version of UploadMessage(MailMessage, String, String, DateTime).
Public method | UploadMessageAsync(MailMessage, String, String, String) | async/await version of UploadMessage(MailMessage, String, String, String).
Public method | UploadMessageAsync(MailMessage, String, String, String, Boolean, UidPlusResult) | async/await version of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult).
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
Fields
Name | Description
AllMessages | Specifies the message set (sequence) which includes all messages in the folder.
Top
Properties
 | Name | Description
Public property | EnableLastDownloaded | Gets or sets whether MailBee should save currently downloaded envelopes in LastDownloadedEnvelopes property.
Public property | Flags | Gets the flags that are applicable for the currently selected folder.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | IsConnected | Indicates whether the component is connected to the server.
Public property | IsFolderSelected | Indicates if a folder is currently selected in the mail account.
Public property | IsIdle | Gets if the component is in IDLE state.
Public property | IsLoggedIn | Indicates whether the component has already successfully authenticated on the server and logged in the user account.
Public property | IsSslConnection | Indicates whether the current connection (if any) is secured with TLS/SSL layer.
 | LastDownloadedEnvelopes | Gets the collection of the envelopes downloaded to the current moment.
Public property | LastResult | Gets a numeric code of the last error.
 | LicenseKey | Obsolete. Assigns the license key.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MessageCount | Gets the number of messages in the currently selected folder.
Public property | PermanentFlags | Gets the flags the client can change permanently.
 | Proxy | Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RaiseEventsViaMessageLoop | Gets or sets whether the events will be raised on the message loop of the application or not.
Public property | RecentCount | Gets the number of recent messages in the currently selected folder.
Public property | RequestEncoding | Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the mail server.
Public property | ResponseEncoding | Gets or sets the encoding used to convert a byte data received from the mail server into a string.
Public property | SetSeenForEntireMessages | Specifies if MailBee should also set SEEN flag when downloading entire messages.
Public property | Site | Gets or sets the object to be used as a site for the component.
 | SslCertificates | Provides access to the client and server SSL certificate settings.
 | SslMode | Gets or sets how the component should establish TLS/SSL connection with the mail server.
Public property | SslProtocol | Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | UidNext | Gets the UID to be assigned to the next message in the currently selected folder.
Public property | UidValidity | Gets the UIDVALIDITY value of the currently selected folder.
Public property | Unseen | Gets the ordinal message number of the first message which does not have "\Seen" flag set.
Public property | UseXList | Gets or sets whether to use XLIST extension which allows the application to detect special folders like Sent, Drafts, Trash.
Public property | Utf7EncodeFolderNames | Gets or sets whether MailBee should automatically encode folder names with UTF-7 Modified encoding.
Public property | Version | Gets the version of the MailBee assembly.
Top
Events
 | Name | Description
 | Connected | Occurs when the connection with the server is successfully established.
 | DataReceived | Occurs when data is received from the IMAP4 server.
 | DataSent | Occurs when data is sent to the IMAP4 server.
 | Disconnected | Occurs when the connection with the server gets closed.
Public event | Disposed | Occurs after the component was disposed.
 | EnvelopeDataChunkReceived | Occurs on progress of downloading FETCH responses (containing message source data, envelopes, and other message-related information) from the server.
 | EnvelopeDownloaded | Occurs when a FETCH response is received from the IMAP4 server and the method which receives mail messages or envelopes (such as DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)) is in progress.
 | ErrorOccurred | Occurs when the MailBeeException is thrown.
 | HostResolved | Occurs when the IMAP4 server name is successfully resolved into IP address(es).
 | Idling | Ticks every 10 milliseconds while in idle state.
 | LoggedIn | Occurs when the component successfully authenticates the user on the server and logs in the user account.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Imap.Log.MemoryLog is true).
 | LowLevelDataReceived | Occurs when data is received from the connected socket.
 | LowLevelDataSent | Occurs when data is sent to the connected socket.
 | MessageStatus | Occurs when the IMAP4 server informs the client of any changes to mail messages in the currently selected folder.
 | ServerStatus | Occurs when the IMAP4 server reports mailbox or server status information to the client.
 | SocketConnected | Occurs when the IMAP4 server accepts the connection attempt and opens the transmission channel between the remote host (IMAP4 server) and the client (MailBee).
 | SocketCreating | Occurs when MailBee needs a new socket object for establishing a connection with the IMAP4 server.
 | TlsStarted | Occurs when the connection with the server becomes secure.
Top
Remarks
You can perform the following operations using this class:
  • Download entire messages with body and attachments
  • Download message headers (and optionally, the part of message bodies)
  • Download message envelopes or any parts or attributes of messages
  • Download and manage IMAP4 folders, detect special folders like Drafts or Trash
  • Delete messages from the server, examine and set message flags
  • Send user-defined commands to the IMAP4 server
  • Login to a user account using a number of authentication methods (including secure methods and OAuth2)
  • Process multiple messages in a batch
  • Search messages
  • Upload, copy, and move messages between folders
  • Collect folder and accounts statistics like number of messages and total size of all messages
  • Download entire messages or message headers with a single line of code (using static methods)
  • Take advantage of many IMAP4 extensions (QUOTA, IDLE, SORT, UIDPLUS, MOVE, CHILDREN, XLIST, SPECIAL-USE, LITERAL+, and Gmail-specific)
  • Work with IMAP4 namespaces (e.g. Public folders)
  • Establish secure connection with TLS/SSL enabled IMAP4 server
  • Establish connection via a proxy server (SOCKS4, SOCKS5, and HTTP proxy are supported)
Examples
This sample connects to an IMAP4 server, logs in using the most secure method supported by this server, downloads envelopes for the last 10 messages in the inbox, and prints From:, To:, and Subject: field values for every message into Console, newer messages first.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.somecompany.com");
        imp.Login("jdoe@somecompany.com", "secret");
        imp.SelectFolder("INBOX");

        string range;

        // Does the inbox contain at least 10 mails?
        if (imp.MessageCount >= 10)
        {
            // We'll get last 10 mails.
            range = (imp.MessageCount - 9).ToString() + ":" + "*";
        }
        else
        {
            // We'll get all mails.
            range = Imap.AllMessages;
        }

        // Get envelopes for the specified messages.
        EnvelopeCollection envelopes = imp.DownloadEnvelopes(range, false);

        // Make newer messages be displayed first.
        envelopes.Reverse();

        foreach (Envelope env in envelopes)
        {
            Console.WriteLine("Message #" + env.MessageNumber);
            Console.WriteLine("From: " + env.From.ToString());
            Console.WriteLine("To: " + env.To.ToString());
            Console.WriteLine("Subject: " + env.Subject);
            Console.WriteLine();
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.somecompany.com")
        imp.Login("jdoe@somecompany.com", "secret")
        imp.SelectFolder("INBOX")

        Dim range As String

        ' Does the inbox contain at least 10 mails?
        If imp.MessageCount >= 10 Then
            ' We'll get last 10 mails.
            range = (imp.MessageCount - 9).ToString() & ":" & "*"
        Else
            ' We'll get all mails.
            range = Imap.AllMessages
        End If

        ' Get envelopes for the specified messages.
        Dim envelopes As EnvelopeCollection = imp.DownloadEnvelopes(range, False)

        ' Make newer messages be displayed first.
        envelopes.Reverse()

        For Each env As Envelope In envelopes
            Console.WriteLine("Message #" & env.MessageNumber)
            Console.WriteLine("From: " & env.From.ToString())
            Console.WriteLine("To: " & env.To.ToString())
            Console.WriteLine("Subject: " & env.Subject)
            Console.WriteLine()
        Next

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

MailBee.ImapMail Namespace


Imap Constructor

Imap Constructor
Creates an instance of Imap class.
Overload List
 | Name | Description
Public method | Imap | Creates an instance of Imap class.
Public method | Imap(String) | Creates and unlocks an instance of Imap class.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap Constructor

Imap Constructor
Creates an instance of Imap class.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Imap()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET IMAP not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

Imap Class
Imap Overload
MailBee.ImapMail Namespace


Imap Constructor (String)

Imap Constructor (String)
Creates and unlocks an instance of Imap class.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Imap(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET IMAP not licensed and the supplied license key is invalid.
See Also

Reference

Imap Class
Imap Overload
MailBee.ImapMail Namespace


Imap Fields

Imap Fields

The Imap type exposes the following members.

Fields
Name | Description
AllMessages | Specifies the message set (sequence) which includes all messages in the folder.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.AllMessages Field

ImapAllMessages Field
Specifies the message set (sequence) which includes all messages in the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string AllMessages
Public Const AllMessages As String

Field Value

Type: String
"1:*" string.
Remarks
This constant can be passed as messageIndexSet parameter value to Imap class methods which accept this parameter (for instance, DownloadEnvelopes(String, Boolean)) to specify that ALL messages in the currently selected folder should be processed (downloaded, deleted, etc).
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap Methods

Imap Methods

The Imap type exposes the following members.

Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | BeginClose | Obsolete. Begins an asynchronous request for closing (unselecting) the currently selected folder and optional removing of messages marked as deleted from this folder.
 | BeginConnect | Obsolete. Begins an asynchronous request for a connecting to an IMAP4 server.
 | BeginCopyOrMoveMessages | Obsolete. Begins an asynchronous request for copying or moving the specified messages from the currently selected folder to the specified folder.
Public method | BeginDisconnect | Obsolete. Begins an asynchronous request for a disconnection from the mail server.
 | BeginDownloadEnvelopes | Obsolete. Begins an asynchronous request for downloading the specified message elements (envelopes, flags, body structures, entire messages or message headers, etc) from the currently selected folder.
 | BeginDownloadEnvelopesEx | Obsolete. Begins an asynchronous request for downloading the specified sets of message items (for each message, its own set of items can be requested) from the currently selected folder.
 | BeginDownloadFolders | Obsolete. Begins an asynchronous request for downloading IMAP folders matching the specified criteria.
 | BeginExecuteCustomCommand | Obsolete. Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.
 | BeginIdle | Obsolete. Begins an asynchronous request for starting idling mode.
 | BeginLogin | Obsolete. Begins an asynchronous request for a logging in an account on an IMAP4 server.
 | BeginSearch | Obsolete. Begins an asynchronous request for searching the currently selected folder for messages meeting the specified criteria.
 | BeginSelectFolder | Obsolete. Begins an asynchronous request for selecting a folder in an account on an IMAP4 server.
 | BeginSetMessageFlags | Obsolete. Begins an asynchronous request to set or reset the specified message flags for the specified messages in the currently selected folder.
 | BeginSortedSearch | Obsolete. Begins an asynchronous request for searching the currently selected folder for messages meeting the specified criteria and sorting them accordingly the specified sort condition.
 | BeginStartTls | Obsolete. Begins an asynchronous request to start TLS/SSL negotiation with the server.
 | BeginUploadMessage | Obsolete. Begins an asynchronous request for uploading the message into the specified folder on the server.
 | Close | Unselects the currently selected folder and removes all messages having \Deleted flag set from the folder.
Public method | Close(Boolean) | Unselects the currently selected folder and optionally removes all messages having \Deleted flag set from the folder.
Public method | CloseAsync | async/await version of Close.
Public method | CloseAsync(Boolean) | async/await version of Close(Boolean).
 | Connect(String) | Connects to an IMAP4 server on the standard IMAP4 port (143).
 | Connect(String, Int32) | Connects to an IMAP4 server.
 | Connect(String, Int32, Socket, EndPoint) | Connects to an IMAP4 server.
Public method | ConnectAsync(String) | async/await version of Connect(String).
Public method | ConnectAsync(String, Int32) | async/await version of Connect(String, Int32).
Public method | ConnectAsync(String, Int32, Socket, EndPoint) | async/await version of Connect(String, Int32, Socket, EndPoint).
 | CopyMessages(String, Boolean, String) | Copies the specified messages from the currently selected folder to the specified folder.
 | CopyMessages(String, Boolean, String, UidPlusResult) | Copies the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the copied messages in the destination folder.
Public method | CopyMessagesAsync(String, Boolean, String) | async/await version of CopyMessages(String, Boolean, String).
Public method | CopyMessagesAsync(String, Boolean, String, UidPlusResult) | async/await version of CopyMessages(String, Boolean, String, UidPlusResult).
 | CreateFolder | Creates a new folder (mailbox in IMAP4 terms) in the IMAP4 account.
Public method | CreateFolderAsync | async/await version of CreateFolder(String).
 | DeleteFolder | Deletes an existing folder (mailbox in IMAP4 terms) from the IMAP4 account.
Public method | DeleteFolderAsync | async/await version of DeleteFolder(String).
 | DeleteMessages | Marks the specified messages in the currently selected folder as deleted.
Public method | DeleteMessagesAsync | async/await version of DeleteMessages(String, Boolean).
 | Disconnect | Disconnects from the IMAP4 server and releases any used resources.
Public method | DisconnectAsync | async/await version of Disconnect.
Public method | Dispose | Closes all opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.
 | DownloadEntireMessage | Completely downloads the specified message from the server.
Public method | DownloadEntireMessageAsync | async/await version of DownloadEntireMessage(Int64, Boolean).
 | DownloadEntireMessages | Completely downloads the specified messages from the server.
Public method | DownloadEntireMessagesAsync | async/await version of DownloadEntireMessages(String, Boolean).
 | DownloadEnvelopes(String, Boolean) | Fetches message envelopes from the server.
 | DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32) | Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.
 | DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) | Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.
Public method | DownloadEnvelopesAsync(String, Boolean) | async/await version of DownloadEnvelopes(String, Boolean).
Public method | DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32) | async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32).
Public method | DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32, String, String) | async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String).
 | DownloadEnvelopesEx | Fetches message envelopes, bodies, headers, flags, attributes, etc from the server allowing you to request different items for every message in the list.
Public method | DownloadEnvelopesExAsync | async/await version of DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String).
 | DownloadFolders | Downloads the list of all IMAP folders of the mail account.
 | DownloadFolders(Boolean) | Downloads the list of IMAP folders of the mail account.
 | DownloadFolders(Boolean, String, String) | Downloads the list of IMAP folders matching the specified criteria.
Public method | DownloadFoldersAsync | async/await version of DownloadFolders.
Public method | DownloadFoldersAsync(Boolean) | async/await version of DownloadFolders(Boolean).
Public method | DownloadFoldersAsync(Boolean, String, String) | async/await version of DownloadFolders(Boolean, String, String).
 | DownloadMessageHeaders | Downloads the header of each message in the specified set from the server.
Public method | DownloadMessageHeadersAsync | async/await version of DownloadMessageHeaders(String, Boolean).
Public method | EndClose | Ends the pending asynchronous close folder request.
Public method | EndConnect | Ends the pending asynchronous connection request.
Public method | EndCopyOrMoveMessages | Ends a pending asynchronous request for copying or moving messages.
Public method | EndDisconnect | Ends a pending asynchronous disconnection request.
Public method | EndDownloadEnvelopes | Ends the pending asynchronous download envelopes request.
Public method | EndDownloadEnvelopesEx | Ends the pending asynchronous request of pipelined downloading envelopes.
Public method | EndDownloadFolders | Ends the pending asynchronous download folders request.
Public method | EndExecuteCustomCommand | Ends the pending asynchronous request for sending user-defined command to the server.
Public method | EndIdle | Ends the pending asynchronous request for idling termination.
Public method | EndLogin | Ends the pending asynchronous login request.
Public method | EndSearch | Ends the pending asynchronous search request.
Public method | EndSelectFolder | Ends the pending asynchronous select folder request.
Public method | EndSetMessageFlags | Ends a pending asynchronous setting message flags request.
Public method | EndSortedSearch | Ends the pending asynchronous sorted search request.
Public method | EndStartTls | Ends a pending asynchronous TLS/SSL negotiation request.
Public method | EndUploadMessage | Ends the pending asynchronous upload message request.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | ExamineFolder | Selects the specified folder (mailbox in IMAP4 terms) for read-only access.
Public method | ExamineFolderAsync | async/await version of ExamineFolder(String).
 | ExecuteCustomCommand | Sends user-defined command to the server and receives the server response to this command.
Public method | ExecuteCustomCommandAsync | async/await version of ExecuteCustomCommand(String, String).
 | Expunge | Permanently removes all the messages marked as deleted from the currently selected folder.
 | Expunge(String, Boolean) | Permanently removes the messages marked as deleted from the currently selected folder.
Public method | ExpungeAsync | async/await version of Expunge.
Public method | ExpungeAsync(String, Boolean) | async/await version of Expunge(String, Boolean).
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAccountQuota | Gets the quota (resource usage limit) of the entire mail account on the server.
Public method | GetAccountQuotaAsync | async/await version of GetAccountQuota.
Public method | GetErrorDescription | Returns a textual description of the last occurred error.
 | GetExtension | Returns the name of the specified IMAP4 capability if it's supported by the mail server.
 | GetExtensions | Returns a reference to the key-value list of the mail server capabilities.
 | GetFolderQuota | Gets the quota (resource usage limit) of the specified folder.
Public method | GetFolderQuotaAsync | async/await version of GetFolderQuota(String).
 | GetFolderSize | Downloads the size of each message in the currently selected folder and returns the total size occupied by all messages in this folder.
Public method | GetFolderSizeAsync | async/await version of GetFolderSize.
 | GetFolderStatus | Gets the status of the specified folder without selecting it.
Public method | GetFolderStatusAsync | async/await version of GetFolderStatus(String).
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetNamespaces | Downloads the list of IMAP4 namespaces available for the currently logged mail user.
Public method | GetNamespacesAsync | async/await version of GetNamespaces.
Public method | GetServerResponse | Returns the last response from the server.
Public method | GetServerResponses | Returns the specified individual responses from the last group of responses received from the server.
Public method | GetSocket | Returns the underlying Socket MailBee uses for the current network connection.
Public method | GetSocketError | Returns a Win32 error code of the last socket-related error.
 | GetSpecialFolder | Gets a reference to the special folder of the specified kind.
Public method | GetStream | Returns the underlying Stream MailBee uses for the current network connection.
 | GetSupportedAuthMethods | Returns a set of flags indicating which authentication methods are supported by the server.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | Idle | Attempts to start idling mode which makes the client wait for any notifications from the server regarding the currently selected folder.
Public method | IdleAsync | async/await version of Idle.
 | Login(String, String) | Logs in a mail account on the IMAP4 server.
 | Login(String, String, AuthenticationMethods) | Logs in a mail account on the IMAP4 server.
 | Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mail account on the IMAP4 server.
 | Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mail account on the IMAP4 server.
Public method | LoginAsync(String, String) | async/await version of Login(String, String).
Public method | LoginAsync(String, String, AuthenticationMethods) | async/await version of Login(String, String, AuthenticationMethods).
Public method | LoginAsync(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Public method | LoginAsync(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | MoveMessages(String, Boolean, String) | Moves the specified messages from the currently selected folder to the specified folder.
 | MoveMessages(String, Boolean, String, UidPlusResult) | Moves the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the moved messages in the destination folder.
Public method | MoveMessagesAsync(String, Boolean, String) | async/await version of MoveMessages(String, Boolean, String).
Public method | MoveMessagesAsync(String, Boolean, String, UidPlusResult) | async/await version of MoveMessages(String, Boolean, String, UidPlusResult).
Public method | Noop | Sends a NOOP command to the mail server.
Public method | NoopAsync | async/await version of Noop.
Protected method | OnConnected | Used by MailBee to raise Connected event.
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnDisconnected | Used by MailBee to raise Disconnected event.
Protected method | OnEnvelopeDataChunkReceived | Used by MailBee to raise EnvelopeDataChunkReceived event.
Protected method | OnEnvelopeDownloaded | Used by MailBee to raise EnvelopeDownloaded event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnHostResolved | Used by MailBee to raise HostResolved event.
Protected method | OnIdling | Used by MailBee to raise Idling event.
Protected method | OnLoggedIn | Used by MailBee to raise LoggedIn event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnLowLevelDataReceived | Used by MailBee to raise LowLevelDataReceived event.
Protected method | OnLowLevelDataSent | Used by MailBee to raise LowLevelDataSent event.
Protected method | OnMessageStatus | Used by MailBee to raise MessageStatus event.
Protected method | OnServerStatus | Used by MailBee to raise ServerStatus event.
Protected method | OnSocketConnected | Used by MailBee to raise SocketConnected event.
Protected method | OnSocketCreating | Used by MailBee to raise SocketCreating event.
Protected method | OnTlsStarted | Used by MailBee to raise TlsStarted event.
 | QuickDownloadMessage(String, String, String, String, Int32) | Completely downloads the specified message from the specified folder on the server, in a single line of code.
 | QuickDownloadMessage(String, String, String, String, Int32, Int32) | Downloads the specified message (entire message or message header only) from the specified folder on the server, in a single line of code.
 | QuickDownloadMessages(String, String, String, String) | Completely downloads all the messages in the specified folder on the server, in a single line of code.
 | QuickDownloadMessages(String, String, String, String, Int32) | Downloads all the messages (entire messages or message headers only) in the specified folder on the server, in a single line of code.
 | RenameFolder | Renames an existing folder (mailbox in IMAP4 terms) of the IMAP4 account.
Public method | RenameFolderAsync | async/await version of RenameFolder(String, String).
Public method | ResetState | Resets the internal state of the component.
 | Search | Returns the collection of UIDs of all messages in the currently selected folder.
 | Search(Boolean, String, String) | Searches the currently selected folder for messages that meet the specified criteria.
Public method | SearchAsync | async/await version of Search.
 | SearchAsync(Boolean, String, String) | async/await version of Search(Boolean, String, String).
 | SelectFolder | Selects the specified folder (mailbox in IMAP4 terms) for read-write access.
Public method | SelectFolderAsync | async/await version of SelectFolder(String).
 | SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction) | Sets or resets the specified flags for the specified messages in the currently selected folder.
 | SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) | Sets or resets the specified flags for the specified messages in the currently selected folder.
Public method | SetMessageFlagsAsync(String, Boolean, SystemMessageFlags, MessageFlagAction) | async/await version of SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction).
Public method | SetMessageFlagsAsync(String, Boolean, String, MessageFlagAction, Boolean) | async/await version of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean).
 | SortedSearch | Searches the currently selected folder for messages that meet the specified criteria and returns them as a collection sorted by the specified condition.
Public method | SortedSearchAsync | async/await version of SortedSearch(Boolean, String, String, String).
 | StartTls | Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.
Public method | StartTlsAsync | async/await version of StartTls.
Public method | StopIdle | Notifies MailBee to terminate idling when appropriate.
Public method | SubscribeFolder | Subscribes to the specified folder (mailbox in IMAP4 terms) of the IMAP4 account.
Public method | SubscribeFolderAsync | async/await version of SubscribeFolder(String).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | UnsubscribeFolder | Unsubscribes the previously subscribed folder (mailbox in IMAP4 terms) of the IMAP4 account.
Public method | UnsubscribeFolderAsync | async/await version of UnsubscribeFolder(String).
 | UploadMessage(MailMessage, String) | Uploads a mail message to the specified folder.
 | UploadMessage(MailMessage, String, SystemMessageFlags) | Uploads a mail message to the specified folder and assigns the specified flags to this message.
 | UploadMessage(MailMessage, String, String, DateTime) | Uploads a mail message to the specified folder and assigns the specified date and flags to this message.
 | UploadMessage(MailMessage, String, String, String) | Uploads a mail message to the specified folder and assigns the specified date and flags to this message.
 | UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) | Uploads a mail message to the specified folder, assigns the specified date and flags to this message, and retrieves UID assigned to the uploaded message by the server.
Public method | UploadMessageAsync(MailMessage, String) | async/await version of UploadMessage(MailMessage, String).
Public method | UploadMessageAsync(MailMessage, String, SystemMessageFlags) | async/await version of UploadMessage(MailMessage, String, SystemMessageFlags).
Public method | UploadMessageAsync(MailMessage, String, String, DateTime) | async/await version of UploadMessage(MailMessage, String, String, DateTime).
Public method | UploadMessageAsync(MailMessage, String, String, String) | async/await version of UploadMessage(MailMessage, String, String, String).
Public method | UploadMessageAsync(MailMessage, String, String, String, Boolean, UidPlusResult) | async/await version of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult).
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Abort Method

ImapAbort Method
Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Abort()
Public Sub Abort
Remarks

A method which was in progress when Abort method has been called will throw MailBeeUserAbortException (unless ThrowExceptions is not false). If the component was not doing any work at the moment (IsBusy was false), the connection is aborted but no exception is thrown.

This method tries to abort the current network operation immediately, which works for all cases except of resolving a domain name into IP address. Due to .NET framework limitations, this operation cannot be aborted. Thus, sometimes you may experience a several seconds delay between calling this method and getting MailBeeUserAbortException (the time needed for DNS resolve to complete).

Note Note
No events will be raised after this method has been called.
To restore the component from the aborted state, the developer can use ResetState method.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapIsAborted
ImapResetState


Imap.BeginClose Method

ImapBeginClose Method

Note: This API is now obsolete.

Begins an asynchronous request for closing (unselecting) the currently selected folder and optional removing of messages marked as deleted from this folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use CloseAsync instead.")]
public IAsyncResult BeginClose(
    bool expungeDeleted,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use CloseAsync instead.")>
Public Function BeginClose (
    expungeDeleted As Boolean,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

expungeDeleted
Type: SystemBoolean
Indicates if the messages marked as deleted must be expunged.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous unselecting folder and expunging deleted messages process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Close(Boolean).
Examples
This WinForms sample demonstrates asynchronous unselecting the Inbox folder and expunging of all deleted messages if any.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

Imap imp = null;
bool finished = false;

// A callback function. Since it's called on Imap worker thread,
// it cannot update controls on the form or otherwise access UI.
// The only UI-related action permitted in worker thread is
// displaying a message box (MessageBox.Show).
// Any updates of UI must take place on message loop thread.
// See BeginSearch method example on how to update UI in callbacks.
private void CloseCallback(IAsyncResult result)
{
    imp.EndClose();
    finished = true;
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    imp = new Imap();

    // Connect to the server, login and select inbox.
    imp.Connect("mail.company.com");
    imp.Login("jdoe@company.com", "secret");
    imp.SelectFolder("Inbox");

    // Start async close/expunge operation.
    imp.BeginClose(true, new AsyncCallback(CloseCallback), null);

    // Wait until it's finished.
    while (!finished)
    {
        // Process events on message loop thread.
        // Alternatively, we could set imp.RaiseEventsOnMessageLoop
        // to false and use imp.Wait method to perform waiting.
        System.Threading.Thread.Sleep(1);
        Application.DoEvents();
    }

    // Close the connection.
    imp.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.
Dim imp As Imap = Nothing
Dim finished As Boolean = False

' A callback function. Since it's called on Imap worker thread,
' it cannot update controls on the form or otherwise access UI.
' The only UI-related action permitted in worker thread is
' displaying a message box (MessageBox.Show).
' Any updates of UI must take place on message loop thread.
' See BeginSearch method example on how to update UI in callbacks.
Private Sub CloseCallback(ByVal result As IAsyncResult)
    imp.EndClose()
    finished = True
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim imp As New Imap

    ' Connect to the server, login and select inbox.
    imp.Connect("imap.domain.com")
    imp.Login("jdoe", "secret")
    imp.SelectFolder("Inbox")

    ' Start async close/expunge operation.
    imp.BeginClose(True, New AsyncCallback(AddressOf CloseCallback), Nothing)

    ' Wait until it's finished.
    While Not finished
        ' Process events on message loop thread.
        ' Alternatively, we could set imp.RaiseEventsOnMessageLoop
        ' to false and use imp.Wait method to perform waiting.
        System.Threading.Thread.Sleep(1)
        Application.DoEvents()
    End While

    ' Close the connection.
    imp.Disconnect()
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapClose(Boolean)


Imap.BeginConnect Method

ImapBeginConnect Method

Note: This API is now obsolete.

Begins an asynchronous request for a connecting to an IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ConnectAsync instead.")]
public IAsyncResult BeginConnect(
    string serverName,
    int port,
    Socket socketToUse,
    EndPoint localEndPoint,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ConnectAsync instead.")>
Public Function BeginConnect (
    serverName As String,
    port As Integer,
    socketToUse As Socket,
    localEndPoint As EndPoint,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard IMAP4 port is 143.
socketToUse
Type: System.Net.SocketsSocket
Usually, a null reference (Nothing in Visual Basic). You can supply your own socket object here if you wish MailBee to use this object instead of creating a new one (typically, to fine-tune the WinSock subsystem when you need to deal with thousands of connections).
localEndPoint
Type: System.NetEndPoint
Usually, a null reference. Set it if you need to bind the connection to a certain local IP address/port to fine-tune the performance under heavy loads. If you supply your own socket object (via socketToUse argument), make sure you EITHER bind the local end point to this socket object in your own code (and pass a null reference as localEndPoint value) OR simply pass the local end point as localEndPoint value (not calling socket.Bind in your own code). Also, you can use no local end point at all. Just make sure you're not binding twice: directly in your code and via passing the local end point to this method.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous connection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks

This method is an asynchronous version of Connect(String, Int32, Socket, EndPoint).

A reference to the state object will be available in the events raised by this method through the State property value. This is also valid for the rest of asynchronous methods in MailBee.

Examples
Asynchronous connecting to an IMAP4 server in WinForms application. This sample also handles Connected event. Wait method is used to wait for the asynchronous method completion, since .NET's standard WaitOne(Int32, Boolean) cannot process events.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// "Connected" event handler.
private void OnConnected(object sender, ConnectedEventArgs e)
{
    Console.WriteLine("Connected to the server");
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Imap imp = new Imap();

    // Let MailBee process events.
    imp.RaiseEventsViaMessageLoop = false;

    imp.Connected += new ConnectedEventHandler(OnConnected);

    // Initiate an asynchronous connection.
    imp.BeginConnect("imap.somehost.com", 143, null, null, null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        imp.Wait(0);
    }

    // If the connection was not established during execution of the lengthy
    // work, wait until it's established.
    imp.Wait();

    // End the connection request.
    imp.EndConnect();

    // Connected to the server!

    // Disconnect from the server.
    imp.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

' "Connected" event handler.
Private Sub OnConnected(ByVal sender As System.Object, ByVal e As ConnectedEventArgs)
    Console.WriteLine("Connected to the server")
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As ConnectedEventArgs)
    Dim imp As New Imap

    ' Let MailBee process events.
    imp.RaiseEventsViaMessageLoop = False

    AddHandler imp.Connected, AddressOf OnConnected
    ' Initiate an asynchronous connection.
    imp.BeginConnect("imap.somehost.com", 143, Nothing, Nothing, Nothing, Nothing)

    ' Simulate some lengthy work here...
    For i As Integer = 1 To 100
        'Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        'Process events which were raised during execution of the work above.
        imp.Wait(0)
    Next
    ' If the connection was not established during execution of the lengthy
    ' work, wait until it's established.
    imp.Wait()

    ' End the connection request.
    imp.EndConnect()

    ' Connected to the server!

    ' Disconnect from the server.
    imp.Disconnect()
End Sub
Examples
Asynchronous connecting to an IMAP4 server in non-WinForms application. Applications which do not have message loop (such as console or web applications) can raise events on any thread and do not require any special events processing.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // "Connected" event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Connected to the server");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connected += new ConnectedEventHandler(OnConnected);

        // Initiate an asynchronous connection.
        imp.BeginConnect("imap.somehost.com", 143, null, null, null, null);

        // Simulate some lengthy work here...
        System.Threading.Thread.Sleep(1000);

        // If the connection was not established during execution of the lengthy work,
        // wait until it's established, and end the connection request.
        imp.EndConnect();

        // Connected to the server!

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Public Class Sample
    ' "Connected" event handler.
    Public Shared Sub OnConnected(ByVal sender As System.Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Connected to the server")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim imp As New Imap
        AddHandler imp.Connected, AddressOf OnConnected

        ' Initiate an asynchronous connection.
        imp.BeginConnect("imap.somehost.com", 143, Nothing, Nothing, Nothing, Nothing)

        ' Simulate some lengthy work here...
        System.Threading.Thread.Sleep(1000)

        ' If the connection was not established during execution of the lengthy work,
        ' wait until it's established, and end the connection request.
        imp.EndConnect()

        ' Connected to the server!

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapConnect(String, Int32, Socket, EndPoint)
ImapRaiseEventsViaMessageLoop
ImapWait


Imap.BeginCopyOrMoveMessages Method

ImapBeginCopyOrMoveMessages Method

Note: This API is now obsolete.

Begins an asynchronous request for copying or moving the specified messages from the currently selected folder to the specified folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use CopyMessagesAsync or MoveMessagesAsync instead.")]
public IAsyncResult BeginCopyOrMoveMessages(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName,
    UidPlusResult result,
    bool move,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use CopyMessagesAsync or MoveMessagesAsync instead.")>
Public Function BeginCopyOrMoveMessages (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String,
    result As UidPlusResult,
    move As Boolean,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the copy/move operation reported by UIDPLUS enabled server (the outcome includes the UIDs of the source messages being copied/moved, the UIDs assigned to the copied/moved messages in the destination folder, and the UIDVALIDITY of the destination folder), or a null reference (Nothing in Visual Basic) if the application does not need this information.
move
Type: SystemBoolean
If true, the messages will be moved; otherwise, copied.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous copying or moving messages process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of CopyMessages(String, Boolean, String, UidPlusResult) (if move is false) or MoveMessages(String, Boolean, String, UidPlusResult) (if move is true).
Examples

This console sample demonstrates asynchronous moving the first and the last messages from the Inbox folder into the Trash folder. A callback function is used as well.

The sample assumes "Trash" folder had already been created in the past. To learn how to make sure the folder exists, see UploadMessage(MailMessage, String, String, DateTime) or UploadMessage(MailMessage, String, String, String) samples.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // A callback function.
    private static void CopyOrMoveMessagesCallback(IAsyncResult result)
    {
        Imap imp = (Imap)result.AsyncState;
        try
        {
            imp.EndCopyOrMoveMessages();
            Console.WriteLine("The messages moved successfully");
        }
        catch (MailBeeException e)
        {
            // In callback functions (generally speaking, in worker threads),
            // it's better to handle exceptions. If exception is not handled,
            // the worker thread silently dies and the application may never
            // know that something went wrong.
            Console.WriteLine(e.Message);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap4.somehost.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Initiate an asynchronous messages moving attempt.
        // We move the first and the last messages.
        IAsyncResult ar = imp.BeginCopyOrMoveMessages(
            "1," + imp.MessageCount.ToString(), false,
            "Trash", null, true,
            new AsyncCallback(CopyOrMoveMessagesCallback), imp);

        // Simulate some lengthy work here. At the same time,
        // messages are moved on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the messages moving attempt is still in progress,
        // then wait until it's finished.
        while (imp.IsBusy) ar.AsyncWaitHandle.WaitOne();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' A callback function.
    Private Sub CopyOrMoveMessagesCallback(ByVal result As IAsyncResult)
        Dim imp As Imap
        imp = CType(result.AsyncState, Imap)

        Try
            imp.EndCopyOrMoveMessages()
            Console.WriteLine("The messages moved successfully")
        Catch e As MailBeeException
            ' In callback functions (generally speaking, in worker threads),
            ' it's better to handle exceptions. If exception is not handled,
            ' the worker thread silently dies and the application may never
            ' know that something went wrong.
            Console.WriteLine(e.Message)
        End Try
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap4.somehost.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Initiate an asynchronous messages moving attempt.
        ' We move the first and the last messages.
        Dim ar As IAsyncResult = imp.BeginCopyOrMoveMessages("1," & _
            imp.MessageCount.ToString(), False, "Trash", Nothing, _
            True, AddressOf CopyOrMoveMessagesCallback, imp)

        ' Simulate some lengthy work here. At the same time,
        ' messages are moved on another thread.
        System.Threading.Thread.Sleep(3000)

        ' If the messages moving attempt is still in progress,
        ' then wait until it's finished.
        While imp.IsBusy
            ar.AsyncWaitHandle.WaitOne()
        End While

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapCopyMessages(String, Boolean, String, UidPlusResult)
ImapMoveMessages(String, Boolean, String, UidPlusResult)


Imap.BeginDisconnect Method

ImapBeginDisconnect Method

Note: This API is now obsolete.

Begins an asynchronous request for a disconnection from the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DisconnectAsync instead.")]
public IAsyncResult BeginDisconnect(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DisconnectAsync instead.")>
Public Function BeginDisconnect (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous disconnection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Disconnect.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDisconnect


Imap.BeginDownloadEnvelopes Method

ImapBeginDownloadEnvelopes Method

Note: This API is now obsolete.

Begins an asynchronous request for downloading the specified message elements (envelopes, flags, body structures, entire messages or message headers, etc) from the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEnvelopesAsync instead.")]
public IAsyncResult BeginDownloadEnvelopes(
    string messageIndexSet,
    bool indexIsUid,
    EnvelopeParts parts,
    int bodyPreviewSize,
    string[] extraHeaders,
    string[] extraItems,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEnvelopesAsync instead.")>
Public Function BeginDownloadEnvelopes (
    messageIndexSet As String,
    indexIsUid As Boolean,
    parts As EnvelopeParts,
    bodyPreviewSize As Integer,
    extraHeaders As String(),
    extraItems As String(),
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
Specifies which message elements or attributes to download.
bodyPreviewSize
Type: SystemInt32
If parts includes MessagePreview flag, specifies the length of the message body section (in bytes) to be downloaded in addition to the message header section; if 0, only the message header is downloaded; if -1 or -2, the entire message is downloaded. -1 is the only option which also sets Seen flag marking the message as read.
extraHeaders
Type: SystemString
The array of names of message headers to be downloaded, or a null reference (Nothing in Visual Basic) if additional headers are not needed.
extraItems
Type: SystemString
The array of additional FETCH request items to download, or a null reference (Nothing in Visual Basic) if additional FETCH items are not needed.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous downloading of envelopes or other message elements.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String).
Examples
This WinForms sample demonstrates asynchronous downloading of all new messages in the Inbox folder. The messages are downloaded completely (with attachments, text parts, etc) and saved into "C:\Temp" folder. The message flags are downloaded as well. For each message, the sample prints saved file name and flags into Output window (it's visible when the application is being run in debug mode).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Imap imp = new Imap();

    // We do not subscribe to any events in this sample, so we do not
    // need to care about them. However, if you decide to subscribe to
    // an event and your application will block message loop thread
    // using imp.Wait() method, you should uncomment the next line
    // to tell MailBee not to use message loop thread for raising events
    // and use imp.Wait() method instead of ar.AsyncWaitHandle.WaitOne().
    // imp.RaiseEventsViaMessageLoop = false;

    // Connect to the server, login and select inbox.
    imp.Connect("imap4.server.com");
    imp.Login("jdoe", "secret");
    imp.SelectFolder("Inbox");

    // Obtain UIDs of new messages (messages which are recent and unseen).
    UidCollection uids = (UidCollection)imp.Search(true, "NEW", null);

    EnvelopeCollection envs = null;

    if (uids.Count > 0)
    {
        // Asynchronously download entire messages and their flags.
        IAsyncResult ar = imp.BeginDownloadEnvelopes(uids.ToString(), true,
            EnvelopeParts.MessagePreview | EnvelopeParts.Flags, -1,
            null, null, null, null);

        // Wait until the asynchronous download completes. Note: this call
        // blocks UI. Thus, if you subscribe to any events, you'll got a
        // deadlock (because events will be raised only after message loop thread
        // gets un-blocked again, while WaitOne() method which blocked the message
        // loop will wait until all events get raised). The solution is to set
        // imp.RaiseEventsViaMessageLoop to false and use imp.Wait() method
        // instead of ar.AsyncWaitHandle.WaitOne() method.
        ar.AsyncWaitHandle.WaitOne();

        // Get downloaded envelopes (messages + flags).
        envs = imp.EndDownloadEnvelopes();
    }

    // Demonstrate that we may disconnect before finished with processing
    // of downloaded envelopes. Although in most samples we disconnect in
    // the very end of the code, it's more efficient to disconnect once the
    // connection is no longer needed. For instance, it may take considerable
    // amount of time to save downloaded messages in the folder (see below).
    // During this time, the connection with the server will just waste system
    // resources since the connection is not actually required any longer.
    // The same optimization can be applied to all other MailBee components.
    imp.Disconnect();

    if (envs != null)
    {
        // Save all downloaded messages into "C:\Temp" folder.
        // Each filename is generated as message's UID + ".eml".
        foreach (Envelope env in envs)
        {
            string filename = env.Uid + ".eml";
            env.MessagePreview.SaveMessage(@"C:\Temp\" + filename);

            // To see this report in VS.NET environment, run the sample
            // in debug mode and monitor the contents of Output window.
            System.Diagnostics.Debug.WriteLine("Message #" + env.MessageNumber +
                " having (" + env.Flags.ToString() + ") flags set was saved as " +
                filename);
        }
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim imp As New Imap

    ' We do not subscribe to any events in this sample, so we do not
    ' need to care about them. However, if you decide to subscribe to
    ' an event and your application will block message loop thread
    ' using imp.Wait() method, you should uncomment the next line
    ' to tell MailBee not to use message loop thread for raising events
    ' and use imp.Wait() method instead of ar.AsyncWaitHandle.WaitOne().
    ' imp.RaiseEventsViaMessageLoop = false

    ' Connect to the server, login and select inbox.
    imp.Connect("imap4.server.com")
    imp.Login("jdoe", "secret")
    imp.SelectFolder("Inbox")

    ' Obtain UIDs of new messages (messages which are recent and unseen).
    Dim uids As UidCollection = CType(imp.Search(True, "NEW", Nothing), UidCollection)

    Dim envs As EnvelopeCollection = Nothing

    If uids.Count > 0 Then
        ' Asynchronously download entire messages and their flags.
        Dim ar As IAsyncResult = imp.BeginDownloadEnvelopes(uids.ToString(), True, _
            EnvelopeParts.MessagePreview Or EnvelopeParts.Flags, -1, _
            Nothing, Nothing, Nothing, Nothing)

        ' Wait until the asynchronous download completes. Note: this call
        ' blocks UI. Thus, if you subscribe to any events, you'll got a
        ' deadlock (because events will be raised only after message loop thread
        ' gets un-blocked again, while WaitOne() method which blocked the message
        ' loop will wait until all events get raised). The solution is to set
        ' imp.RaiseEventsViaMessageLoop to false and use imp.Wait() method
        ' instead of ar.AsyncWaitHandle.WaitOne() method.
        ar.AsyncWaitHandle.WaitOne()

        ' Get downloaded envelopes (messages + flags).
        envs = imp.EndDownloadEnvelopes()
    End If

    ' Demonstrate that we may disconnect before finished with processing
    ' of downloaded envelopes. Although in most samples we disconnect in
    ' the very end of the code, it's more efficient to disconnect once the
    ' connection is no longer needed. For instance, it may take considerable
    ' amount of time to save downloaded messages in the folder (see below).
    ' During this time, the connection with the server will just waste system
    ' resources since the connection is not actually required any longer.
    ' The same optimization can be applied to all other MailBee components.
    imp.Disconnect()

    If Not envs Is Nothing Then
        ' Save all downloaded messages into "C:\Temp" folder.
        ' Each filename is generated as message's UID + ".eml".
        For Each env As Envelope In envs
            Dim filename As String = env.Uid & ".eml"
            env.MessagePreview.SaveMessage("C:\Temp\" & filename)

            ' To see this report in VS.NET environment, run the sample
            ' in debug mode and monitor the contents of Output window.
            System.Diagnostics.Debug.WriteLine("Message #" & env.MessageNumber & _
                " having (" & env.Flags.ToString() & ") flags set was saved as " & filename)
        Next
    End If
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)
ImapDownloadEntireMessages(String, Boolean)
ImapDownloadMessageHeaders(String, Boolean)


Imap.BeginDownloadEnvelopesEx Method

ImapBeginDownloadEnvelopesEx Method

Note: This API is now obsolete.

Begins an asynchronous request for downloading the specified sets of message items (for each message, its own set of items can be requested) from the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEnvelopesExAsync instead.")]
public IAsyncResult BeginDownloadEnvelopesEx(
    long[] messageIndices,
    bool indicesAreUids,
    EnvelopeParts[] parts,
    int[] bodyPreviewSizes,
    string[][] extraHeaders,
    string[][] extraItems,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEnvelopesExAsync instead.")>
Public Function BeginDownloadEnvelopesEx (
    messageIndices As Long(),
    indicesAreUids As Boolean,
    parts As EnvelopeParts(),
    bodyPreviewSizes As Integer(),
    extraHeaders As String()(),
    extraItems As String()(),
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

messageIndices
Type: SystemInt64
The array of UIDs or message numbers of the messages to be fetched.
indicesAreUids
Type: SystemBoolean
If true, messageIndices holds UIDs; otherwise, ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
For every message to be fetched, denotes its EnvelopeParts to be requested. If a null reference (Nothing in Visual Basic), MailBee will use Uid for all messages.
bodyPreviewSizes
Type: SystemInt32
For every message to be fetched, denotes how many bytes of the raw body part to download in addition to the raw header part. If a null reference, MailBee will use 0 for all messages.
extraHeaders
Type: SystemString
For every message to be fetched, denotes its extra MIME headers to be requested. If a null reference MailBee will not request any additional headers for any messages.
extraItems
Type: SystemString
For every message to be fetched, denotes its extra items to be requested. If a null reference MailBee will not request any additional items for any messages.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous downloading of envelopes or other message elements.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String). It's also a pipelined version of BeginDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object) method. It allows the developer to request different FETCH items for different messages in a single command (batch).
Examples

This sample is very close to 2nd sample in DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) topic (that sample gets HTML and plain-text bodies of all messages in the inbox). This sample gets only first 300 bytes of each plain-text and HTML body (i.e. preview).

This text body preview is not related to bodyPreviewSizes. bodyPreviewSizes specifies how much raw body to download. This raw body may contain lots of technical data like MIME boundaries and MIME part headers. Thus, you won't get much of useful information with bodyPreviewSizes unless all your e-mails are simple and their raw body part is the same as their text part. In contrast, the example below accurately extracts exactly HTML and text body preview.

C#
VB
Copy
using System;
using System.Collections;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Enable logging for troubleshooting (for instance, you can see
        // if you send and receive correct FETCH requests and responses.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("user", "password");
        imp.SelectFolder("INBOX");

        // Download body structure for all e-mails in the inbox.
        // We'll use BeginDownloadEnvelopesEx later.
        imp.BeginDownloadEnvelopes(Imap.AllMessages, true,
            EnvelopeParts.BodyStructure, 0, null, null, null, null);
        EnvelopeCollection envs = imp.EndDownloadEnvelopes();

        // The array of lists of FETCH keys to request from the server.
        string[][] fetchRequestKeyListArray = new string[envs.Count][];

        // The array of lists of FETCH keys to expect from the server in return
        // to requests of items listed in each element of fetchRequestKeyListArray.
        string[][] fetchResponseKeyListArray = new string[envs.Count][];

        // UIDs of the messages for which we received the body structure.
        long[] uids = new long[envs.Count];

        for (int i = 0; i < envs.Count; i++)
        {
            Envelope env = envs[i];

            ArrayList fetchRequestKeyList = new ArrayList();
            ArrayList fetchResponseKeyList = new ArrayList();

            // Get body structures of all MIME parts as flat list.
            ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
            foreach (ImapBodyStructure part in parts)
            {
                string contentType = part.ContentType.ToLower();
                string disposition = (part.Disposition == null ? string.Empty : part.Disposition.ToLower());
                if (disposition != "attachment" &&
                    (contentType == "text/plain" || contentType == "text/html"))
                {
                    if (parts.Count > 1)
                    {
                        // For each text body part, we request its MIME part header and the first 300 bytes
                        // of the body. Also note using .MIME instead of .HEADER
                        // because some mail servers don't support .HEADER syntax.
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + ".MIME]");
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + "]<0.300>");

                        // For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[" + part.PartID + ".MIME]");
                        fetchResponseKeyList.Add("BODY[" + part.PartID + "]<0>");
                    }
                    else
                    {
                        fetchRequestKeyList.Add("BODY.PEEK[HEADER]");
                        fetchRequestKeyList.Add("BODY.PEEK[TEXT]<0.300>");

                        // For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[HEADER]");
                        fetchResponseKeyList.Add("BODY[TEXT]<0>");
                    }
                }
            }

            // Second time, we'll get message by its UID. This will avoid the situation
            // when new message arrives between two queries (and thus it could be possible
            // to download wrong message second time).
            uids[i] = env.Uid;

            // Save the generated items for FETCH request and FETCH response.
            fetchRequestKeyListArray[i] = (string[])fetchRequestKeyList.ToArray(typeof(string));
            fetchResponseKeyListArray[i] = (string[])fetchResponseKeyList.ToArray(typeof(string));
        }

        if (envs.Count > 0)
        {
            // Download previews of text parts.
            imp.BeginDownloadEnvelopesEx(uids, true, null, null, null, fetchRequestKeyListArray, null, null);
            envs = imp.EndDownloadEnvelopesEx();

            foreach (Envelope env in envs)
            {
                // We need this to find FETCH request and response keys
                // which correspond to the envelope being examined.
                int index = Array.IndexOf(uids, env.Uid);

                if (index < 0)
                {
                    // For some odd reason, we got envelope we haven't requested.
                    // Hope this will never happen. Anyway, skip such envelope.
                    continue;
                }

                string[] fetchRequestKeys = fetchRequestKeyListArray[index];
                string[] fetchResponseKeys = fetchResponseKeyListArray[index];

                for (int i = 0; i < fetchRequestKeys.Length; i += 2)
                {
                    // Get MIME part header data.
                    byte[] mimePartHeader = (byte[])env.GetEnvelopeItem(
                        fetchResponseKeys[i], true);

                    // Get MIME part body data.
                    byte[] mimePartBody = (byte[])env.GetEnvelopeItem(
                        fetchResponseKeys[i + 1], true);

                    // Build MIME part data from header data and body data.
                    byte[] mimePartData = new byte[mimePartHeader.Length + mimePartBody.Length];
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length);
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData,
                        mimePartHeader.Length, mimePartBody.Length);
                    mimePartHeader = null;
                    mimePartBody = null;

                    // Build TextBodyPart object from the MIME part data.
                    MimePart part = MimePart.Parse(mimePartData);
                    TextBodyPart textPart = new TextBodyPart(part);

                    // Print content-type and text content of the message.
                    Console.WriteLine("For message with UID=" + env.Uid);
                    Console.WriteLine("Content-Type=" + part.ContentType);
                    Console.WriteLine("The text follows...");
                    Console.WriteLine(textPart.Text);
                    Console.WriteLine("---------------------------------");
                    Console.WriteLine();
                }
            }
        }

        imp.Disconnect();
    }
}
Imports System
Imports System.Collections
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' Enable logging for troubleshooting (for instance, you can see
        ' if you send and receive correct FETCH requests and responses.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("user", "password")
        imp.SelectFolder("INBOX")

        ' Download body structure for all e-mails in the inbox.
        ' We'll use BeginDownloadEnvelopesEx later.
        imp.BeginDownloadEnvelopes(Imap.AllMessages, True, EnvelopeParts.BodyStructure, 0, _
         Nothing, Nothing, Nothing, Nothing)
        Dim envs As EnvelopeCollection = imp.EndDownloadEnvelopes()

        ' The array of lists of FETCH keys to request from the server.
        Dim fetchRequestKeyListArray()() As String = New String(envs.Count)() {}

        ' The array of lists of FETCH keys to expect from the server in return
        ' to requests of items listed in each element of fetchRequestKeyListArray.
        Dim fetchResponseKeyListArray()() As String = New String(envs.Count)() {}

        ' UIDs of the messages for which we received the body structure.
        Dim uids() As Long = New Long(envs.Count) {}

        Dim i As Integer
        For i = 0 To envs.Count - 1
            Dim env As Envelope = envs(i)

            Dim fetchRequestKeyList As ArrayList = New ArrayList
            Dim fetchResponseKeyList As ArrayList = New ArrayList

            ' Get body structures of all MIME parts as flat list.
            Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()
            Dim part As ImapBodyStructure
            For Each part In parts
                Dim contentType As String = part.ContentType.ToLower()
                Dim disposition As String = String.Empty
                If Not part.Disposition Is Nothing Then disposition = part.Disposition.ToLower()
                If disposition <> "attachment" AndAlso (contentType = "text/plain" Or contentType = "text/html") Then
                    If parts.Count > 1 Then
                        ' For each text body part, we request its MIME part header and the first 300 bytes
                        ' of the body. Also note using .MIME instead of .HEADER
                        ' because some mail servers don't support .HEADER syntax.
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + ".MIME]")
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + "]<0.300>")

                        ' For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[" + part.PartID + ".MIME]")
                        fetchResponseKeyList.Add("BODY[" + part.PartID + "]<0>")
                    Else
                        fetchRequestKeyList.Add("BODY.PEEK[HEADER]")
                        fetchRequestKeyList.Add("BODY.PEEK[TEXT]<0.300>")

                        ' For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[HEADER]")
                        fetchResponseKeyList.Add("BODY[TEXT]<0>")
                    End If
                End If
            Next

            ' Second time, we'll get message by its UID. This will avoid the situation
            ' when new message arrives between two queries (and thus it could be possible
            ' to download wrong message second time).
            uids(i) = env.Uid

            ' Save the generated items for FETCH request and FETCH response.
            fetchRequestKeyListArray(i) = CType(fetchRequestKeyList.ToArray(GetType(String)), String())
            fetchResponseKeyListArray(i) = CType(fetchResponseKeyList.ToArray(GetType(String)), String())
        Next

        If envs.Count > 0 Then
            ' Download previews of text parts.
            imp.BeginDownloadEnvelopesEx(uids, True, Nothing, Nothing, Nothing, fetchRequestKeyListArray, _
             Nothing, Nothing)
            envs = imp.EndDownloadEnvelopesEx()

            Dim env As Envelope
            For Each env In envs
                ' We need this to find FETCH request and response keys
                ' which correspond to the envelope being examined.
                Dim index As Integer = Array.IndexOf(uids, env.Uid)

                If index < 0 Then
                    ' For some odd reason, we got envelope we haven't requested.
                    ' Hope this will never happen. Anyway, skip such envelope.
                    ' In VB 2005 and higher you can use Continue statement instead of Goto.
                    GoTo ContinueHere
                End If

                Dim fetchRequestKeys() As String = fetchRequestKeyListArray(index)
                Dim fetchResponseKeys() As String = fetchResponseKeyListArray(index)

                Dim j As Integer
                For j = 0 To fetchRequestKeys.Length - 1 Step 2
                    ' Get MIME part header data.
                    Dim mimePartHeader, mimePartBody As Byte()
                    mimePartHeader = env.GetEnvelopeItem(CType(fetchResponseKeys(j), String), True)

                    ' Get MIME part body data.
                    mimePartBody = env.GetEnvelopeItem(CType(fetchResponseKeys(j + 1), String), True)

                    ' Build MIME part data from header data and body data.
                    Dim mimePartData As Byte()
                    ReDim mimePartData(mimePartHeader.Length + mimePartBody.Length)
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length)
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData, mimePartHeader.Length, mimePartBody.Length)
                    mimePartHeader = Nothing
                    mimePartBody = Nothing

                    ' Build TextBodyPart object from the MIME part data.
                    Dim part As MimePart = MimePart.Parse(mimePartData)
                    Dim textPart As TextBodyPart = New TextBodyPart(part)

                    ' Print content-type and text content of the message.
                    Console.WriteLine("For message with UID=" & env.Uid)
                    Console.WriteLine("Content-Type=" & part.ContentType)
                    Console.WriteLine("The text follows...")
                    Console.WriteLine(textPart.Text)
                    Console.WriteLine("---------------------------------")
                    Console.WriteLine()
                Next
ContinueHere:
            Next
        End If

        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.BeginDownloadFolders Method

ImapBeginDownloadFolders Method

Note: This API is now obsolete.

Begins an asynchronous request for downloading IMAP folders matching the specified criteria.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadFoldersAsync instead.")]
public IAsyncResult BeginDownloadFolders(
    bool subscribedOnly,
    string parentFolderName,
    string pattern,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadFoldersAsync instead.")>
Public Function BeginDownloadFolders (
    subscribedOnly As Boolean,
    parentFolderName As String,
    pattern As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

subscribedOnly
Type: SystemBoolean
If true, only subscribed folders will be downloaded; otherwise, all the folders.
parentFolderName
Type: SystemString
The full name of the folder which subfolders must be downloaded, or a null reference (Nothing in Visual Basic) to download all the folders.
pattern
Type: SystemString
The exact or wildcard name (relative to parentFolderName) of the folder or folders to be downloaded, or a null reference (Nothing in Visual Basic) to download all the folders.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous download folder list process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of DownloadFolders(Boolean, String, String).
Examples
This sample demonstrates asynchronous downloading of folders list using complex pattern in a console application. BeginDownloadFolders(Boolean, String, String, AsyncCallback, Object) method is called twice. First, to get a delimiter of folders level. Second, to get the list of folders which are subfolders of the 1st level. Thus, "Inbox/Orders" and "Sent Items/Personal" will be listed while "Inbox", "Sent Items", "Drafts", "Inbox/Orders/April 2006", "Inbox/Orders/April 2006/29" will not (because they are either parent folders or subfolders of deeper levels such as 2, 3, etc).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("mail.somehost.com");

        imp.Login("jdoe", "secret");

        // Initiate an asynchronous download folder list attempt.
        // This will download a single empty Folder element having only delimiter
        // field set. We need it in order to correctly combine pattern value for
        // subsequent folder list download.
        IAsyncResult ar = imp.BeginDownloadFolders(false, "", "", null, null);

        // Simulate some lengthy work here. At the same time,
        // folders are being downloaded is executed on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the download is still in progress, then wait until it's finished,
        // and get the delimiter.
        FolderCollection folders = imp.EndDownloadFolders();

        if (folders.Count == 0)
        {
            Console.WriteLine("Bad IMAP4 server.");
        }
        else
        {
            string delim = folders[0].Delimiter;

            if (delim == null)
            {
                Console.WriteLine("Folder names are flat. Hierarchy is not supported.");
            }
            else
            {

                // Initiate an asynchronous download folder list attempt.
                // Here, we request to download all 1st level subfolders of the account.
                ar = imp.BeginDownloadFolders(false, "", "%" + delim + "%", null, null);

                // Simulate some lengthy work here. At the same time,
                // folders are being downloaded is executed on another thread.
                System.Threading.Thread.Sleep(3000);

                // If the download is still in progress, then wait until it's finished,
                // and get the folders.
                folders = imp.EndDownloadFolders();

                // Print folder names matching the specified criteria.
                foreach (Folder fold in folders)
                {
                    Console.WriteLine(fold.Name);
                }
            }
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        imp.Connect("imap4.company.com")

        imp.Login("jdoe@company.com", "secret")

        ' Initiate an asynchronous download folder list attempt.
        ' This will download a single empty Folder element having only delimiter
        ' field set. We need it in order to correctly combine pattern value for
        ' subsequent folder list download.
        Dim ar As IAsyncResult = imp.BeginDownloadFolders(False, "", "", Nothing, Nothing)

        ' Simulate some lengthy work here. At the same time,
        ' folders are being downloaded is executed on another thread.
        System.Threading.Thread.Sleep(3000)

        ' If the download is still in progress, then wait until it's finished,
        ' and get the delimiter.
        Dim folders As FolderCollection = imp.EndDownloadFolders()

        If folders.Count = 0 Then
            Console.WriteLine("Bad IMAP4 server.")
        Else
            Dim delim As String = folders(0).Delimiter

            If delim Is Nothing Then
                Console.WriteLine("Folder names are flat. Hierarchy is not supported.")
            Else
                ' Initiate an asynchronous download folder list attempt.
                ' Here, we request to download all 1st level subfolders of the account.
                ar = imp.BeginDownloadFolders(False, "", "%" & delim & "%", Nothing, Nothing)

                ' Simulate some lengthy work here. At the same time,
                ' folders are being downloaded is executed on another thread.
                System.Threading.Thread.Sleep(3000)

                ' If the download is still in progress, then wait until it's finished,
                ' and get the folders.
                folders = imp.EndDownloadFolders()

                ' Print folder names matching the specified criteria.
                For Each fold As Folder In folders
                    Console.WriteLine(fold.Name)
                Next
            End If
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDownloadFolders(Boolean, String, String)


Imap.BeginExecuteCustomCommand Method

ImapBeginExecuteCustomCommand Method

Note: This API is now obsolete.

Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ExecuteCustomCommanAsync instead.")]
public IAsyncResult BeginExecuteCustomCommand(
    string command,
    string commandID,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ExecuteCustomCommanAsync instead.")>
Public Function BeginExecuteCustomCommand (
    command As String,
    commandID As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

command
Type: SystemString
User-defined command text (without line terminator).
commandID
Type: SystemString
The ID (tag in IMAP4 terms) which will be prepended to the command text, or an empty string to let MailBee autogenerate the ID value, or a null reference (Nothing in Visual Basic) to send command without ID.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous user-defined command execution.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of ExecuteCustomCommand(String, String).
Examples

This console sample shows how manage folders (create, delete, rename, subscribe, unsubscribe), expunge deleted messages, and issue NOOP asynchronously.

BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic also includes the second WinForms sample of sending NOOP command asynchronously (see below).

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Console.WriteLine("Input a new folder name to manage");
        string folderName = Console.ReadLine();

        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap.domain.com");
        imp.Login("jdoe@domain.com", "secret");

        // Issue NOOP
        imp.BeginExecuteCustomCommand("NOOP", string.Empty, null, null);
        imp.EndExecuteCustomCommand();

        // Create a new folder
        imp.BeginExecuteCustomCommand(
            "CREATE " + ImapUtils.ToUtf7QuotedString(folderName),
            string.Empty, null, null);
        imp.EndExecuteCustomCommand();

        // Select the created folder (to demonstrate asynchronous Expunge).
        imp.BeginSelectFolder(folderName, false, null, null);
        imp.EndSelectFolder();

        // Expunge deleted messages from this folder. This will actually do
        // nothing since the folder is empty but it shows the idea.
        imp.BeginExecuteCustomCommand("EXPUNGE", string.Empty, null, null);
        imp.EndExecuteCustomCommand();

        // Deselect the folder (we could also call BeginClose(true, ...)
        // to close the folder and expunge the deleted messages instead of
        // sending EXPUNGE and calling BeginClose(false, ...).
        imp.BeginClose(false, null, null);
        imp.EndClose();

        // Subscribe the created folder
        imp.BeginExecuteCustomCommand(
            "SUBSCRIBE " + ImapUtils.ToUtf7QuotedString(folderName),
            string.Empty, null, null);
        imp.EndExecuteCustomCommand();

        // Unsubscribe the created folder
        imp.BeginExecuteCustomCommand(
            "UNSUBSCRIBE " + ImapUtils.ToUtf7QuotedString(folderName),
            string.Empty, null, null);
        imp.EndExecuteCustomCommand();

        // Rename the created folder into "MyFolder".
        imp.BeginExecuteCustomCommand(
            "RENAME " + ImapUtils.ToUtf7QuotedString(folderName) + " " +
            ImapUtils.ToQuotedString("MyFolder"), string.Empty, null, null);
        imp.EndExecuteCustomCommand();

        // Delete the created folder
        imp.BeginExecuteCustomCommand(
            "DELETE " + ImapUtils.ToQuotedString("MyFolder"), string.Empty,
            null, null);
        imp.EndExecuteCustomCommand();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Console.WriteLine("Input a new folder name to manage")
        Dim folderName As String = Console.ReadLine()

        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap.domain.com")
        imp.Login("jdoe@domain.com", "secret")

        ' Issue NOOP
        imp.BeginExecuteCustomCommand("NOOP", String.Empty, Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Create a new folder
        imp.BeginExecuteCustomCommand( _
            "CREATE " & ImapUtils.ToUtf7QuotedString(folderName), _
            String.Empty, Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Select the created folder (to demonstrate asynchronous Expunge).
        imp.BeginSelectFolder(folderName, False, Nothing, Nothing)
        imp.EndSelectFolder()

        ' Expunge deleted messages from this folder. This will actually do
        ' nothing since the folder is empty but it shows the idea.
        imp.BeginExecuteCustomCommand("EXPUNGE", String.Empty, Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Deselect the folder (we could also call BeginClose(true, ...)
        ' to close the folder and expunge the deleted messages instead of
        ' sending EXPUNGE and calling BeginClose(false, ...).
        imp.BeginClose(False, Nothing, Nothing)
        imp.EndClose()

        ' Subscribe the created folder
        imp.BeginExecuteCustomCommand( _
            "SUBSCRIBE " & ImapUtils.ToUtf7QuotedString(folderName), _
            String.Empty, Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Unsubscribe the created folder
        imp.BeginExecuteCustomCommand( _
            "UNSUBSCRIBE " & ImapUtils.ToUtf7QuotedString(folderName), _
            String.Empty, Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Rename the created folder into "MyFolder".
        imp.BeginExecuteCustomCommand( _
            "RENAME " & ImapUtils.ToUtf7QuotedString(folderName) & " " & _
            ImapUtils.ToQuotedString("MyFolder"), String.Empty, Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Delete the created folder
        imp.BeginExecuteCustomCommand( _
            "DELETE " & ImapUtils.ToQuotedString("MyFolder"), String.Empty, _
            Nothing, Nothing)
        imp.EndExecuteCustomCommand()

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
Examples
This WinForms sample shows how to send NOOP command asynchronously to keep the connection with the server alive for a long period of time. The same approach can be used to execute any IMAP4 command asynchronously.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

System.Timers.Timer t = null;
Imap imp = null;

// A callback function. Since it's called on Imap worker thread,
// WinForms timer cannot be used here because it can only be used
// on message loop thread.
private void ExecuteCustomCommandCallback(IAsyncResult result)
{
    Imap imp = (Imap)result.AsyncState;
    imp.EndExecuteCustomCommand();
    imp.Log.WriteLine("NOOP done");
    t.Start();
}

// System.Timers.Timer.Elapsed event handler.
private void OnElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    t.Stop();

    // Execute NOOP command in Imap worker thread.
    imp.BeginExecuteCustomCommand("NOOP", string.Empty,
        new AsyncCallback(ExecuteCustomCommandCallback), imp);
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    imp = new Imap();

    // Enable logging to monitor background activity.
    imp.Log.Filename = @"C:\Temp\log.txt";
    imp.Log.Enabled = true;
    imp.Log.Clear();

    // Connect to the server, login and select inbox.
    imp.Connect("imap.domain.com");
    imp.Login("jdoe", "secret");
    imp.SelectFolder("Inbox");

    // Initialize timer to raise Elapsed event every 10 seconds.
    t = new System.Timers.Timer();
    t.Elapsed += new System.Timers.ElapsedEventHandler(OnElapsed);
    t.Interval = 10000;
    t.Start();
}

// Shutdown Imap component on form closing.
private void Form1_Closing(object sender,
    System.ComponentModel.CancelEventArgs e)
{
    t.Stop();
    if (imp.IsBusy)
    {
        imp.EndExecuteCustomCommand();
    }
    // Disconnect from the server.
    imp.Disconnect();
}
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

Dim t As System.Timers.Timer = Nothing
Dim imp As Imap = Nothing

' A callback function. Since it's called on Imap worker thread,
' WinForms timer cannot be used here because it can only be used
' on message loop thread.
Private Sub ExecuteCustomCommandCallback(ByVal result As IAsyncResult)
    Dim imp As Imap = CType(result.AsyncState, Imap)
    imp.EndExecuteCustomCommand()
    imp.Log.WriteLine("NOOP done")
    t.Start()
End Sub

' System.Timers.Timer.Elapsed event handler.
Private Sub OnElapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
    t.Stop()

    ' Execute NOOP command in Imap worker thread.
    imp.BeginExecuteCustomCommand("NOOP", String.Empty, _
        New AsyncCallback(AddressOf ExecuteCustomCommandCallback), imp)
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    imp = New Imap

    ' Enable logging to monitor background activity.
    imp.Log.Filename = "C:\Temp\log.txt"
    imp.Log.Enabled = True
    imp.Log.Clear()

    ' Connect to the server, login and select inbox.
    imp.Connect("imap.domain.com")
    imp.Login("jdoe", "secret")
    imp.SelectFolder("Inbox")

    ' Initialize timer to raise Elapsed event every 10 seconds.
    t = New System.Timers.Timer
    AddHandler t.Elapsed, AddressOf OnElapsed
    t.Interval = 10000
    t.Start()
End Sub

' Shutdown Imap component on form closing.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
    t.Stop()
    If imp.IsBusy Then
        imp.EndExecuteCustomCommand()
    End If
    ' Disconnect from the server.
    imp.Disconnect()
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapExecuteCustomCommand(String, String)


Imap.BeginIdle Method

ImapBeginIdle Method

Note: This API is now obsolete.

Begins an asynchronous request for starting idling mode.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use IdleAsync instead.")]
public IAsyncResult BeginIdle(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use IdleAsync instead.")>
Public Function BeginIdle (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous idle process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Idle. However, unlike Idle, using BeginIdle(AsyncCallback, Object) method usually does not require subscribing to Idling event because BeginIdle(AsyncCallback, Object) does not block and the application can use other techniques to keep UI responsive during idling.
Examples
This WinForms sample is an asynchronous version of the sample listed in Idle method documentation. Idling event is not used but UI still does not freeze during idling.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// Imap object declared global because it's accessed from several methods.
Imap imp = null;

bool started = false;

// Monitor folder changes and save them in the log file.
private void imp_MessageStatus(object sender, ImapMessageStatusEventArgs e)
{
    ((Imap)sender).Log.WriteLine("Got " + e.StatusID + " status update");
}

// Start/stop idling.
// Add button1 on the form to make this sample working.
private void button1_Click(object sender, System.EventArgs e)
{
    if (started)
    {
        // Stop idling.
        imp.StopIdle();
        imp.EndIdle();

        // Disconnect from the server and revert to the original state.
        imp.Disconnect();
        button1.Text = "Go idle";
        started = false;
    }
    else
    {
        started = true;

        imp = new Imap();

        // Enable logging into a file.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Connect to the server and check if IDLE is supported.
        imp.Connect("mail.domain.com");
        if (imp.GetExtension("IDLE") == null)
        {
            MessageBox.Show("IDLE not supported");
            imp.Disconnect();
            started = false;
        }
        else
        {
            // Login and select inbox.
            imp.Login("jdoe", "secret");
            imp.SelectFolder("Inbox");

            // Attach event handler.
            imp.MessageStatus +=new ImapMessageStatusEventHandler(imp_MessageStatus);

            button1.Text = "Stop idle";

            // Go idle in the background.
            imp.BeginIdle(null, null);
        }
    }
}

// Finish idling if the user closes the application.
// To make this method work, attach it to Closing event of the form.
private void Form1_Closing(object sender,
    System.ComponentModel.CancelEventArgs e)
{
    if (imp != null && imp.IsBusy)
    {
        imp.StopIdle();
        imp.EndIdle();
        imp.Disconnect();
    }
}
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

' Imap object declared global because it's accessed from several methods.
Dim imp As Imap = Nothing

Dim started As Boolean = False

' Monitor folder changes and save them in the log file.
Private Sub imp_MessageStatus(ByVal sender As Object, ByVal e As ImapMessageStatusEventArgs)
    CType(sender, Imap).Log.WriteLine("Got " & e.StatusID & " status update")
End Sub

' Start/stop idling.
' Add button1 on the form to make this sample working.
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    If started Then
        ' Stop idling.
        imp.StopIdle()
        imp.EndIdle()

        ' Disconnect from the server and revert to the original state.
        imp.Disconnect()
        button1.Text = "Go idle"
        started = False
    Else
        started = True

        imp = New Imap

        ' Enable logging into a file.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Connect to the server and check if IDLE is supported.
        imp.Connect("mail.domain.com")
        If imp.GetExtension("IDLE") Is Nothing Then
            MsgBox("IDLE not supported")
            imp.Disconnect()
            started = False
        Else
            ' Login and select inbox.
            imp.Login("jdoe", "secret")
            imp.SelectFolder("Inbox")

            ' Attach event handler.
            AddHandler imp.MessageStatus, AddressOf imp_MessageStatus

            button1.Text = "Stop idle"

            ' Go idle in the background.
            imp.BeginIdle(Nothing, Nothing)
        End If
    End If
End Sub

' Finish idling if the user closes the application.
' To make this method work, attach it to Closing event of the form.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
    If Not imp Is Nothing And imp.IsBusy Then
        imp.StopIdle()
        imp.EndIdle()
        imp.Disconnect()
    End If
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapIdle


Imap.BeginLogin Method

ImapBeginLogin Method

Note: This API is now obsolete.

Begins an asynchronous request for a logging in an account on an IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use LoginAsync instead.")]
public IAsyncResult BeginLogin(
    string targetName,
    string domain,
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use LoginAsync instead.")>
Public Function BeginLogin (
    targetName As String,
    domain As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

targetName
Type: SystemString
The Service Principal Name of the server. Used only with GSSAPI/Kerberos authentication. You can leave it a null reference (Nothing in Visual Basic) or an empty string.
domain
Type: SystemString
The user account domain on the server. Used only with NTLM and GSSAPI authentication. You can leave it a null reference to use the current domain.
accountName
Type: SystemString
The user account name on the server. You can leave it a null reference when using NTLM or GSSAPI and wish to authenticate as the current Windows user.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous login process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Examples
This sample demonstrates asynchronous logging in an account and use of a callback function in a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // A callback function.
    private static void LoginCallback(IAsyncResult result)
    {
        Imap imp = (Imap)result.AsyncState;
        imp.EndLogin();
        imp.SelectFolder("INBOX");
        Console.WriteLine("Message #" + imp.Unseen + " is first unseen");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("imap.somehost.com");

        // Initiate an asynchronous login attempt.
        IAsyncResult ar = imp.BeginLogin(null, null, "jdoe", "secret",
            AuthenticationMethods.Auto, AuthenticationOptions.None,
            null, new AsyncCallback(LoginCallback), imp);

        // Simulate some lengthy work here. At the same time,
        // login is executed on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the login attempt is still in progress, then wait until it's finished.
        while (imp.IsBusy) ar.AsyncWaitHandle.WaitOne();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Class Sample
    ' A callback function.
    Private Shared Sub LoginCallback(ByVal result As IAsyncResult)
        Dim imp As New Imap
        imp = result.AsyncState
        imp.EndLogin()
        imp.SelectFolder("INBOX")
        Console.WriteLine("Message #" & imp.Unseen & " is first unseen")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim imp As New Imap

        imp.Connect("imap.somehost.com")

        ' Initiate an asynchronous login attempt.
        Dim ar = imp.BeginLogin(Nothing, Nothing, "jdoe", "secret", _
            AuthenticationMethods.Auto, AuthenticationOptions.None, _
            Nothing, New AsyncCallback(AddressOf LoginCallback), imp)

        ' Simulate some lengthy work here. At the same time
        ' login is executed on another thread.
        System.Threading.Thread.Sleep(3000)

        ' If the login attempt is still in progress, then wait until it's finished.
        While imp.IsBusy
            ar.AsyncWaitHandle.WaitOne()
        End While

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
ImapBeginConnect(String, Int32, Socket, EndPoint, AsyncCallback, Object)
MailBeeSaslMethod


Imap.BeginSearch Method

ImapBeginSearch Method

Note: This API is now obsolete.

Begins an asynchronous request for searching the currently selected folder for messages meeting the specified criteria.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SearchAsync instead.")]
public IAsyncResult BeginSearch(
    bool returnUids,
    string searchCondition,
    string charset,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SearchAsync instead.")>
Public Function BeginSearch (
    returnUids As Boolean,
    searchCondition As String,
    charset As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

returnUids
Type: SystemBoolean
If true, search results will be returned as UidCollection; otherwise, as MessageNumberCollection.
searchCondition
Type: SystemString
Search expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method return all messages in the folder.
charset
Type: SystemString
Charset used in searchCondition, or a null reference to use US-ASCII setting.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous search process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Search(Boolean, String, String).
Examples
This WinForms sample demonstrates asynchronous search of messages arrived into the Inbox folder since yesterday. Also, it demonstrates how to handle exceptions and update the application user interface (UI) when using callback functions (which are not directly allowed to update UI due to threading limitations).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// Declaration of delegate which will update UI.
private delegate void UpdateUIDelegate(Imap imp);

// This method will be called as a delegate by Form.Invoke.
// Since Form.Invoke always executes delegates on UI thread,
// it's safe to update UI in this method (for instance, change
// text in Label or Button controls, disable/enable/add/remove
// controls, or do whatever you need to).
private void UpdateUI(Imap imp)
{
    // It's important to use exception handling here because otherwise
    // we could never know if exception was thrown. This is because this
    // method is called by SearchCallback which is executed on the worker
    // thread. If exception is thrown in UpdateUI method, Form.Invoke then
    // propagates it to SearchCallback by throwing TargetInvocationException
    // in SearchCallback. Now, because SearchCallback is executed on the worker
    // thread, this thread is terminated but no exception is thrown on the UI
    // thread. The worker thread just silently dies. Due to this, the developer
    // should carefully guard all code blocks in callback functions and any
    // methods called by these functions.
    // In this sample, we catch MailBeeException directly in UpdateUI. However,
    // we could also catch TargetInvocationException when calling Invoke in
    // SearchCallback and display .InnerException. The result would be the same
    // (because this sample can throw only MailBeeException in UpdateUI).
    // If UpdateUI method could also throw exceptions of other types, catching
    // TargetInvocationException when calling Invoke would also handle them all.
    // Thus, we need to either catch all exceptions inside the code of the method
    // being called by Form.Invoke or catch TargetInvocationException when calling
    // Form.Invoke itself.
    try
    {
        // Obtain ordinal message numbers of found messages and display them.
        MessageNumberCollection msgNums = (MessageNumberCollection)imp.EndSearch();
        MessageBox.Show(msgNums.ToString());
    }
    catch (MailBeeException e)
    {
        MessageBox.Show(e.Message);
    }

    // Update form's caption area to demonstrate
    // that it's safe to update UI in this method.
    this.Text = "Search finished";
}

// A callback function. Since it's called on Imap worker thread,
// it cannot update controls on the form or otherwise access UI.
// The only UI-related action permitted in worker thread is
// displaying a message box (MessageBox.Show).
// Any updates of UI must take place on message loop thread.
private void SearchCallback(IAsyncResult result)
{
    Imap imp = (Imap)result.AsyncState;

    // To end search and display results on UI thread, we use
    // Form.Invoke passing Imap instance as a parameter.
    Invoke(new UpdateUIDelegate(UpdateUI), new object[] {imp});

    // See comment in UpdateUI.
    try
    {
        imp.Disconnect();
    }
    catch (MailBeeException e)
    {
        MessageBox.Show(e.Message);
    }
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Imap imp = new Imap();

    // Connect to the server, login and select inbox.
    imp.Connect("imap4.mail.server.com");
    imp.Login("jdoe@server.com", "secret");
    imp.SelectFolder("Inbox");

    // Start async search of messages received since yesterday.
    imp.BeginSearch(false,
        "SINCE \"" + ImapUtils.GetImapDateString(DateTime.Today.AddDays(-1)) + "\"",
        null, new AsyncCallback(SearchCallback), imp);

    // Note: we do not wait until search is finished here.
    // Subsequent code calls will be made in SearchCallback.
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

' Declaration of delegate which will update UI.
Private Delegate Sub UpdateUIDelegate(ByVal imp As Imap)

' This method will be called as a delegate by Form.Invoke.
' Since Form.Invoke always executes delegates on UI thread,
' it's safe to update UI in this method (for instance, change
' text in Label or Button controls, disable/enable/add/remove
' controls, or do whatever you need to).
Private Sub UpdateUI(ByVal imp As Imap)
    ' It's important to use exception handling here because otherwise
    ' we could never know if exception was thrown. This is because this
    ' method is called by SearchCallback which is executed on the worker
    ' thread. If exception is thrown in UpdateUI method, Form.Invoke then
    ' propagates it to SearchCallback by throwing TargetInvocationException
    ' in SearchCallback. Now, because SearchCallback is executed on the worker
    ' thread, this thread is terminated but no exception is thrown on the UI
    ' thread. The worker thread just silently dies. Due to this, the developer
    ' should carefully guard all code blocks in callback functions and any
    ' methods called by these functions.
    ' In this sample, we catch MailBeeException directly in UpdateUI. However,
    ' we could also catch TargetInvocationException when calling Invoke in
    ' SearchCallback and display .InnerException. The result would be the same
    ' (because this sample can throw only MailBeeException in UpdateUI).
    ' If UpdateUI method could also throw exceptions of other types, catching
    ' TargetInvocationException when calling Invoke would also handle them all.
    ' Thus, we need to either catch all exceptions inside the code of the method
    ' being called by Form.Invoke or catch TargetInvocationException when calling
    ' Form.Invoke itself.
    Try
        ' Obtain ordinal message numbers of found messages and display them.
        Dim msgNums As MessageNumberCollection = CType(imp.EndSearch(), MessageNumberCollection)
        MessageBox.Show(msgNums.ToString())
    Catch e As MailBeeException
        MessageBox.Show(e.Message)
    End Try

    ' Update form's caption area to demonstrate
    ' that it's safe to update UI in this method.
    Me.Text = "Search finished"
End Sub

' A callback function. Since it's called on Imap worker thread,
' it cannot update controls on the form or otherwise access UI.
' The only UI-related action permitted in worker thread is
' displaying a message box (MessageBox.Show).
' Any updates of UI must take place on message loop thread.
Private Sub SearchCallback(ByVal result As IAsyncResult)
    Dim imp As Imap = CType(result.AsyncState, Imap)

    ' To end search and display results on UI thread, we use
    ' Form.Invoke passing Imap instance as a parameter.
    Invoke(New UpdateUIDelegate(AddressOf UpdateUI), New Object() {imp})

    ' See comment in UpdateUI.
    Try
        imp.Disconnect()
    Catch e As MailBeeException
        MessageBox.Show(e.Message)
    End Try
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim imp As New Imap

    ' Connect to the server, login and select inbox.
    imp.Connect("imap4.mail.server.com")
    imp.Login("jdoe@server.com", "secret")
    imp.SelectFolder("Inbox")

    ' Start async search of messages received since yesterday.
    imp.BeginSearch(False, "SINCE """ & _
        ImapUtils.GetImapDateString(DateTime.Today.AddDays(-1)) & _
        """", Nothing, New AsyncCallback(AddressOf SearchCallback), imp)

    ' Note: we do not wait until search is finished here.
    ' Subsequent code calls will be made in SearchCallback.
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)


Imap.BeginSelectFolder Method

ImapBeginSelectFolder Method

Note: This API is now obsolete.

Begins an asynchronous request for selecting a folder in an account on an IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SelectFolderAsync instead.")]
public IAsyncResult BeginSelectFolder(
    string folderName,
    bool readOnly,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SelectFolderAsync instead.")>
Public Function BeginSelectFolder (
    folderName As String,
    readOnly As Boolean,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

folderName
Type: SystemString
The full name of the folder to be selected.
readOnly
Type: SystemBoolean
Indicates if the folder should be selected in read-only mode.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous select folder process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of SelectFolder(String) (if readOnly is false) or ExamineFolder(String) (if readOnly is true).
Examples
This sample demonstrates asynchronous selecting a folder and use of a callback function in a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // A callback function.
    private static void SelectFolderCallback(IAsyncResult result)
    {
        Imap imp = (Imap)result.AsyncState;
        imp.EndSelectFolder();
        Console.WriteLine("Overall size of all messages in the inbox is " +
            imp.GetFolderSize() + " bytes");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("imap4.somehost.com");
        imp.Login("jdoe@somehost.com", "secret");

        // Initiate an asynchronous select folder attempt.
        IAsyncResult ar = imp.BeginSelectFolder("Inbox", false,
            new AsyncCallback(SelectFolderCallback), imp);

        // Simulate some lengthy work here. At the same time,
        // folder selection is executed on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the folder selection attempt is still in progress,
        // then wait until it's finished.
        while (imp.IsBusy) ar.AsyncWaitHandle.WaitOne();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample

    ' A callback function.
    Private Sub SelectFolderCallback(ByVal result As IAsyncResult)
        Dim imp As Imap = CType(result.AsyncState, Imap)
        imp.EndSelectFolder()
        Console.WriteLine("Overall size of all messages in the inbox is " & _
            imp.GetFolderSize() & " bytes")
    End Sub

    Sub Main()
        ' The actual code (put it into a method of your class)
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Initiate an asynchronous select folder attempt.
        Dim ar As IAsyncResult = imp.BeginSelectFolder("Inbox", False, _
            New AsyncCallback(AddressOf SelectFolderCallback), imp)

        ' Simulate some lengthy work here. At the same time,
        ' folder selection is executed on another thread.
        System.Threading.Thread.Sleep(3000)

        ' If the folder selection attempt is still in progress,
        ' then wait until it's finished.
        While imp.IsBusy
            ar.AsyncWaitHandle.WaitOne()
        End While

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapExamineFolder(String)
ImapSelectFolder(String)


Imap.BeginSetMessageFlags Method

ImapBeginSetMessageFlags Method

Note: This API is now obsolete.

Begins an asynchronous request to set or reset the specified message flags for the specified messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SetMessageFlagsAsync instead.")]
public IAsyncResult BeginSetMessageFlags(
    string messageIndexSet,
    bool indexIsUid,
    string flags,
    MessageFlagAction action,
    bool silentMode,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SetMessageFlagsAsync instead.")>
Public Function BeginSetMessageFlags (
    messageIndexSet As String,
    indexIsUid As Boolean,
    flags As String,
    action As MessageFlagAction,
    silentMode As Boolean,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
flags
Type: SystemString
The string containing IMAP4 flags to be set or reset.
action
Type: MailBee.ImapMailMessageFlagAction
The action to perform with the specified flags (set, reset, etc).
silentMode
Type: SystemBoolean
If true, the server will NOT respond with the new values of flags of the affected messages; otherwise, the server will produce a series of untagged FETCH responses containing the updated flag lists of affected messages.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous setting message flags.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean).
Examples

This WinForms samples deletes the first message in the inbox folder of the mail account asynchronously (in a worker thread). The sample then expunges the deleted messages (the expunge is also performed in worker thread).

The sample also demonstrates how to wait for asynchronous operation completion without blocking user interface of the application (the user can click buttons, move windows, etc) during the asynchronous processing. However, the sample does not allow the user to click a button which starts the asynchronous operation if this operation is already in progress.

C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

bool finished;
bool started = false;

// A callback function. Since it's called on Imap worker thread,
// it cannot display any messages or otherwise access UI.
// Any updates of UI must take place on message loop thread.
// See the sample in BeginSearch() topic on how to update UI in
// such scenario.
private void SetMessageFlagsCallback(IAsyncResult result)
{
    Imap imp = (Imap)result.AsyncState;

    // It's important to handle exceptions in worker threads. Otherwise,
    // the worker thread could silently die and the application would
    // have never known this had happened.
    try
    {
        imp.EndSetMessageFlags();
        imp.Expunge();
    }
    catch (MailBeeException e)
    {
        MessageBox.Show(e.Message);
    }
    finally
    {
        finished = true;
    }
}

// Add button1 on the form to make this sample working.
private void button1_Click(object sender, System.EventArgs e)
{
    if (started)
    {
        MessageBox.Show("The operation is already in progress");
    }
    else
    {
        started = true;
    }

    finished = false;

    Imap imp = new Imap();

    // Connect to the server, login and select inbox.
    imp.Connect("mail.company.com");
    imp.Login("jdoe", "secret");
    imp.SelectFolder("Inbox");

    // Asynchronously mark the first message as deleted. Instead of
    // MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Deleted),
    // we could simply use "\Deleted" (@"\Deleted" in C#).
    imp.BeginSetMessageFlags("1", false,
        MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Deleted),
        MessageFlagAction.Add, true,
        new AsyncCallback(SetMessageFlagsCallback), imp);

    // Wait until completion via periodic polling
    // of the completion status.
    while (!finished)
    {
        System.Threading.Thread.Sleep(1);

        // It's not necessary to call DoEvents here since we do not
        // handle any MailBee events in this sample. However, if we did,
        // we would have needed this call to let the events be processed.
        // Alternatively, we could have set imp.RaiseEventsViaMessageLoop
        // to false and use imp.Wait() instead of Thread.Sleep() and
        // Application.DoEvents(). If using imp.Wait(), we would not need
        // to prevent this routine from being called again while it's
        // already being executed since imp.Wait() blocks UI and it would
        // be impossible to click a button until imp.Wait() completes.
        Application.DoEvents();
    }

    // Disconnect from the server.
    imp.Disconnect();

    started = false;
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

Dim finished As Boolean
Dim started As Boolean = False

' A callback function. Since it's called on Imap worker thread,
' it cannot display any messages or otherwise access UI.
' Any updates of UI must take place on message loop thread.
' See the sample in BeginSearch() topic on how to update UI in
' such scenario.
Private Sub SetMessageFlagsCallback(ByVal result As IAsyncResult)
    Dim imp As Imap = CType(result.AsyncState, Imap)

    ' It's important to handle exceptions in worker threads. Otherwise,
    ' the worker thread could silently die and the application would
    ' have never known this had happened.
    Try
        imp.EndSetMessageFlags()
        imp.Expunge()
    Catch e As MailBeeException
        MessageBox.Show(e.Message)
    Finally
        finished = True
    End Try
End Sub

' Add button1 on the form to make this sample working.
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    If started Then
        MessageBox.Show("The operation is already in progress")
    Else
        started = True
    End If

    finished = False

    Dim imp As New Imap

    ' Connect to the server, login and select inbox.
    imp.Connect("mail.company.com")
    imp.Login("jdoe", "secret")
    imp.SelectFolder("Inbox")

    ' Asynchronously mark the first message as deleted. Instead of
    ' MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Deleted),
    ' we could simply use "\Deleted" ("\Deleted" in Visual Basic).
    imp.BeginSetMessageFlags("1", False, _
        MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Deleted), _
        MessageFlagAction.Add, True, New AsyncCallback(AddressOf SetMessageFlagsCallback), imp)

    ' Wait until completion via periodic polling
    ' of the completion status.
    While Not finished
        System.Threading.Thread.Sleep(1)

        ' It's not necessary to call DoEvents here since we do not
        ' handle any MailBee events in this sample. However, if we did,
        ' we would have needed this call to let the events be processed.
        ' Alternatively, we could have set imp.RaiseEventsViaMessageLoop
        ' to false and use imp.Wait() instead of Thread.Sleep() and
        ' Application.DoEvents(). If using imp.Wait(), we would not need
        ' to prevent this routine from being called again while it's
        ' already being executed since imp.Wait() blocks UI and it would
        ' be impossible to click a button until imp.Wait() completes.
        Application.DoEvents()
    End While

    ' Disconnect from the server.
    imp.Disconnect()

    started = False
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean)


Imap.BeginSortedSearch Method

ImapBeginSortedSearch Method

Note: This API is now obsolete.

Begins an asynchronous request for searching the currently selected folder for messages meeting the specified criteria and sorting them accordingly the specified sort condition.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SortedSearchAsync instead.")]
public IAsyncResult BeginSortedSearch(
    bool returnUids,
    string searchCondition,
    string charset,
    string orderBy,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SortedSearchAsync instead.")>
Public Function BeginSortedSearch (
    returnUids As Boolean,
    searchCondition As String,
    charset As String,
    orderBy As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

returnUids
Type: SystemBoolean
If true, search results will be returned as UidCollection; otherwise, as MessageNumberCollection.
searchCondition
Type: SystemString
Search expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method return all messages in the folder.
charset
Type: SystemString
Charset used in searchCondition, or a null reference to use US-ASCII setting.
orderBy
Type: SystemString
Sorting order expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method downgrade to the regular BeginSearch(Boolean, String, String, AsyncCallback, Object).
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous search process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of SortedSearch(Boolean, String, String, String).
Examples
This console sample demonstrates asynchronous search of messages arrived into the Inbox folder since yesterday and sorting them by their Subject line.
C#
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // A callback function.
    private static void SortedSearchCallback(IAsyncResult result)
    {
        // Extract values from state object.
        Imap imp = (Imap)((object [])result.AsyncState)[0];
        bool sortAvail = (bool)((object [])result.AsyncState)[1];

        // Display the outcome.
        Console.WriteLine("SORT capability is " + (!sortAvail ? "NOT " : "") + "available");
        try
        {
            Console.WriteLine("UIDs found: " + ((UidCollection)imp.EndSortedSearch()).ToString());
        }
        catch (Exception e)
        {
            // Catching exception here is recommended. Because callback function is a separate
            // thread, unhandled exception would silently terminate it without any message to
            // the user (and it would be hard to understand what exactly happened).
            Console.WriteLine("Exception occurred: " + e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Set to true if SORT extension is available.
        bool sortAvail = (imp.GetExtension("SORT") != null);

        // If SORT is supported, order messages by SUBJECT field. If SORT is not supported,
        // orderBy criteria will not be set and SortedSearch will downgrade to the regular Search.
        string orderByCriteria = sortAvail ? "SUBJECT" : null;

        // Initiate an asynchronous request for getting UIDs of messages received since yesterday,
        // sorted accordingly orderByCriteria.
        IAsyncResult ar = imp.BeginSortedSearch(true,
            "SINCE \"" + ImapUtils.GetImapDateString(DateTime.Today.AddDays(-1)) + "\"",
            null, orderByCriteria,
            new AsyncCallback(SortedSearchCallback), new object[] {imp, sortAvail});

        // Simulate some lengthy work here. At the same time,
        // folder selection is executed on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the folder selection attempt is still in progress,
        // then wait until it's finished.
        while (imp.IsBusy) ar.AsyncWaitHandle.WaitOne();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSortedSearch(Boolean, String, String, String)
ImapBeginSearch(Boolean, String, String, AsyncCallback, Object)


Imap.BeginStartTls Method

ImapBeginStartTls Method

Note: This API is now obsolete.

Begins an asynchronous request to start TLS/SSL negotiation with the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use StartTlsAsync instead.")]
public IAsyncResult BeginStartTls(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use StartTlsAsync instead.")>
Public Function BeginStartTls (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous TLS/SSL negotiation.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of StartTls.
Examples
Asynchronous TLS/SSL negotiation with the IMAP4 server in WinForms application. This sample also handles TlsStarted event. Wait method is used to wait for the asynchronous method completion, since .NET's standard WaitOne(Int32, Boolean) cannot process events.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// TlsStarted event handler.
private void OnTlsStarted(object sender, TlsStartedEventArgs e)
{
    MessageBox.Show("TLS/SSL negotiation complete. Secure connection is ready.");
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Imap imp = new Imap();

    // Let MailBee process events.
    imp.RaiseEventsViaMessageLoop = false;

    imp.TlsStarted += new TlsStartedEventHandler(OnTlsStarted);

    imp.Connect("mail.company.com");

    // Initiate an asynchronous TLS/SSL negotiation.
    imp.BeginStartTls(null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        imp.Wait(0);
    }

    // If the connection was not established during execution of the lengthy
    // work, wait until it's established.
    imp.Wait();

    // End the connection request.
    imp.EndStartTls();

    // The connection is now under TLS/SSL layer!

    // Disconnect from the server.
    imp.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' TlsStarted event handler.
Public Shared Sub OnTlsStarted(ByVal sender As Object, ByVal e As TlsStartedEventArgs)
    MsgBox("TLS/SSL negotiation complete. Secure connection is ready.")
End Sub

' The actual code.
Public Shared Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim imp As New Imap

    ' Let MailBee process events.
    imp.RaiseEventsViaMessageLoop = False

    AddHandler imp.TlsStarted, AddressOf OnTlsStarted

    imp.Connect("mail.company.com")

    ' Initiate an asynchronous TLS/SSL negotiation.
    imp.BeginStartTls(Nothing, Nothing)

    ' Simulate some lengthy work here...
    For i As Integer = 1 To 100
        ' Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above.
        imp.Wait(0)
    Next

    ' If the connection was not established during execution of the lengthy
    ' work, wait until it's established.
    imp.Wait()

    ' End the connection request.
    imp.EndStartTls()

    ' The connection is now under TLS/SSL layer!

    ' Disconnect from the server.
    imp.Disconnect()
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapStartTls


Imap.BeginUploadMessage Method

ImapBeginUploadMessage Method

Note: This API is now obsolete.

Begins an asynchronous request for uploading the message into the specified folder on the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use UploadMessageAsync instead.")]
public IAsyncResult BeginUploadMessage(
    MailMessage msg,
    string folderName,
    string flags,
    string dateTimeString,
    bool batchMode,
    UidPlusResult result,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use UploadMessageAsync instead.")>
Public Function BeginUploadMessage (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dateTimeString As String,
    batchMode As Boolean,
    result As UidPlusResult,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dateTimeString
Type: SystemString
The string containing datetime (in IMAP4 format) to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server), or a null reference to let the server assign its current datetime value.
batchMode
Type: SystemBoolean
If true and LITERAL+ extension is supported by the server, the message will be uploaded in a single network operation; otherwise, in two operations.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the upload operation reported by UIDPLUS enabled server (the outcome includes the UID assigned to the uploaded message and the UIDVALIDITY of the folder the message was uploaded to), or a null reference if the application does not need this information.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous upload process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult).
Examples
This sample demonstrates asynchronous uploading a message into "Draft" folder and use of a callback function in a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // A callback function.
    private static void UploadMessageCallback(IAsyncResult result)
    {
        Imap imp = (Imap)result.AsyncState;

        try
        {
            imp.EndUploadMessage();
            Console.WriteLine("The message was successfully uploaded");
        }
        catch (MailBeeException e)
        {
            // In callback functions (generally speaking, in worker threads),
            // it's better to handle exceptions. If exception is not handled,
            // the worker thread silently dies and the application may never
            // know that something went wrong.
            Console.WriteLine(e.Message);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap.somedomain.com");
        imp.Login("jdoe", "secret");

        // Create a new message. Assume we need to save a draft of the message.
        MailMessage msg = new MailMessage();

        // Initiate an asynchronous upload attempt with the following settings:
        // - Object to download: msg
        // - Folder to download to: Draft
        // - Flags: \Draft
        // - Message date on server: datetime/timezone of the local computer
        // - batch mode: enabled
        // - obtain UID of uploaded message: no, thanks
        IAsyncResult ar = imp.BeginUploadMessage(msg, "Draft", @"\Draft",
            null, true, null, new AsyncCallback(UploadMessageCallback), imp);

        // Simulate some lengthy work here. At the same time,
        // uploading occurs on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the upload process is still in progress,
        // then wait until it's finished.
        while (imp.IsBusy) ar.AsyncWaitHandle.WaitOne();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    ' A callback function.
    Private Sub UploadMessageCallback(ByVal result As IAsyncResult)
        Dim imp As Imap = CType(result.AsyncState, Imap)

        Try
            imp.EndUploadMessage()
            Console.WriteLine("The message was successfully uploaded")
        Catch e As MailBeeException
            ' In callback functions (generally speaking, in worker threads),
            ' it's better to handle exceptions. If exception is not handled,
            ' the worker thread silently dies and the application may never
            ' know that something went wrong.
            Console.WriteLine(e.Message)
        End Try
    End Sub

    ' The actual code.
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap.somedomain.com")
        imp.Login("jdoe", "secret")

        ' Create a new message. Assume we need to save a draft of the message.
        Dim msg As New MailMessage

        ' Initiate an asynchronous upload attempt with the following settings:
        ' - Object to download: msg
        ' - Folder to download to: Draft
        ' - Flags: \Draft
        ' - Message date on server: datetime/timezone of the local computer
        ' - batch mode: enabled
        ' - obtain UID of uploaded message: no, thanks
        Dim ar As IAsyncResult = imp.BeginUploadMessage(msg, "Draft", "\Draft", _
            Nothing, True, Nothing, New AsyncCallback(AddressOf UploadMessageCallback), imp)

        ' Simulate some lengthy work here. At the same time,
        ' uploading occurs on another thread.
        System.Threading.Thread.Sleep(3000)

        ' If the upload process is still in progress,
        ' then wait until it's finished.
        While imp.IsBusy
            ar.AsyncWaitHandle.WaitOne()
        End While

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapUploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult)


Imap.Close Method

ImapClose Method
Overload List
 | Name | Description
 | Close | Unselects the currently selected folder and removes all messages having \Deleted flag set from the folder.
Public method | Close(Boolean) | Unselects the currently selected folder and optionally removes all messages having \Deleted flag set from the folder.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Close Method

ImapClose Method
Unselects the currently selected folder and removes all messages having \Deleted flag set from the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Close()
Public Function Close As Boolean

Return Value

Type: Boolean
true if the folder was unselected successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To avoid expunging messages marked as deleted, the developer should not call this method and simply close the connection with Disconnect method. Another way is to select a different folder or simply unselect the current folder using Close(false) call.

To expunge messages marked as deleted without unselecting the current folder, Expunge(String, Boolean) method should be called.

Examples
This sample marks the first message in Sent folder as deleted, and then closes this folder expunging deleted messages.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap.company.com");
        imp.Login("jdoe", "secret");

        // Select Sent folder.
        imp.SelectFolder("Sent");

        // Mark message #1 as deleted.
        imp.SetMessageFlags("1", false,
            SystemMessageFlags.Deleted, MessageFlagAction.Add);

        // Close the folder and expunge deleted messages.
        imp.Close();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        ' The actual code (put it into a method of your class)
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select Sent folder.
        imp.SelectFolder("Sent")

        ' Mark message #1 as deleted.
        imp.SetMessageFlags("1", False, _
            SystemMessageFlags.Deleted, MessageFlagAction.Add)

        ' Close the folder and expunge deleted messages.
        imp.Close()

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
Close Overload
MailBee.ImapMail Namespace
ImapDisconnect
ImapExpunge(String, Boolean)


Imap.Close Method (Boolean)

ImapClose Method (Boolean)
Unselects the currently selected folder and optionally removes all messages having \Deleted flag set from the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Close(
    bool expungeDeleted
)
Public Function Close (
    expungeDeleted As Boolean
) As Boolean

Parameters

expungeDeleted
Type: SystemBoolean
If true, the messages marked as deleted will be permanently removed from the folder.

Return Value

Type: Boolean
true if the folder was unselected successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If expungeDeleted is true, this method sends CLOSE command to the IMAP4 server. This commands expunges all messages marked as deleted from the selected folder, and then unselects the folder.

If expungeDeleted is false, this method simply unselects the currently selected folder. No messages are expunged. Unselecting is performed either via UNSELECT command if the server supports UNSELECT capability or via SELECT command without argument if UNSELECT capability is not supported.

Note Note
Another way of keeping messages marked as deleted without expunging them is calling Disconnect method or selecting another folder using SelectFolder(String) or ExamineFolder(String) method. Close(false) should only be used when the developer needs to close the current folder but retain the connection and do not select another folder.
See Also

Reference

Imap Class
Close Overload
MailBee.ImapMail Namespace
ImapSelectFolder(String)
ImapExpunge(String, Boolean)


Imap.CloseAsync Method

ImapCloseAsync Method
Overload List
 | Name | Description
Public method | CloseAsync | async/await version of Close.
Public method | CloseAsync(Boolean) | async/await version of Close(Boolean).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.CloseAsync Method

ImapCloseAsync Method
async/await version of Close.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> CloseAsync()
Public Function CloseAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
CloseAsync Overload
MailBee.ImapMail Namespace


Imap.CloseAsync Method (Boolean)

ImapCloseAsync Method (Boolean)
async/await version of Close(Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> CloseAsync(
    bool expungeDeleted
)
Public Function CloseAsync (
    expungeDeleted As Boolean
) As Task(Of Boolean)

Parameters

expungeDeleted
Type: SystemBoolean
If true, the messages marked as deleted will be permanently removed from the folder.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
CloseAsync Overload
MailBee.ImapMail Namespace


Imap.Connect Method

ImapConnect Method
Connects to an IMAP4 server.
Overload List
Name | Description
Connect(String) | Connects to an IMAP4 server on the standard IMAP4 port (143).
Connect(String, Int32) | Connects to an IMAP4 server.
Connect(String, Int32, Socket, EndPoint) | Connects to an IMAP4 server.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Connect Method (String)

ImapConnect Method (String)
Connects to an IMAP4 server on the standard IMAP4 port (143).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect(
    string serverName
)
Public Function Connect (
    serverName As String
) As Boolean

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.

Return Value

Type: Boolean
true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). Thus, this method can actually connect to the mail server on port 993 if you specified "imap.gmail.com" as serverName. To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.

Examples
This sample connects to the IMAP4 server, logs in the account, selects "Inbox" folder, downloads the last message entirely, and displays its body text. If the message is HTML formatted, plain-text version is displayed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("jdoe", "secret");
imp.SelectFolder("Inbox");
MailMessage msg = imp.DownloadEntireMessage(imp.MessageCount, false);
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;
Console.WriteLine(msg.BodyPlainText);
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
imp.Login("jdoe", "secret")
imp.SelectFolder("Inbox")
Dim msg As MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain
Console.WriteLine(msg.BodyPlainText)
imp.Disconnect()
See Also

Reference

Imap Class
Connect Overload
MailBee.ImapMail Namespace


Imap.Connect Method (String, Int32)

ImapConnect Method (String, Int32)
Connects to an IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect(
    string serverName,
    int port
)
Public Function Connect (
    serverName As String,
    port As Integer
) As Boolean

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard IMAP4 port is 143. For TLS/SSL connections, dedicated port is 993 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).

Return Value

Type: Boolean
true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). Thus, this method can actually connect to the mail server on port 993 if you specified "imap.gmail.com" as serverName. To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.
Examples
This sample connects to the IMAP4 server, logs in the account and selects "Inbox" folder, then downloads the last message entirely, and displays filenames of all attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com", 143);
imp.Login("jdoe", "secret");
imp.SelectFolder("Inbox");
MailMessage msg = imp.DownloadEntireMessage(imp.MessageCount, false);
foreach (Attachment attach in msg.Attachments)
{
    Console.WriteLine(attach.Filename);
}
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com", 143)
imp.Login("jdoe", "secret")
imp.SelectFolder("Inbox")
Dim msg As MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)
For Each attach As Attachment In msg.Attachments
    Console.WriteLine(attach.Filename)
Next
imp.Disconnect()
See Also

Reference

Imap Class
Connect Overload
MailBee.ImapMail Namespace


Imap.Connect Method (String, Int32, Socket, EndPoint)

ImapConnect Method (String, Int32, Socket, EndPoint)
Connects to an IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect(
    string serverName,
    int port,
    Socket socketToUse,
    EndPoint localEndPoint
)
Public Function Connect (
    serverName As String,
    port As Integer,
    socketToUse As Socket,
    localEndPoint As EndPoint
) As Boolean

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard IMAP4 port is 143. For TLS/SSL connections, dedicated port is 993 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).
socketToUse
Type: System.Net.SocketsSocket
Usually, a null reference (Nothing in Visual Basic). You can supply your own socket object here if you wish MailBee to use this object instead of creating a new one (typically, to fine-tune the WinSock subsystem when you need to deal with thousands of connections).
localEndPoint
Type: System.NetEndPoint
Usually, a null reference. Set it if you need to bind the connection to a certain local IP address/port to fine-tune the performance under heavy loads. If you supply your own socket object (via socketToUse argument), make sure you EITHER bind the local end point to this socket object in your own code (and pass a null reference as localEndPoint value) OR simply pass the local end point as localEndPoint value (not calling socket.Bind in your own code). Also, you can use no local end point at all. Just make sure you're not binding twice: directly in your code and via passing the local end point to this method.

Return Value

Type: Boolean
true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). Thus, this method can actually connect to the mail server on port 993 if you specified "imap.gmail.com" as serverName. To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.
Examples
This sample connects to the IMAP4 server using the specified local end point. This is useful if have multiple network adapters and wish to bind a particular connection to the specific adapter (you must know the IP address of this adapter).
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.Net;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com", 143, null, new IPEndPoint(IPAddress.Parse("192.168.0.123"), 3000));
imp.Disconnect();
' To use the code below, import these namespaces at the top of your code.
Imports System.Net
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com", 143, Nothing, New IPEndPoint(IPAddress.Parse("192.168.0.123"), 3000))
imp.Disconnect()
See Also

Reference

Imap Class
Connect Overload
MailBee.ImapMail Namespace


Imap.ConnectAsync Method

ImapConnectAsync Method
Overload List
 | Name | Description
Public method | ConnectAsync(String) | async/await version of Connect(String).
Public method | ConnectAsync(String, Int32) | async/await version of Connect(String, Int32).
Public method | ConnectAsync(String, Int32, Socket, EndPoint) | async/await version of Connect(String, Int32, Socket, EndPoint).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ConnectAsync Method (String)

ImapConnectAsync Method (String)
async/await version of Connect(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync(
    string serverName
)
Public Function ConnectAsync (
    serverName As String
) As Task(Of Boolean)

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
ConnectAsync Overload
MailBee.ImapMail Namespace


Imap.ConnectAsync Method (String, Int32)

ImapConnectAsync Method (String, Int32)
async/await version of Connect(String, Int32).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync(
    string serverName,
    int port
)
Public Function ConnectAsync (
    serverName As String,
    port As Integer
) As Task(Of Boolean)

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard IMAP4 port is 143. For TLS/SSL connections, dedicated port is 993 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
ConnectAsync Overload
MailBee.ImapMail Namespace


Imap.ConnectAsync Method (String, Int32, Socket, EndPoint)

ImapConnectAsync Method (String, Int32, Socket, EndPoint)
async/await version of Connect(String, Int32, Socket, EndPoint).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync(
    string serverName,
    int port,
    Socket socketToUse,
    EndPoint localEndPoint
)
Public Function ConnectAsync (
    serverName As String,
    port As Integer,
    socketToUse As Socket,
    localEndPoint As EndPoint
) As Task(Of Boolean)

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard IMAP4 port is 143. For TLS/SSL connections, dedicated port is 993 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).
socketToUse
Type: System.Net.SocketsSocket
Usually, a null reference (Nothing in Visual Basic). You can supply your own socket object here if you wish MailBee to use this object instead of creating a new one (typically, to fine-tune the WinSock subsystem when you need to deal with thousands of connections). This approach is now obsolete. Subscribe to SocketCreating event instead.
localEndPoint
Type: System.NetEndPoint
Usually, a null reference. Set it if you need to bind the connection to a certain local IP address/port to fine-tune the performance under heavy loads. If you supply your own socket object (via socketToUse argument), make sure you EITHER bind the local end point to this socket object in your own code (and pass a null reference as localEndPoint value) OR simply pass the local end point as localEndPoint value (not calling socket.Bind in your own code). Also, you can use no local end point at all. Just make sure you're not binding twice: directly in your code and via passing the local end point to this method.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
ConnectAsync Overload
MailBee.ImapMail Namespace


Imap.CopyMessages Method

ImapCopyMessages Method
Overload List
Name | Description
CopyMessages(String, Boolean, String) | Copies the specified messages from the currently selected folder to the specified folder.
CopyMessages(String, Boolean, String, UidPlusResult) | Copies the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the copied messages in the destination folder.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.CopyMessages Method (String, Boolean, String)

ImapCopyMessages Method (String, Boolean, String)
Copies the specified messages from the currently selected folder to the specified folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool CopyMessages(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName
)
Public Function CopyMessages (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.

Return Value

Type: Boolean
true if the messages were copied successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.
Examples

This sample copies all messages from the inbox folder to the Sent folder.

The sample assumes "Sent" folder had already been created in the past. To learn how to make sure the folder exists, see UploadMessage(MailMessage, String, String, DateTime) or UploadMessage(MailMessage, String, String, String) samples.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.company.com");
        imp.Login("jdoe@company.com", "secret");
        imp.SelectFolder("INBOX");

        // Copy all messages in Inbox into Sent.
        imp.CopyMessages(Imap.AllMessages, false, "Sent");

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.company.com")
        imp.Login("jdoe@company.com", "secret")
        imp.SelectFolder("INBOX")

        ' Copy all messages in Inbox into Sent.
        imp.CopyMessages(Imap.AllMessages, False, "Sent")

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
CopyMessages Overload
MailBee.ImapMail Namespace
ImapMoveMessages(String, Boolean, String, UidPlusResult)


Imap.CopyMessages Method (String, Boolean, String, UidPlusResult)

ImapCopyMessages Method (String, Boolean, String, UidPlusResult)
Copies the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the copied messages in the destination folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool CopyMessages(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName,
    UidPlusResult result
)
Public Function CopyMessages (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String,
    result As UidPlusResult
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the copy operation reported by UIDPLUS enabled server (the outcome includes the UIDs of the source messages being copied, the UIDs assigned to the copied messages in the destination folder, and the UIDVALIDITY of the destination folder), or a null reference (Nothing in Visual Basic) if the application does not need this information.

Return Value

Type: Boolean
true if the messages were copied successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

When result is specified and the server supports UIDPLUS extension, CopyMessages(String, Boolean, String, UidPlusResult) method will set the supplied UidPlusResult object properties as below:

Property | Value
IsValid | true
IsSupported | true
SrcUids | The UidCollection object containing the UIDs of the messages being copied.
SrcUidString | The string containing the message sequence of UIDs of the messages being copied.
DestUids | The UidCollection object containing the UIDs assigned to the copied messages in targetFolderName folder.
DestUidString | The string containing the message sequence of UIDs assigned to the copied messages in targetFolderName folder.
DestUidValidity | The UIDVALIDITY of the targetFolderName folder.
If UIDPLUS capability is not supported by the server, IsSupported will be set to false.

Examples
This sample copies last 3 messages from the inbox folder to the Sent folder (it's assumed the Sent folder already exists and the inbox contains at least 3 messages). The UIDs assigned to the copied messages in the destination folder are displayed if UIDPLUS capability is supported by the server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");
        imp.SelectFolder("INBOX");

        // Prepare the object that will receive copying results.
        UidPlusResult res = new UidPlusResult();

        string range = (imp.MessageCount - 2).ToString() + ":*";

        // Copy the messages into "Sent" and fill res with copying results.
        imp.CopyMessages(range, false, "Sent", res);

        if (res.IsSupported)
        {
            Console.WriteLine("UIDs assigned to the copied messages are " +
                res.DestUidString);
        }
        else
        {
            Console.WriteLine("Sorry, UIDPLUS is not supported by the server");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("jdoe@company.com", "secret")
        imp.SelectFolder("INBOX")

        ' Prepare the object that will receive copying results.
        Dim res As New UidPlusResult
        Dim range As String = (imp.MessageCount - 2).ToString() & ":*"

        ' Copy the messages into "Sent" and fill res with copying results.
        imp.CopyMessages(range, False, "Sent", res)

        If res.IsSupported Then
            Console.WriteLine("UIDs assigned to the copied messages are " & _
                res.DestUidString)
        Else
            Console.WriteLine("Sorry, UIDPLUS is not supported by the server")
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
CopyMessages Overload
MailBee.ImapMail Namespace
ImapMoveMessages(String, Boolean, String, UidPlusResult)


Imap.CopyMessagesAsync Method

ImapCopyMessagesAsync Method
Overload List
 | Name | Description
Public method | CopyMessagesAsync(String, Boolean, String) | async/await version of CopyMessages(String, Boolean, String).
Public method | CopyMessagesAsync(String, Boolean, String, UidPlusResult) | async/await version of CopyMessages(String, Boolean, String, UidPlusResult).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.CopyMessagesAsync Method (String, Boolean, String)

ImapCopyMessagesAsync Method (String, Boolean, String)
async/await version of CopyMessages(String, Boolean, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> CopyMessagesAsync(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName
)
Public Function CopyMessagesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
CopyMessagesAsync Overload
MailBee.ImapMail Namespace


Imap.CopyMessagesAsync Method (String, Boolean, String, UidPlusResult)

ImapCopyMessagesAsync Method (String, Boolean, String, UidPlusResult)
async/await version of CopyMessages(String, Boolean, String, UidPlusResult).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> CopyMessagesAsync(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName,
    UidPlusResult result
)
Public Function CopyMessagesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String,
    result As UidPlusResult
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the copy operation reported by UIDPLUS enabled server (the outcome includes the UIDs of the source messages being copied, the UIDs assigned to the copied messages in the destination folder, and the UIDVALIDITY of the destination folder), or a null reference (Nothing in Visual Basic) if the application does not need this information.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
CopyMessagesAsync Overload
MailBee.ImapMail Namespace


Imap.CreateFolder Method

ImapCreateFolder Method
Creates a new folder (mailbox in IMAP4 terms) in the IMAP4 account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool CreateFolder(
    string folderName
)
Public Function CreateFolder (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The full name of the folder to be created.

Return Value

Type: Boolean
true if the folder was created successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

The developer should specify the full name of the folder (including all parent folders' names if the new folder should be a subfolder of another existing folder). For instance, imap.CreateFolder("Orders") call will create "Orders" folder, not "Inbox/Orders" even if "Inbox" folder is currently selected.

This method automatically creates parent folders if required. For instance, if folderName is "Archive/April/29" and there is no "Archive" folder in the account, this method will create "Archive", "Archive/April", and "Archive/April/29" folders.

Note Note
Although the most popular delimiter char for separating folder levels is "/", some IMAP4 servers may use "\", ".", etc, or even do not support folder hierarchy at all (flat names). The developer can obtain the folder delimiter char adopted by the current server using DownloadFolders(Boolean, String, String) method.
Note Note
Depending on the mail server implementation, folder names other than "Inbox" may be case-sensitive ("Drafts", "DRAFTS", and "drafts" may designate different folder names).

MailBee fully supports international folder names encoded with UTF-7 Modified encoding.

To create a folder asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

Examples
This sample connects to the IMAP4 server, logs in the mail account, and creates Orders subfolder in Inbox. If the server does not support subfolders, "Inbox/Orders" folder is created.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class)
Imap imp = new Imap();

// Connect to the server and log in the account.
imp.Connect("imap4.company.com");
imp.Login("jdoe@company.com", "secret");

// Determine what delimiter char is on the server.
FolderCollection delim = imp.DownloadFolders(false, string.Empty, string.Empty);

string folderName = null;
if (delim.Count == 0)
{
    Console.WriteLine("Bad IMAP4 server");
}
else if (delim[0].Delimiter == null)
{
    folderName = "Inbox/Orders";
    Console.WriteLine("Folder names are flat. Will create " + folderName + " folder.");
}
else
{
    folderName = "Inbox" + delim[0].Delimiter + "Orders";
    Console.WriteLine("Will create " + folderName + " folder.");
}

// Create folder
imp.CreateFolder(folderName);
Console.WriteLine(folderName + " folder successfully created.");

imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class)
Dim imp As New Imap

' Connect to the server and log in the account.
imp.Connect("imap4.company.com")
imp.Login("jdoe@company.com", "secret")

' Determine what delimiter char is on the server.
Dim delim As FolderCollection = _
    imp.DownloadFolders(False, String.Empty, String.Empty)

Dim folderName As String

If delim.Count = 0 Then
    Console.WriteLine("Bad IMAP4 server")
ElseIf delim(0).Delimiter Is Nothing Then
    folderName = "Inbox/Orders"
    Console.WriteLine("Folder names are flat. Will create " & folderName & " folder.")
Else
    folderName = "Inbox" & delim(0).Delimiter & "Orders"
    Console.WriteLine("Will create " & folderName & " folder.")
End If

' Create folder
imp.CreateFolder(folderName)
Console.WriteLine(folderName & " folder successfully created.")

' Disconnect from the server.
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.CreateFolderAsync Method

ImapCreateFolderAsync Method
async/await version of CreateFolder(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> CreateFolderAsync(
    string folderName
)
Public Function CreateFolderAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The full name of the folder to be created.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DeleteFolder Method

ImapDeleteFolder Method
Deletes an existing folder (mailbox in IMAP4 terms) from the IMAP4 account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteFolder(
    string folderName
)
Public Function DeleteFolder (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The full name of the folder to be deleted.

Return Value

Type: Boolean
true if the folder was deleted successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

The developer should specify the full name of the folder (including all parent folders' names if the folder is a a subfolder of another existing folder). See CreateFolder(String) topic for details regarding folder names.

Note Note
If the folder contains subfolders, the mail server may not allow the client to delete it. It's permitted, however, to delete a folder which does not contain any subfolders but does contain some e-mail messages in it. The currently selected folder and Inbox folder cannot be deleted under any circumstances.

To delete a folder asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

Examples
This sample connects to the IMAP4 server, logs in the mail account, and removes all folders except Inbox, Sent, Drafts and their subfolders. If certain folders to be removed contain subfolders, these subfolders are removed first.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class)
Imap imp = new Imap();

// Connect to the server and log in the account.
imp.Connect("imap4.company.com");
imp.Login("jdoe@company.com", "secret");

FolderCollection folders = null;

// We may need to iterate through folders collection multiple
// times. For instance, if certain folder to be deleted contains
// subfolders, we should delete this subfolders first and then
// try again. However, using folders.Reverse() optimization
// reduces the number of iterations. Without Reverse, subfolders
// usually appear in the end of the list (thus, all parent folders
// which are in the beginning of the list could not be deleted during
// the first iteration). With Reverse, subfolders will come before
// their parent folders in the list. Thus, if we use Reverse and
// the mail server always returns parent folders before their
// subfolders, we'll delete all the folders in a single pass.
for (;;)
{
    bool deletedAnything = false;
    int processedCount = 0;

    // Get the list of folders in descending order (so that
    // subfolders come first). Alternatively, we could use
    // 'for' loop (instead of 'foreach') with descending
    // counter variable (i.e. i-- instead of i++).
    folders = imp.DownloadFolders();
    folders.Reverse();

    foreach (Folder imapFolder in folders)
    {
        if (!imapFolder.IsValid)
        {
            Console.WriteLine("IMAP4 folder list is corrupted");
            break;
        }
        else
        {
            string folderName = imapFolder.Name.ToLower();

            // Check folder names in case-insensitive manner...
            if (folderName == "inbox" ||
                folderName == "sent" ||
                folderName == "drafts")
            {
                processedCount++;
            }
            else
            {
                try
                {
                    // ...but pass original name when deleting.
                    imp.DeleteFolder(imapFolder.Name);

                    // Remember this deletion attempt succeeded.
                    processedCount++;
                    deletedAnything = true;
                }
                catch (MailBeeImapNegativeResponseException e)
                {
                    // If the server responded with "NO" response,
                    // it usually means the folder contains,
                    // sub-folders so we need to delete them first
                    // (i.e. that's normal situation). If, however,
                    // the response is BAD, this is the real problem,
                    // and we'll re-throw the exception in this case.
                    if (e.CompletionResult != "NO")
                    {
                        throw;
                    }
                }
            }
        }
    }

    if (processedCount == folders.Count || !deletedAnything)
    {
        // If we successfully processed all the folders or
        // no folders have been deleted during the last iteration,
        // it means we deleted everything we should or could.
        break;
    }
}

// Display the list of folders remained after performing clean-up.
folders = imp.DownloadFolders();
foreach (Folder imapFolder in folders)
{
    Console.WriteLine(imapFolder.Name);
}

imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class)
Dim imp As New Imap

' Connect to the server and log in the account.
imp.Connect("imap4.company.com")
imp.Login("jdoe@company.com", "secret")

Dim folders As FolderCollection = Nothing

' We may need to iterate through folders collection multiple
' times. For instance, if certain folder to be deleted contains
' subfolders, we should delete this subfolders first and then
' try again. However, using folders.Reverse() optimization
' reduces the number of iterations. Without Reverse, subfolders
' usually appear in the end of the list (thus, all parent folders
' which are in the beginning of the list could not be deleted during
' the first iteration). With Reverse, subfolders will come before
' their parent folders in the list. Thus, if we use Reverse and
' the mail server always returns parent folders before their
' subfolders, we'll delete all the folders in a single pass.

Do
    Dim deletedAnything As Boolean = False
    Dim processedCount As Integer = 0

    ' Get the list of folders in descending order (so that
    ' subfolders come first). Alternatively, we could use
    ' 'For' loop (instead of 'For Each') with descending
    ' counter variable (i.e. 'i -= 1' instead of 'i += 1').
    folders = imp.DownloadFolders()
    folders.Reverse()

    For Each imapFolder As Folder In folders
        If Not imapFolder.IsValid Then
            Console.WriteLine("IMAP4 folder list is corrupted")
            Exit Do
        Else
            Dim folderName As String = imapFolder.Name.ToLower()

            ' Check folder names in case-insensitive manner...
            If folderName = "inbox" OrElse folderName = "sent" OrElse _
                folderName = "drafts" Then

                processedCount += 1
            Else
                Try
                    ' ...but pass original name when deleting.
                    imp.DeleteFolder(imapFolder.Name)

                    ' Remember this deletion attempt succeeded.
                    processedCount += 1
                    deletedAnything = True

                Catch e As MailBeeImapNegativeResponseException
                    ' If the server responded with "NO" response,
                    ' it usually means the folder contains,
                    ' sub-folders so we need to delete them first
                    ' (i.e. that's normal situation). If, however,
                    ' the response is BAD, this is the real problem,
                    ' and we'll re-throw the exception in this case.
                    If e.CompletionResult <> "NO" Then
                        Throw
                    End If
                End Try
            End If
        End If
    Next

    If processedCount = folders.Count OrElse Not deletedAnything Then
        ' If we successfully processed all the folders or
        ' no folders have been deleted during the last iteration,
        ' it means we deleted everything we should or could.
        Exit Do
    End If
Loop While True

' Display the list of folders remained after performing clean-up.
folders = imp.DownloadFolders()
For Each imapFolder As Folder In folders
    Console.WriteLine(imapFolder.Name)
Next

imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DeleteFolderAsync Method

ImapDeleteFolderAsync Method
async/await version of DeleteFolder(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteFolderAsync(
    string folderName
)
Public Function DeleteFolderAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The full name of the folder to be deleted.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DeleteMessages Method

ImapDeleteMessages Method
Marks the specified messages in the currently selected folder as deleted.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteMessages(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DeleteMessages (
    messageIndexSet As String,
    indexIsUid As Boolean
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: Boolean
true if the messages have been marked as deleted successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

Note Note
This method just sets "\Deleted" flag for the specified messages. To purge deleted messages permanently, call Expunge(String, Boolean) method or explicitly unselect the folder using Close(Boolean) method.

To learn now to undelete messages marked as deleted, see the sample in SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction) topic.

Examples
This sample marks the first message and the messages #5, #6, and #7 in the inbox as deleted.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.server.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Mark messages as deleted.
        imp.DeleteMessages("1,5:7", false);

        // Uncomment the next line to purge deleted messages.
        // imp.Close();

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.server.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Mark messages as deleted.
        imp.DeleteMessages("1,5:7", False)

        ' Uncomment the next line to purge deleted messages.
        ' imp.Close()

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DeleteMessagesAsync Method

ImapDeleteMessagesAsync Method
async/await version of DeleteMessages(String, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteMessagesAsync(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DeleteMessagesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Disconnect Method

ImapDisconnect Method
Disconnects from the IMAP4 server and releases any used resources.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Disconnect()
Public Function Disconnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Unlike POP3, where all the messages marked as deleted are expunged when Disconnect method is called, the IMAP4 protocol requires the client to explicitly expunge messages marked as deleted using Close(Boolean) or Expunge(String, Boolean) method call.
Examples
This sample connects to the IMAP4 server and then disconnects.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DisconnectAsync Method

ImapDisconnectAsync Method
async/await version of Disconnect.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DisconnectAsync()
Public Function DisconnectAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Dispose Method

ImapDispose Method
Overload List
 | Name | Description
Public method | Dispose | Closes all opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Dispose Method

ImapDispose Method
Closes all opened network connections (if any) and releases any used system resources.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
Usually, the developer does not need to call this method. It's recommended to call Disconnect method to close the connections and free the resources.
See Also

Reference

Imap Class
Dispose Overload
MailBee.ImapMail Namespace


Imap.Dispose Method (Boolean)

ImapDispose Method (Boolean)
When overridden in a derived class, must release unmanaged and optionally managed resources used by the component.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Remarks
If the derived class does not use any additional resources, this method does not need to be overridden. If, however, it's overridden, the developer must also call Dispose method of the base class.
See Also

Reference

Imap Class
Dispose Overload
MailBee.ImapMail Namespace


Imap.DownloadEntireMessage Method

ImapDownloadEntireMessage Method
Completely downloads the specified message from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DownloadEntireMessage(
    long messageIndex,
    bool indexIsUid
)
Public Function DownloadEntireMessage (
    messageIndex As Long,
    indexIsUid As Boolean
) As MailMessage

Parameters

messageIndex
Type: SystemInt64
The ordinal position or UID of the message in the currently selected folder (for ordinal message numbers, can be negative, i.e. -1 denotes the last e-mail in the folder).
indexIsUid
Type: SystemBoolean
If true, messageIndex is treated as UID; otherwise, as ordinal message number.

Return Value

Type: MailMessage
On success, a MailMessage object containing the entire message, including the message header, all the body parts and attachments; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If more than one message is downloaded, it's recommended to use DownloadEntireMessages(String, Boolean) method when possible, since it is capable of downloading multiple messages in a batch.

To make messages SEEN upon downloading, change SetSeenForEntireMessages property value to true before calling this method.

For advanced purposes, use DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String). With IMAP envelopes, you can get extra flags, and more.

Examples
This sample downloads the first message from an inbox on an IMAP4 server, saves it as index.htm file, and also saves the embedded pictures and other linked objects, making it possible to open index.htm file in a browser and have the message being correctly displayed (including all the graphics, styles, etc).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.somehost.com");
        imp.Login("jdoe@somehost.com", "secret");
        imp.SelectFolder("INBOX");

        // Save message as C:\Temp\index.htm
        MailMessage msg = imp.DownloadEntireMessage(1, false);
        msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml;
        msg.SaveHtmlAndRelatedFiles(@"C:\Temp\index.htm");

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.somehost.com")
        imp.Login("jdoe@somehost.com", "secret")
        imp.SelectFolder("INBOX")

        ' Save message as C:\Temp\index.htm
        Dim msg As MailMessage = imp.DownloadEntireMessage(1, False)
        msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml
        msg.SaveHtmlAndRelatedFiles("C:\Temp\index.htm")

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDownloadEntireMessages(String, Boolean)
ImapDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)


Imap.DownloadEntireMessageAsync Method

ImapDownloadEntireMessageAsync Method
async/await version of DownloadEntireMessage(Int64, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessage> DownloadEntireMessageAsync(
    long messageIndex,
    bool indexIsUid
)
Public Function DownloadEntireMessageAsync (
    messageIndex As Long,
    indexIsUid As Boolean
) As Task(Of MailMessage)

Parameters

messageIndex
Type: SystemInt64
The ordinal position or UID of the message in the currently selected folder (for ordinal message numbers, can be negative, i.e. -1 denotes the last e-mail in the folder).
indexIsUid
Type: SystemBoolean
If true, messageIndex is treated as UID; otherwise, as ordinal message number.

Return Value

Type: Task MailMessage
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessage object containing the entire message, including the message header, all the body parts and attachments; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadEntireMessages Method

ImapDownloadEntireMessages Method
Completely downloads the specified messages from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadEntireMessages(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DownloadEntireMessages (
    messageIndexSet As String,
    indexIsUid As Boolean
) As MailMessageCollection

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

This method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.

To make messages SEEN upon downloading, change SetSeenForEntireMessages property value to true before calling this method.

Note Note
To track downloading messages, EnvelopeDownloaded event should be used. There is no MessageDownloaded event since mail messages are actually downloaded within envelopes. Once an envelope is downloaded, the mail message data is extracted from it. Generally speaking, DownloadEntireMessages(String, Boolean) is a kind of overload of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.

For advanced purposes, use DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String). With IMAP envelopes, you can get extra flags, and more.

Examples
This console sample completely downloads the last 10 messages from the inbox, and displays the number of attachments for each downloaded message. EnvelopeDownloaded event is used to track the download progress.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // EnvelopeDownloaded event handler.
    private static void OnEnvelopeDownloaded(object sender,
        ImapEnvelopeDownloadedEventArgs e)
    {
        Console.WriteLine("Message #" + e.MessageNumber + " downloaded");
    }

    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Subscribe to the EnvelopeDownloaded event.
        imp.EnvelopeDownloaded +=
            new ImapEnvelopeDownloadedEventHandler(OnEnvelopeDownloaded);

        // Download the last 10 messages. Note: this sample does not check
        // if there are less than 10 messages in the inbox. See sample code
        // in DownloadEnvelopes(string, bool) overload for more information.
        MailMessageCollection msgs = imp.DownloadEntireMessages(
            (imp.MessageCount - 9).ToString() + ":*", false);

        // Display some information about downloaded messages.
        foreach (MailMessage msg in msgs)
        {
            Console.WriteLine("Message #" + msg.IndexOnServer +
                " contains " + msg.Attachments.Count + " attachment(s)");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    ' EnvelopeDownloaded event handler.
    Private Sub OnEnvelopeDownloaded(ByVal sender As Object, _
        ByVal e As ImapEnvelopeDownloadedEventArgs)

        Console.WriteLine("Message #" & e.MessageNumber & " downloaded")
    End Sub

    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Subscribe to the EnvelopeDownloaded event.
        AddHandler imp.EnvelopeDownloaded, AddressOf OnEnvelopeDownloaded

        ' Download the last 10 messages. Note: this sample does not check
        ' if there are less than 10 messages in the inbox. See sample code
        ' in DownloadEnvelopes(string, bool) overload for more information.
        Dim msgs As MailMessageCollection = _
            imp.DownloadEntireMessages((imp.MessageCount - 9).ToString() & ":*", False)

        ' Display some information about downloaded messages.
        For Each msg As MailMessage In msgs
            Console.WriteLine("Message #" & msg.IndexOnServer & " contains " & _
                 msg.Attachments.Count & " attachment(s)")
        Next

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadEntireMessagesAsync Method

ImapDownloadEntireMessagesAsync Method
async/await version of DownloadEntireMessages(String, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadEntireMessagesAsync(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DownloadEntireMessagesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean
) As Task(Of MailMessageCollection)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: Task MailMessageCollection
On success, the value of TResult parameter is a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadEnvelopes Method

ImapDownloadEnvelopes Method
Overload List
Name | Description
DownloadEnvelopes(String, Boolean) | Fetches message envelopes from the server.
DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32) | Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.
DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) | Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadEnvelopes Method (String, Boolean)

ImapDownloadEnvelopes Method (String, Boolean)
Fetches message envelopes from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection DownloadEnvelopes(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DownloadEnvelopes (
    messageIndexSet As String,
    indexIsUid As Boolean
) As EnvelopeCollection

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: EnvelopeCollection
EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Ordinal message numbers and UIDs are one-based (minimum value is 1, not 0). However, the returned EnvelopeCollection is zero-based. The developer can use MessageNumber or Uid properties to obtain ordinal message numbers and UIDs of the downloaded envelopes.

To specify multiple message numbers or UIDs in messageIndexSet, delimit them with comma (,) or use ranges (such as "5:10" which means "download messages in the range from message #5 to the message #10"). Wildcard character (*), can be used to specify range which spans till the last message in the folder. In particular, "1:*" means "download all messages in the folder". "1:*" is also declared as AllMessages constant.

Examples of valid message sequences: "1", "1:*", "1,2", "1:2", "5:10,12:45,99,101,105,141:*".

Note Note
A message sequence string may NOT contain whitespaces. The following is INCORRECT: "1, 2, 5". The correct one is: "1,2,5".

When using a range of UIDs (indexIsUid is true), it's important to understand the number of returned messages may be LESS than the length of the range (or even zero). This is because UIDs are not continuous. For instance, if the folder contains messages with UIDs 4, 5, 6, 10, and 22, the "1,2,8:20" sequence of UIDs corresponds to a single message with UID=10.

This method fetches the following items from the IMAP server: UID, FLAGS, INTERNALDATE, RFC822SIZE, ENVELOPE. To get additional information about messages (for instance, a body structure, non-standard header fields, attachments, a message header section, etc), the developer should use other overloads of this method.

Note Note
Due to complexity of IMAP4 responses, some servers may return badly formed FETCH responses under certain circumstances. If MailBee detects this, it raises ErrorOccurred event and sets IsValid to false. Since this is done on per-envelope basis, some Envelope objects in the returned collection may have IsValid set to false while others - to true. Anyway, the component does not throw exception when it encounters invalid envelope. This allows the application to skip invalid response and successfully receive subsequent messages.
Examples
For each message in the Inbox, this sample downloads and displays the envelope information: From, Reply-To, To, CC, Subject, the date when the message was originally composed, and the date when the message was received by the server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("imap.server.com");

        imp.Login("jdoe@server.com", "secret");

        // Select Inbox folder.
        imp.SelectFolder("INBOX");

        // Download envelopes for last 10 messages in the inbox. If there are
        // less than 10 messages, we'll get envelopes for all of them. In this
        // sample, we define higher boundary of the range as imp.MessageCount
        // but we could also use "*" character for that.
        int start = imp.MessageCount - 9;
        if (start < 1)
        {
            start = 1;
        }
        EnvelopeCollection envs = imp.DownloadEnvelopes(
            start.ToString() + ":" + imp.MessageCount.ToString(), false);

        foreach (Envelope env in envs)
        {
            Console.WriteLine("Message #" + env.MessageNumber + " info:");
            if (env.IsValid)
            {
                Console.WriteLine("From: " + env.From.ToString());
                Console.WriteLine("Reply-To: " + env.ReplyTo.ToString());
                Console.WriteLine("To: " + env.To.ToString());
                Console.WriteLine("CC: " + env.Cc.ToString());
                Console.WriteLine("Subject: " + env.Subject);

                // Check if the message does not have Date: header set.
                if (env.Date == DateTime.MinValue)
                {
                    Console.WriteLine("Composed at: " + env.Date);
                }
                else
                {
                    Console.WriteLine("Composed at: N/A");
                }

                Console.WriteLine("Received at: " + env.DateReceived);
            }
            else
            {
                Console.WriteLine("FETCH response contains some invalid data.");
            }
            Console.WriteLine("==============================================");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        imp.Connect("imap.server.com")

        imp.Login("jdoe@server.com", "secret")

        ' Select Inbox folder.
        imp.SelectFolder("INBOX")

        ' Download envelopes for last 10 messages in the inbox. If there are
        ' less than 10 messages, we'll get envelopes for all of them. In this
        ' sample, we define higher boundary of the range as imp.MessageCount
        ' but we could also use "*" character for that.
        Dim start As Integer = imp.MessageCount - 9
        If start < 1 Then
            start = 1
        End If

        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(start.ToString() & _
            ":" & imp.MessageCount.ToString(), False)

        For Each env As Envelope In envs
            Console.WriteLine("Message #" & env.MessageNumber & " info:")
            If env.IsValid Then
                Console.WriteLine("From: " & env.From.ToString())
                Console.WriteLine("Reply-To: " & env.ReplyTo.ToString())
                Console.WriteLine("To: " & env.To.ToString())
                Console.WriteLine("CC: " & env.Cc.ToString())
                Console.WriteLine("Subject: " & env.Subject)

                ' Check if the message does not have Date: header set.
                If env.Date = DateTime.MinValue Then
                    Console.WriteLine("Composed at: " & env.Date)
                Else
                    Console.WriteLine("Composed at: N/A")
                End If

                Console.WriteLine("Received at: " & env.DateReceived)
            Else
                Console.WriteLine("FETCH response contains some invalid data.")
            End If
            Console.WriteLine("==============================================")
        Next

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End module
See Also

Reference

Imap Class
DownloadEnvelopes Overload
MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope


Imap.DownloadEnvelopes Method (String, Boolean, EnvelopeParts, Int32)

ImapDownloadEnvelopes Method (String, Boolean, EnvelopeParts, Int32)
Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection DownloadEnvelopes(
    string messageIndexSet,
    bool indexIsUid,
    EnvelopeParts parts,
    int bodyPreviewSize
)
Public Function DownloadEnvelopes (
    messageIndexSet As String,
    indexIsUid As Boolean,
    parts As EnvelopeParts,
    bodyPreviewSize As Integer
) As EnvelopeCollection

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
Specifies which message elements or attributes to download.
bodyPreviewSize
Type: SystemInt32
If parts includes MessagePreview flag, specifies the length of the message body section (in bytes) to be downloaded in addition to the message header section; if 0, only the message header is downloaded; if -1 or -2, the entire message is downloaded. -1 is the only option which also sets Seen flag marking the message as read.

Return Value

Type: EnvelopeCollection
EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Ordinal message numbers and UIDs are one-based (minimum value is 1, not 0). However, the returned EnvelopeCollection is zero-based. The developer can use MessageNumber or Uid properties to obtain ordinal message numbers and UIDs of the downloaded envelopes.

To specify multiple message numbers or UIDs in messageIndexSet, delimit them with comma (,) or use ranges (such as "5:10" which means "download messages in the range from message #5 to the message #10"). Wildcard character (*), can be used to specify range which spans till the last message in the folder. In particular, "1:*" means "download all messages in the folder". "1:*" is also declared as AllMessages constant.

Examples of valid message sequences: "1", "1:*", "1,2", "1:2", "5:10,12:45,99,101,105,141:*".

Note Note
A message sequence string may NOT contain whitespaces. The following is INCORRECT: "1, 2, 5". The correct one is: "1,2,5".

When using a range of UIDs (indexIsUid is true), it's important to understand the number of returned messages may be LESS than the length of the range (or even zero). This is because UIDs are not continuous. For instance, if the folder contains messages with UIDs 4, 5, 6, 10, and 22, the "1,2,8:20" sequence of UIDs corresponds to a single message with UID=10.

parts parameters can be used to specify which message elements to download. This allows the developer to request only required information from the server and thus reduce network traffic by not downloading unnecessary data.

Note Note
If certain message element, attribute, or group of elements/attributes is not requested from the server, the developer should not attempt to read the corresponding properties of Envelope objects within the returned collection. For instance, if parts didn't contain Envelope (or MailBeeEnvelope, which is a superset of Envelope), From, To, Subject, and some other properties will not return useful information. See remarks in EnvelopeParts topic for more information on dependencies between downloaded parts of FETCH response and related properties of Envelope object.

bodyPreviewSize parameter makes sense only when parts includes MessagePreview flag. When bodyPreviewSize is 0, the component will download only header section of each message (accessible via MessagePreview property). If bodyPreviewSize is larger than 0, the component will download the header and the specified count of bytes of the body. If bodyPreviewSize is -1 or -2, the entire message is returned (-2 will keep UNSEEN status). Methods like DownloadEntireMessage(Int64, Boolean) or DownloadMessageHeaders(String, Boolean) simply call DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) inside and then return MessagePreview values.

Note Note
Due to complexity of IMAP4 responses, some servers may return badly formed FETCH responses under certain circumstances. If MailBee detects this, it raises ErrorOccurred event and sets IsValid to false. Since this is done on per-envelope basis, some Envelope objects in the returned collection may have IsValid set to false while others - to true. Anyway, the component does not throw exception when it encounters invalid envelope. This allows the application to skip invalid response and successfully receive subsequent messages.
Examples
For each message in the Inbox, this sample downloads the message preview (the message header section + first 1000 bytes of the body), the body structure (to correctly determine if the message has attachments), and the date of receiving the message by the server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("mail.company.com");

        imp.Login("jdoe", "secret");

        // Select Inbox folder.
        imp.SelectFolder("Inbox");

        // Download body structure (header + 1000 bytes of the body), message preview,
        // and the date assigned to the message by the server (usually, it's the date
        // when the message was received by the server).
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, false,
            EnvelopeParts.BodyStructure | EnvelopeParts.MessagePreview | EnvelopeParts.InternalDate,
            1000);

        foreach (Envelope env in envs)
        {
            Console.WriteLine("Message #" + env.MessageNumber + " info:");
            if (env.IsValid)
            {
                // Tell MailBee to create plain-text version of HTML message
                // if plain-text version is not available in the message.
                // It's important to set this before the message gets parsed
                // (which occurs automatically when any element of the message
                // is accessed though MailMessage object properties or methods).
                // If you change HtmlToPlainMode after the message has already been parsed,
                // call MailMessage.Parser.Apply to reparse the message with new settings.
                env.MessagePreview.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;

                Console.WriteLine("From: " + env.MessagePreview.From.ToString());
                Console.WriteLine("To: " + env.MessagePreview.To.ToString());
                Console.WriteLine("Subject: " + env.MessagePreview.Subject);
                Console.WriteLine("Composed at: " + env.MessagePreview.Date);

                // We use DateReceived from INTERNALDATE item of FETCH response.
                // We could have also used env.MessagePreview.DateReceived instead
                // (it's obtained from "Received:" headers of the message).
                // However, env.MessagePreview.DateReceived is DateTime.MinValue
                // when the message does not contain "Received:" headers.
                // INTERNALDATE, on other hand, is always available in IMAP4.
                // MailMessage.DateReceived still makes sense because INTERNALDATE
                // is not available in POP3, and examining "Received:" headers is
                // the only way of getting this info when using POP3 protocol.
                Console.WriteLine("Received at: " + env.DateReceived);

                if (env.MessagePreview.Priority >= MailPriority.High)
                {
                    Console.WriteLine("The message is high priority");
                }

                // Determine if the message has attachments.
                bool hasAttachments = false;
                ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
                foreach (ImapBodyStructure part in parts)
                {
                    // Detect if this part is attachment.
                    if ((part.Disposition != null && part.Disposition.ToLower() == "attachment") ||
                        (part.Filename != null && part.Filename != string.Empty) ||
                        (part.ContentType != null && part.ContentType.ToLower() == "message/rfc822"))
                    {
                        hasAttachments = true;
                        break;
                    }
                }
                if (hasAttachments)
                {
                    Console.WriteLine("The message has attachments.");
                }

                // Display first 250 characters of the text body. Note that we requested
                // 1000 bytes but now display only 250 characters. We request more than
                // we display because of:
                // - body section of MIME message may start with a block of additional
                // information which is not a part of text body. Usually, the length
                // of this block is 100-300 bytes.
                // - non-ASCII characters may occupy more than one byte.
                // In some cases, reading 1000 bytes may still be not enough to reach the
                // text body (for instance, if the message contains attachment which preceeds
                // the text body in the message source). In such rare cases, the body preview
                // will not be available (or, the developer may request more than 1000 bytes
                // of the body and thus increase network traffic).
                string bodyPreview = env.MessagePreview.BodyPlainText;
                if (bodyPreview.Length > 250)
                {
                    bodyPreview = bodyPreview.Substring(0, 250);
                }
                Console.WriteLine();
                Console.WriteLine(bodyPreview);
            }
            else
            {
                Console.WriteLine("FETCH response contains some invalid data.");
            }
            Console.WriteLine("============================================================");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        imp.Connect("mail.company.com")

        imp.Login("jdoe", "secret")

        ' Select Inbox folder.
        imp.SelectFolder("Inbox")

        ' Download body structure (header + 1000 bytes of the body), message preview,
        ' and the date assigned to the message by the server (usually, it's the date
        ' when the message was received by the server).
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(Imap.AllMessages, False, _
            EnvelopeParts.BodyStructure Or EnvelopeParts.MessagePreview Or EnvelopeParts.InternalDate, 1000)

        For Each env As Envelope In envs
            Console.WriteLine("Message #" & env.MessageNumber & " info:")
            If env.IsValid Then
                ' Tell MailBee to create plain-text version of HTML message
                ' if plain-text version is not available in the message.
                ' It's important to set this before the message gets parsed
                ' (which occurs automatically when any element of the message
                ' is accessed though MailMessage object properties or methods).
                ' If you change HtmlToPlainMode after the message has already been parsed,
                ' call MailMessage.Parser.Apply to re-parse the message with new settings.
                env.MessagePreview.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain

                Console.WriteLine("From: " & env.MessagePreview.From.ToString())
                Console.WriteLine("To: " & env.MessagePreview.To.ToString())
                Console.WriteLine("Subject: " & env.MessagePreview.Subject)
                Console.WriteLine("Composed at: " & env.MessagePreview.Date)

                ' We use DateReceived from INTERNALDATE item of FETCH response.
                ' We could have also used env.MessagePreview.DateReceived instead
                ' (it's obtained from "Received:" headers of the message).
                ' However, env.MessagePreview.DateReceived is DateTime.MinValue
                ' when the message does not contain "Received:" headers.
                ' INTERNALDATE, on other hand, is always available in IMAP4.
                ' MailMessage.DateReceived still makes sense because INTERNALDATE
                ' is not available in POP3, and examining "Received:" headers is
                ' the only way of getting this info when using POP3 protocol.
                Console.WriteLine("Received at: " & env.DateReceived)

                If env.MessagePreview.Priority >= MailPriority.High Then
                    Console.WriteLine("The message is high priority")
                End If

                ' Determine if the message has attachments.
                Dim hasAttachments As Boolean = False
                Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()
                For Each part As ImapBodyStructure In parts
                    ' Detect if this part is attachment.
                    If (Not part.Disposition Is Nothing AndAlso part.Disposition.ToLower() = "attachment") OrElse _
                        (Not part.Filename Is Nothing AndAlso part.Filename <> String.Empty) OrElse _
                        (Not part.ContentType Is Nothing AndAlso part.ContentType.ToLower() = "message/rfc822") Then

                        hasAttachments = True
                        Exit For
                    End If
                Next
                If hasAttachments Then
                    Console.WriteLine("The message has attachments.")
                End If

                ' Display first 250 characters of the text body. Note that we requested
                ' 1000 bytes but now display only 250 characters. We request more than
                ' we display because of:
                ' - body section of MIME message may start with a block of additional
                ' information which is not a part of text body. Usually, the length
                ' of this block is 100-300 bytes.
                ' - non-ASCII characters may occupy more than one byte.
                ' In some cases, reading 1000 bytes may still be not enough to reach the
                ' text body (for instance, if the message contains attachment which preceeds
                ' the text body in the message source). In such rare cases, the body preview
                ' will not be available (or, the developer may request more than 1000 bytes
                ' of the body and thus increase network traffic).
                Dim bodyPreview As String = env.MessagePreview.BodyPlainText
                If bodyPreview.Length > 250 Then
                    bodyPreview = bodyPreview.Substring(0, 250)
                End If
                Console.WriteLine()
                Console.WriteLine(bodyPreview)
            Else
                Console.WriteLine("FETCH response contains some invalid data.")
            End If

            Console.WriteLine("============================================================")
        Next

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
DownloadEnvelopes Overload
MailBee.ImapMail Namespace
MailBee.ImapMailEnvelope
MailBee.ImapMailImapBodyStructure


Imap.DownloadEnvelopes Method (String, Boolean, EnvelopeParts, Int32, String[], String[])

ImapDownloadEnvelopes Method (String, Boolean, EnvelopeParts, Int32, String, String)
Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection DownloadEnvelopes(
    string messageIndexSet,
    bool indexIsUid,
    EnvelopeParts parts,
    int bodyPreviewSize,
    string[] extraHeaders,
    string[] extraItems
)
Public Function DownloadEnvelopes (
    messageIndexSet As String,
    indexIsUid As Boolean,
    parts As EnvelopeParts,
    bodyPreviewSize As Integer,
    extraHeaders As String(),
    extraItems As String()
) As EnvelopeCollection

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
Specifies which message elements or attributes to download.
bodyPreviewSize
Type: SystemInt32
If parts includes MessagePreview flag, specifies the length of the message body section (in bytes) to be downloaded in addition to the message header section; if 0, only the message header is downloaded; if -1 or -2, the entire message is downloaded. -1 is the only option which also sets Seen flag marking the message as read.
extraHeaders
Type: SystemString
The array of names of message headers to be downloaded, or a null reference (Nothing in Visual Basic) if additional headers are not needed.
extraItems
Type: SystemString
The array of additional FETCH request items to download, or a null reference (Nothing in Visual Basic) if additional FETCH items are not needed.

Return Value

Type: EnvelopeCollection
EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Ordinal message numbers and UIDs are one-based (minimum value is 1, not 0). However, the returned EnvelopeCollection is zero-based. The developer can use MessageNumber or Uid properties to obtain ordinal message numbers and UIDs of the downloaded envelopes.

To specify multiple message numbers or UIDs in messageIndexSet, delimit them with comma (,) or use ranges (such as "5:10" which means "download messages in the range from message #5 to the message #10"). Wildcard character (*), can be used to specify range which spans till the last message in the folder. In particular, "1:*" means "download all messages in the folder". "1:*" is also declared as AllMessages constant.

Examples of valid message sequences: "1", "1:*", "1,2", "1:2", "5:10,12:45,99,101,105,141:*".

Note Note
A message sequence string may NOT contain whitespaces. The following is INCORRECT: "1, 2, 5". The correct one is: "1,2,5".

When using a range of UIDs (indexIsUid is true), it's important to understand the number of returned messages may be LESS than the length of the range (or even zero). This is because UIDs are not continuous. For instance, if the folder contains messages with UIDs 4, 5, 6, 10, and 22, the "1,2,8:20" sequence of UIDs corresponds to a single message with UID=10.

parts parameters can be used to specify which message elements to download. This allows the developer to request only required information from the server and thus reduce network traffic by not downloading unnecessary data.

Note Note
If certain message element, attribute, or group of elements/attributes is not requested from the server, the developer should not attempt to read the corresponding properties of Envelope objects within the returned collection. For instance, if parts didn't contain Envelope (or MailBeeEnvelope, which is a superset of Envelope), From, To, Subject, and some other properties will not return useful information. See remarks in EnvelopeParts topic for more information on dependencies between downloaded parts of FETCH response and related properties of Envelope object.

bodyPreviewSize parameter makes sense only when parts includes MessagePreview flag. When bodyPreviewSize is 0, the component will download only header section of each message (accessible via MessagePreview property). If bodyPreviewSize is larger than 0, the component will download the header and the specified count of bytes of the body. If bodyPreviewSize is -1 or -2, the entire message is returned (-2 will keep UNSEEN status). Methods like DownloadEntireMessage(Int64, Boolean) or DownloadMessageHeaders(String, Boolean) simply call DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) inside and then return MessagePreview values.

extraHeaders can be used to request certain additional header fields which are not included into ENVELOPE item of FETCH response and thus not present in Envelope object properties. Alternatively, the developer may request downloading the message header by setting MessagePreview flag in parts. Thus, all header fields would be downloaded. However, if the developer wants to reduce traffic and do not download entire header sections of messages, extraHeaders should be used to retrieve specific header fields. The typical usage of extraHeaders is getting "Importance" or "X-Priority" headers.

Values specified in extraItems are passed to the IMAP4 server without alteration. Using extraItems, the developer can request any valid FETCH item from the server (for instance, the developer may request downloading the contents of certain attachment or text body part of the message via its PartID). The downloaded items can than be obtained via GetEnvelopeItem(String, Boolean) method call.

When using extraItems, it's important to remember that item names in FETCH request can be different from their counterparts in the corresponding FETCH response. E.g. if requested item name is "BODY.PEEK[3.HEADER]<0.100>", the server will return "BODY[3.HEADER]<0>" name in the response. The developer may refer to the IMAP4 protocol specification (RFC3501) for more information regarding FETCH requests and responses.

Note Note
Due to complexity of IMAP4 responses, some servers may return badly formed FETCH responses under certain circumstances. If MailBee detects this, it raises ErrorOccurred event and sets IsValid to false. Since this is done on per-envelope basis, some Envelope objects in the returned collection may have IsValid set to false while others - to true. Anyway, the component does not throw exception when it encounters invalid envelope. This allows the application to skip invalid response and successfully receive subsequent messages.
Examples

This sample downloads "X-Priority" and "X-MS-Mail-Priority" header fields for all messages in Inbox, then finds out which messages have High priority, and downloads body structures for these messages. From the body structures, the sample code obtains which messages have attachments. Then, these messages are completely downloaded, and all attachments are saved into "C:\Temp" folder.

The sample performs search of high priority messages via downloading headers just to highlight how to download custom headers. In real world, it's more effective to use Search(Boolean, String, String) method for this. The sample allows the developer to change code path to using Search(Boolean, String, String) via setting searchViaEnvelopes variable value to false.

The sample also keeps track of invalid IMAP responses in ErrorOccurred event handler.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        if (e.Reason is MailBeeImapInvalidEnvelopeException)
        {
            MailBeeImapInvalidEnvelopeException invEnvEx =
                (MailBeeImapInvalidEnvelopeException)e.Reason;

            Console.WriteLine("Fetched data for message #" +
                invEnvEx.InvalidEnvelope.MessageNumber +
                " could not be completed parsed and will be ignored");
        }
    }

    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("imap.somehost.com");

        imp.Login("jdoe@somehost.com", "secret");

        // Select Inbox folder.
        imp.SelectFolder("INBOX");

        // Subscribe to ErrorOccurred event to track invalid envelopes.
        // We could also subscribe before calling Login or Connect since
        // we check the type of occurred error in OnErrorOccurred handler.
        imp.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        EnvelopeCollection envs = null;

        // We'll collect UID of high priority messages in this collection.
        UidCollection uids = new UidCollection();

        // If true, we'll search high priority messages using DownloadEnvelopes().
        // Otherwise, we'll use Search() method (much more effective). Thus, this
        // sample highlights both approaches.
        bool searchViaEnvelopes = true;

        // Download "X-Priority" and "X-MS-Mail-Priority" headers for each message.
        // We could have used Search() instead (just set searchViaEnvelopes=false).
        // Using Search() would be more effective. Imap.DownloadEnvelopes is used
        // here only to demonstrate how to get custom header fields from the server.
        if (searchViaEnvelopes)
        {
            envs = imp.DownloadEnvelopes(Imap.AllMessages, false,
                EnvelopeParts.Uid, 0, new string[] {"X-Priority", "X-MS-Mail-Priority"}, null);

            // For each message, determine if it's high priority.
            foreach (Envelope env in envs)
            {
                bool highPriority = false;

                if (env.IsValid)
                {
                    string priority = env.ExtraHeaders["X-Priority"];
                    if (priority != null && priority.Length > 0)
                    {
                        if (priority[0] == '1' || priority[0] == '2')
                        {
                            // X-Priority is High or Highest
                            highPriority = true;
                        }
                    }
                    else
                    {
                        priority = env.ExtraHeaders["X-MS-Mail-Priority"];
                        if (priority != null && string.Compare(priority, "High", true) == 0)
                        {
                            // X-MS-Mail-Priority is High
                            highPriority = true;
                        }
                    }
                }

                if (highPriority)
                {
                    uids.Add(env.Uid);
                }
            }
        }
        else
        {
            // To search for High-Priority messages in the most effective way, set
            // searchViaEnvelopes=false in the beginning of this sample. Search() method
            // performs the same job as the code block above but produces much less
            // traffic and consumes less resources.
            uids = (UidCollection)imp.Search(true,"OR OR HEADER \"X-Priority\" \"1\" " +
                "HEADER \"X-Priority\" \"2\" HEADER \"X-MS-Mail-Priority\" \"High\"", null);
        }

        if (uids.Count > 0)
        {
            // Download envelope structures of high priority messages.
            envs = imp.DownloadEnvelopes(uids.ToString(), true,
                EnvelopeParts.BodyStructure, 0, null, null);

            // We'll collect UID of high priority messages with attachments in this collection.
            uids = new UidCollection();

            // For each message, determine if it has attachments.
            foreach (Envelope env in envs)
            {
                if (env.IsValid)
                {
                    ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
                    foreach (ImapBodyStructure part in parts)
                    {
                        // Detect if this part is attachment.
                        if ((part.Disposition != null &&
                            part.Disposition.ToLower() == "attachment") ||
                            (part.Filename != null &&
                            part.Filename != string.Empty) ||
                            (part.ContentType != null &&
                            part.ContentType.ToLower() == "message/rfc822"))
                        {
                            uids.Add(env.Uid);
                            break;
                        }
                    }
                }
            }

            if (uids.Count > 0)
            {
                // We could also call DownloadEntireMessages here. Internally,
                // DownloadEntireMessages would call DownloadEnvelopes with the same
                // parameters and returned MailMessageCollection where each MailMessage
                // would be taken from Envelope.MessagePreview.
                envs = imp.DownloadEnvelopes(uids.ToString(), true,
                    EnvelopeParts.MessagePreview, -1, null, null);

                foreach (Envelope env in envs)
                {
                    if (env.IsValid)
                    {
                        // Save all attachments. Note: if the folder already contains
                        // attachment with the given name, MailBee will generate unique name
                        // (e.g. pic.gif will be saved as pic[1].gif if pic.gif already exists
                        // in the target folder.
                        env.MessagePreview.Attachments.SaveAll(@"C:\Temp");
                    }
                }
            }
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' ErrorOccurred event handler.
    Private Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        If (e.Reason Is GetType(MailBeeImapInvalidEnvelopeException)) Then
            Dim invEnvEx As MailBeeImapInvalidEnvelopeException = _
                CType(e.Reason, MailBeeImapInvalidEnvelopeException)

            Console.WriteLine("Fetched data for message #" & invEnvEx.InvalidEnvelope.MessageNumber & _
                 " could not be completed parsed and will be ignored")
        End If
    End Sub

    Sub Main(ByVal args As String())
        Dim imp As New Imap

        imp.Connect("imap.somehost.com")

        imp.Login("jdoe@somehost.com", "secret")

        ' Select Inbox folder.
        imp.SelectFolder("INBOX")

        ' Subscribe to ErrorOccurred event to track invalid envelopes.
        ' We could also subscribe before calling Login or Connect since
        ' we check the type of occurred error in OnErrorOccurred handler.
        AddHandler imp.ErrorOccurred, AddressOf OnErrorOccurred

        Dim envs As EnvelopeCollection = Nothing

        ' We'll collect UID of high priority messages in this collection.
        Dim uids As New UidCollection

        ' If true, we'll search high priority messages using DownloadEnvelopes().
        ' Otherwise, we'll use Search() method (much more effective). Thus, this
        ' sample highlights both approaches.
        Dim searchViaEnvelopes As Boolean = True

        ' Download "X-Priority" and "X-MS-Mail-Priority" headers for each message.
        ' We could have used Search() instead (just set searchViaEnvelopes=false).
        ' Using Search() would be more effective. Imap.DownloadEnvelopes is used
        ' here only to demonstrate how to get custom header fields from the server.
        If searchViaEnvelopes Then
            Dim arr As String() = {"X-Priority", "X-MS-Mail-Priority"}
            envs = imp.DownloadEnvelopes(Imap.AllMessages, False, EnvelopeParts.Uid, 0, arr, Nothing)

            ' For each message, determine if it's high priority.
            For Each env As Envelope In envs
                Dim highPriority As Boolean = False

                If env.IsValid Then
                    Dim priority As String = env.ExtraHeaders("X-Priority")
                    If Not priority Is Nothing AndAlso priority.Length > 0 Then
                        If Left(priority, 1) = "1" OrElse Left(priority, 1) = "2" Then
                            ' X-Priority is High or Highest
                            highPriority = True
                        End If
                    Else
                        priority = env.ExtraHeaders("X-MS-Mail-Priority")
                        If Not priority Is Nothing AndAlso String.Compare(priority, "High", True) = 0 Then
                            ' X-MS-Mail-Priority is High
                            highPriority = True
                        End If
                    End If
                End If

                If highPriority Then
                    uids.Add(env.Uid)
                End If
            Next
        Else
            ' To search for High-Priority messages in the most effective way, set
            ' searchViaEnvelopes=false in the beginning of this sample. Search() method
            ' performs the same job as the code block above but produces much less
            ' traffic and consumes less resources.
            uids = imp.Search(True, "OR OR HEADER ""X-Priority"" ""1"" " & _
                "HEADER ""X-Priority"" ""2"" HEADER ""X-MS-Mail-Priority"" ""High""", Nothing)

            If uids.Count > 0 Then
                ' Download envelope structures of high priority messages.
                envs = imp.DownloadEnvelopes(uids.ToString(), True, EnvelopeParts.BodyStructure, _
                    0, Nothing, Nothing)

                ' We'll collect UID of high priority messages with attachments in this collection.
                uids = New UidCollection

                ' For each message, determine if it has attachments.
                For Each env As Envelope In envs
                    If env.IsValid Then
                        Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()
                        For Each part As ImapBodyStructure In parts
                            ' Detect if this part is attachment.
                            If (Not part.Disposition Is Nothing AndAlso _
                                part.Disposition.ToLower() = "attachment") OrElse _
                                (Not part.Filename Is Nothing AndAlso _
                                part.Filename <> String.Empty) OrElse _
                                (Not part.ContentType Is Nothing AndAlso _
                                part.ContentType.ToLower() = "message/rfc822") Then

                                uids.Add(env.Uid)
                                Exit For
                            End If
                        Next
                    End If
                Next

                If uids.Count > 0 Then
                    ' We could also call DownloadEntireMessages here. Internally,
                    ' DownloadEntireMessages would call DownloadEnvelopes with the same
                    ' parameters and returned MailMessageCollection where each MailMessage
                    ' would be taken from Envelope.MessagePreview.
                    envs = imp.DownloadEnvelopes(uids.ToString(), True, EnvelopeParts.MessagePreview, _
                            -1, Nothing, Nothing)

                    For Each env As Envelope In envs
                        If env.IsValid Then
                            ' Save all attachments. Note: if the folder already contains
                            ' attachment with the given name, MailBee will generate unique name
                            ' (e.g. pic.gif will be saved as pic[1].gif if pic.gif already exists
                            ' in the target folder.
                            env.MessagePreview.Attachments.SaveAll("C:\Temp")
                        End If
                    Next
                End If
            End If
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
DownloadEnvelopes Overload
MailBee.ImapMail Namespace
ImapBeginDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object)
MailBee.ImapMailEnvelope
MailBee.ImapMailImapBodyStructure


Imap.DownloadEnvelopesAsync Method

ImapDownloadEnvelopesAsync Method
Overload List
 | Name | Description
Public method | DownloadEnvelopesAsync(String, Boolean) | async/await version of DownloadEnvelopes(String, Boolean).
Public method | DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32) | async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32).
Public method | DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32, String, String) | async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadEnvelopesAsync Method (String, Boolean)

ImapDownloadEnvelopesAsync Method (String, Boolean)
async/await version of DownloadEnvelopes(String, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EnvelopeCollection> DownloadEnvelopesAsync(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DownloadEnvelopesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean
) As Task(Of EnvelopeCollection)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: Task EnvelopeCollection
A task that represents the asynchronous operation. The value of TResult parameter is EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
DownloadEnvelopesAsync Overload
MailBee.ImapMail Namespace


Imap.DownloadEnvelopesAsync Method (String, Boolean, EnvelopeParts, Int32)

ImapDownloadEnvelopesAsync Method (String, Boolean, EnvelopeParts, Int32)
async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EnvelopeCollection> DownloadEnvelopesAsync(
    string messageIndexSet,
    bool indexIsUid,
    EnvelopeParts parts,
    int bodyPreviewSize
)
Public Function DownloadEnvelopesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    parts As EnvelopeParts,
    bodyPreviewSize As Integer
) As Task(Of EnvelopeCollection)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
Specifies which message elements or attributes to download.
bodyPreviewSize
Type: SystemInt32
If parts includes MessagePreview flag, specifies the length of the message body section (in bytes) to be downloaded in addition to the message header section; if 0, only the message header is downloaded; if -1 or -2, the entire message is downloaded. -1 is the only option which also sets Seen flag marking the message as read.

Return Value

Type: Task EnvelopeCollection
A task that represents the asynchronous operation. The value of TResult parameter is EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
DownloadEnvelopesAsync Overload
MailBee.ImapMail Namespace


Imap.DownloadEnvelopesAsync Method (String, Boolean, EnvelopeParts, Int32, String[], String[])

ImapDownloadEnvelopesAsync Method (String, Boolean, EnvelopeParts, Int32, String, String)
async/await version of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EnvelopeCollection> DownloadEnvelopesAsync(
    string messageIndexSet,
    bool indexIsUid,
    EnvelopeParts parts,
    int bodyPreviewSize,
    string[] extraHeaders,
    string[] extraItems
)
Public Function DownloadEnvelopesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    parts As EnvelopeParts,
    bodyPreviewSize As Integer,
    extraHeaders As String(),
    extraItems As String()
) As Task(Of EnvelopeCollection)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
Specifies which message elements or attributes to download.
bodyPreviewSize
Type: SystemInt32
If parts includes MessagePreview flag, specifies the length of the message body section (in bytes) to be downloaded in addition to the message header section; if 0, only the message header is downloaded; if -1 or -2, the entire message is downloaded. -1 is the only option which also sets Seen flag marking the message as read.
extraHeaders
Type: SystemString
The array of names of message headers to be downloaded, or a null reference (Nothing in Visual Basic) if additional headers are not needed.
extraItems
Type: SystemString
The array of additional FETCH request items to download, or a null reference (Nothing in Visual Basic) if additional FETCH items are not needed.

Return Value

Type: Task EnvelopeCollection
A task that represents the asynchronous operation. The value of TResult parameter is EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
DownloadEnvelopesAsync Overload
MailBee.ImapMail Namespace


Imap.DownloadEnvelopesEx Method

ImapDownloadEnvelopesEx Method
Fetches message envelopes, bodies, headers, flags, attributes, etc from the server allowing you to request different items for every message in the list.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection DownloadEnvelopesEx(
    long[] messageIndices,
    bool indicesAreUids,
    EnvelopeParts[] parts,
    int[] bodyPreviewSizes,
    string[][] extraHeaders,
    string[][] extraItems
)
Public Function DownloadEnvelopesEx (
    messageIndices As Long(),
    indicesAreUids As Boolean,
    parts As EnvelopeParts(),
    bodyPreviewSizes As Integer(),
    extraHeaders As String()(),
    extraItems As String()()
) As EnvelopeCollection

Parameters

messageIndices
Type: SystemInt64
The array of UIDs or message numbers of the messages to be fetched.
indicesAreUids
Type: SystemBoolean
If true, messageIndices holds UIDs; otherwise, ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
For every message to be fetched, denotes its EnvelopeParts to be requested. If a null reference (Nothing in Visual Basic), MailBee will use Uid for all messages.
bodyPreviewSizes
Type: SystemInt32
For every message to be fetched, denotes how many bytes of the raw body part to download in addition to the raw header part. If a null reference, MailBee will use 0 for all messages.
extraHeaders
Type: SystemString
For every message to be fetched, denotes its extra MIME headers to be requested. If a null reference MailBee will not request any additional headers for any messages.
extraItems
Type: SystemString
For every message to be fetched, denotes its extra items to be requested. If a null reference MailBee will not request any additional items for any messages.

Return Value

Type: EnvelopeCollection
EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | messageIndices is a null reference (Nothing in Visual Basic) or empty; bodyPreviewSizes, extraHeaders and extraItems have length different from messageIndices length.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Use this method if you want to download different elements for different messages and would like to have the entire operation complete as a single command (pipelined batch). Typical cases for that are downloading text bodies or certain types of attachments from multiple messages. For other cases (when you need the same items for all messages, like envelope, header, full message, etc), use DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method or its overloads.

The main advantage of DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) method is speed. You can do the same calling DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) multiple times (one call per message) each time requesting different message items. DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) just makes it possible to send all the requests at once and thus save time on multiple round-trips FETCH requests to the server and FETCH responses back from it. If performance is not a concern, use DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String). See GetEnvelopeItem(String, Boolean) for example.

Usually, DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) method is used after DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) which requested body structures of the messages. Then you code analyzes these body structures, composes FETCH requests and the expected items in FETCH responses, and supplies the collected information to DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String) method.

Examples
Two samples in this topic (you may also find the sample in BeginDownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object) topic). The first sample downloads all images from all e-mails in inbox (not downloading anything else) and saves them to disk.
C#
VB
Copy
using System;
using System.Collections;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Enable logging for troubleshooting (for instance, you can see
        // if you send and receive correct FETCH requests and responses.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("user", "password");
        imp.SelectFolder("INBOX");

        // Download body structure for all e-mails in the inbox.
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, true,
            EnvelopeParts.BodyStructure, 0);

        // The array of lists of FETCH keys to request from the server.
        string[][] fetchRequestKeyListArray = new string[envs.Count][];

        // The array of lists of FETCH keys to expect from the server in return
        // to requests of items listed in each element of fetchRequestKeyListArray.
        string[][] fetchResponseKeyListArray = new string[envs.Count][];

        // UIDs of the messages for which we received the body structure.
        long[] uids = new long[envs.Count];

        for (int i = 0; i < envs.Count; i++)
        {
            Envelope env = envs[i];

            ArrayList fetchRequestKeyList = new ArrayList();
            ArrayList fetchResponseKeyList = new ArrayList();

            // Get body structures of all MIME parts as flat list.
            ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
            foreach (ImapBodyStructure part in parts)
            {
                if (part.ContentType.ToLower().IndexOf("image/") > -1)
                {
                    if (parts.Count > 1)
                    {
                        // For each image, we request its MIME part header and body
                        // (the IMAP4 protocol does not support getting the entire MIME
                        // part as a single block of data). Also note using .MIME instead of .HEADER
                        // because some mail servers don't support .HEADER syntax.
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + ".MIME]");
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + "]");

                        // For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[" + part.PartID + ".MIME]");
                        fetchResponseKeyList.Add("BODY[" + part.PartID + "]");
                    }
                    else
                    {
                        fetchRequestKeyList.Add("BODY.PEEK[HEADER]");
                        fetchRequestKeyList.Add("BODY.PEEK[TEXT]");

                        // For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[HEADER]");
                        fetchResponseKeyList.Add("BODY[TEXT]");
                    }
                }
            }

            // Second time, we'll get message by its UID. This will avoid the situation
            // when new message arrives between two queries (and thus it could be possible
            // to download wrong message second time).
            uids[i] = env.Uid;

            // Save the generated items for FETCH request and FETCH response.
            fetchRequestKeyListArray[i] = (string[])fetchRequestKeyList.ToArray(typeof(string));
            fetchResponseKeyListArray[i] = (string[])fetchResponseKeyList.ToArray(typeof(string));
        }

        if (envs.Count > 0)
        {
            // Download images.
            envs = imp.DownloadEnvelopesEx(uids, true,
                null, null, null,
                fetchRequestKeyListArray);

            foreach (Envelope env in envs)
            {
                // We need this to find FETCH request and response keys
                // which correspond to the envelope being examined.
                int index = Array.IndexOf(uids, env.Uid);

                if (index < 0)
                {
                    // For some odd reason, we got envelope we haven't requested.
                    // Hope this will never happen. Anyway, skip such envelope.
                    continue;
                }

                string[] fetchRequestKeys = fetchRequestKeyListArray[index];
                string[] fetchResponseKeys = fetchResponseKeyListArray[index];

                for (int i = 0; i < fetchRequestKeys.Length; i += 2)
                {
                    // Get MIME part header data.
                    byte[] mimePartHeader = (byte[])env.GetEnvelopeItem(
                        fetchResponseKeys[i], true);

                    // Get MIME part body data.
                    byte[] mimePartBody = (byte[])env.GetEnvelopeItem(
                        fetchResponseKeys[i + 1], true);

                    // Build MIME part data from header data and body data.
                    byte[] mimePartData = new byte[mimePartHeader.Length + mimePartBody.Length];
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length);
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData,
                        mimePartHeader.Length, mimePartBody.Length);
                    mimePartHeader = null;
                    mimePartBody = null;

                    // Build Attachment object from the MIME part data.
                    MimePart part = MimePart.Parse(mimePartData);
                    Attachment picture = new Attachment(part);

                    // Save the image into C:\Temp folder.
                    picture.SaveToFolder(@"C:\Temp", false);
                }
            }
        }

        imp.Disconnect();
    }
}
Imports System
Imports System.Collections
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' Enable logging for troubleshooting (for instance, you can see
        ' if you send and receive correct FETCH requests and responses.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("user", "password")
        imp.SelectFolder("INBOX")

        ' Download body structure for all e-mails in the inbox.
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(Imap.AllMessages, True, _
         EnvelopeParts.BodyStructure, 0)

        ' The array of lists of FETCH keys to request from the server.
        Dim fetchRequestKeyListArray()() As String = New String(envs.Count)() {}

        ' The array of lists of FETCH keys to expect from the server in return
        ' to requests of items listed in each element of fetchRequestKeyListArray.
        Dim fetchResponseKeyListArray()() As String = New String(envs.Count)() {}

        ' UIDs of the messages for which we received the body structure.
        Dim uids() As Long = New Long(envs.Count) {}

        Dim i As Integer
        For i = 0 To envs.Count - 1
            Dim env As Envelope = envs(i)

            Dim fetchRequestKeyList As ArrayList = New ArrayList
            Dim fetchResponseKeyList As ArrayList = New ArrayList

            ' Get body structures of all MIME parts as flat list.
            Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()
            Dim part As ImapBodyStructure
            For Each part In parts
                If part.ContentType.ToLower().IndexOf("image/") > -1 Then
                    If parts.Count > 1 Then
                        ' For each image, we request its MIME part header and body
                        ' (the IMAP4 protocol does not support getting the entire MIME
                        ' part as a single block of data). Also note using .MIME instead of .HEADER
                        ' because some mail servers don't support .HEADER syntax.
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + ".MIME]")
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + "]")

                        ' For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[" + part.PartID + ".MIME]")
                        fetchResponseKeyList.Add("BODY[" + part.PartID + "]")
                    Else
                        fetchRequestKeyList.Add("BODY.PEEK[HEADER]")
                        fetchRequestKeyList.Add("BODY.PEEK[TEXT]")

                        ' For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[HEADER]")
                        fetchResponseKeyList.Add("BODY[TEXT]")
                    End If
                End If
            Next

            ' Second time, we'll get message by its UID. This will avoid the situation
            ' when new message arrives between two queries (and thus it could be possible
            ' to download wrong message second time).
            uids(i) = env.Uid

            ' Save the generated items for FETCH request and FETCH response.
            fetchRequestKeyListArray(i) = CType(fetchRequestKeyList.ToArray(GetType(String)), String())
            fetchResponseKeyListArray(i) = CType(fetchResponseKeyList.ToArray(GetType(String)), String())
        Next

        If envs.Count > 0 Then
            ' Download images.
            envs = imp.DownloadEnvelopesEx(uids, True, Nothing, Nothing, Nothing, fetchRequestKeyListArray)

            Dim env As Envelope
            For Each env In envs
                ' We need this to find FETCH request and response keys
                ' which correspond to the envelope being examined.
                Dim index As Integer = Array.IndexOf(uids, env.Uid)

                If index < 0 Then
                    ' For some odd reason, we got envelope we haven't requested.
                    ' Hope this will never happen. Anyway, skip such envelope.
                    ' In VB 2005 and higher you can use Continue statement instead of Goto.
                    GoTo ContinueHere
                End If

                Dim fetchRequestKeys() As String = fetchRequestKeyListArray(index)
                Dim fetchResponseKeys() As String = fetchResponseKeyListArray(index)

                Dim j As Integer
                For j = 0 To fetchRequestKeys.Length - 1 Step 2
                    ' Get MIME part header data.
                    Dim mimePartHeader, mimePartBody As Byte()
                    mimePartHeader = env.GetEnvelopeItem(CType(fetchResponseKeys(j), String), True)

                    ' Get MIME part body data.
                    mimePartBody = env.GetEnvelopeItem(CType(fetchResponseKeys(j + 1), String), True)

                    ' Build MIME part data from header data and body data.
                    Dim mimePartData As Byte()
                    ReDim mimePartData(mimePartHeader.Length + mimePartBody.Length)
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length)
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData, mimePartHeader.Length, mimePartBody.Length)
                    mimePartHeader = Nothing
                    mimePartBody = Nothing

                    ' Build Attachment object from the MIME part data.
                    Dim part As MimePart = MimePart.Parse(mimePartData)
                    Dim picture As New Attachment(part)

                    ' Save the image into C:\Temp folder.
                    picture.SaveToFolder("C:\Temp", False)
                Next
ContinueHere:
            Next
        End If

        imp.Disconnect()
    End Sub
End Class
The second example is very similar to the first one but it downloads HTML and plain-text bodies rather than images.
C#
VB
Copy
using System;
using System.Collections;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Enable logging for troubleshooting (for instance, you can see
        // if you send and receive correct FETCH requests and responses.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("user", "password");
        imp.SelectFolder("INBOX");

        // Download body structure for all e-mails in the inbox.
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, true,
            EnvelopeParts.BodyStructure, 0);

        // The array of lists of FETCH keys to request from the server.
        string[][] fetchRequestKeyListArray = new string[envs.Count][];

        // The array of lists of FETCH keys to expect from the server in return
        // to requests of items listed in each element of fetchRequestKeyListArray.
        string[][] fetchResponseKeyListArray = new string[envs.Count][];

        // UIDs of the messages for which we received the body structure.
        long[] uids = new long[envs.Count];

        for (int i = 0; i < envs.Count; i++)
        {
            Envelope env = envs[i];

            ArrayList fetchRequestKeyList = new ArrayList();
            ArrayList fetchResponseKeyList = new ArrayList();

            // Get body structures of all MIME parts as flat list.
            ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
            foreach (ImapBodyStructure part in parts)
            {
                string contentType = part.ContentType.ToLower();
                string disposition = (part.Disposition == null ? string.Empty : part.Disposition.ToLower());
                if (disposition != "attachment" &&
                    (contentType == "text/plain" || contentType == "text/html"))
                {
                    if (parts.Count > 1)
                    {
                        // For each text body part, we request its MIME part header and body
                        // (the IMAP4 protocol does not support getting the entire MIME
                        // part as a single block of data). Also note using .MIME instead of .HEADER
                        // because some mail servers don't support .HEADER syntax.
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + ".MIME]");
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + "]");

                        // For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[" + part.PartID + ".MIME]");
                        fetchResponseKeyList.Add("BODY[" + part.PartID + "]");
                    }
                    else
                    {
                        fetchRequestKeyList.Add("BODY.PEEK[HEADER]");
                        fetchRequestKeyList.Add("BODY.PEEK[TEXT]");

                        // For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[HEADER]");
                        fetchResponseKeyList.Add("BODY[TEXT]");
                    }
                }
            }

            // Second time, we'll get message by its UID. This will avoid the situation
            // when new message arrives between two queries (and thus it could be possible
            // to download wrong message second time).
            uids[i] = env.Uid;

            // Save the generated items for FETCH request and FETCH response.
            fetchRequestKeyListArray[i] = (string[])fetchRequestKeyList.ToArray(typeof(string));
            fetchResponseKeyListArray[i] = (string[])fetchResponseKeyList.ToArray(typeof(string));
        }

        if (envs.Count > 0)
        {
            // Download text parts.
            envs = imp.DownloadEnvelopesEx(uids, true, null, null, null, fetchRequestKeyListArray);

            foreach (Envelope env in envs)
            {
                // We need this to find FETCH request and response keys
                // which correspond to the envelope being examined.
                int index = Array.IndexOf(uids, env.Uid);

                if (index < 0)
                {
                    // For some odd reason, we got envelope we haven't requested.
                    // Hope this will never happen. Anyway, skip such envelope.
                    continue;
                }

                string[] fetchRequestKeys = fetchRequestKeyListArray[index];
                string[] fetchResponseKeys = fetchResponseKeyListArray[index];

                for (int i = 0; i < fetchRequestKeys.Length; i += 2)
                {
                    // Get MIME part header data.
                    byte[] mimePartHeader = (byte[])env.GetEnvelopeItem(
                        fetchResponseKeys[i], true);

                    // Get MIME part body data.
                    byte[] mimePartBody = (byte[])env.GetEnvelopeItem(
                        fetchResponseKeys[i + 1], true);

                    // Build MIME part data from header data and body data.
                    byte[] mimePartData = new byte[mimePartHeader.Length + mimePartBody.Length];
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length);
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData,
                        mimePartHeader.Length, mimePartBody.Length);
                    mimePartHeader = null;
                    mimePartBody = null;

                    // Build TextBodyPart object from the MIME part data.
                    MimePart part = MimePart.Parse(mimePartData);
                    TextBodyPart textPart = new TextBodyPart(part);

                    // Print content-type and text content of the message.
                    Console.WriteLine("For message with UID=" + env.Uid);
                    Console.WriteLine("Content-Type=" + part.ContentType);
                    Console.WriteLine("The text follows...");
                    Console.WriteLine(textPart.Text);
                    Console.WriteLine("---------------------------------");
                    Console.WriteLine();
                }
            }
        }

        imp.Disconnect();
    }
}
Imports System
Imports System.Collections
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' Enable logging for troubleshooting (for instance, you can see
        ' if you send and receive correct FETCH requests and responses.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Connect to the server, login and select inbox.
        imp.Connect("localhost")
        imp.Login("alex", "12345")
        imp.SelectFolder("INBOX")

        ' Download body structure for all e-mails in the inbox.
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(Imap.AllMessages, True, _
         EnvelopeParts.BodyStructure, 0)

        ' The array of lists of FETCH keys to request from the server.
        Dim fetchRequestKeyListArray()() As String = New String(envs.Count)() {}

        ' The array of lists of FETCH keys to expect from the server in return
        ' to requests of items listed in each element of fetchRequestKeyListArray.
        Dim fetchResponseKeyListArray()() As String = New String(envs.Count)() {}

        ' UIDs of the messages for which we received the body structure.
        Dim uids() As Long = New Long(envs.Count) {}

        Dim i As Integer
        For i = 0 To envs.Count - 1
            Dim env As Envelope = envs(i)

            Dim fetchRequestKeyList As ArrayList = New ArrayList
            Dim fetchResponseKeyList As ArrayList = New ArrayList

            ' Get body structures of all MIME parts as flat list.
            Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()
            Dim part As ImapBodyStructure
            For Each part In parts
                Dim contentType As String = part.ContentType.ToLower()
                Dim disposition As String = String.Empty
                If Not part.Disposition Is Nothing Then disposition = part.Disposition.ToLower()
                If disposition <> "attachment" AndAlso (contentType = "text/plain" Or contentType = "text/html") Then
                    If parts.Count > 1 Then
                        ' For each text body part, we request its MIME part header and body
                        ' (the IMAP4 protocol does not support getting the entire MIME
                        ' part as a single block of data). Also note using .MIME instead of .HEADER
                        ' because some mail servers don't support .HEADER syntax.
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + ".MIME]")
                        fetchRequestKeyList.Add("BODY.PEEK[" + part.PartID + "]")

                        ' For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[" + part.PartID + ".MIME]")
                        fetchResponseKeyList.Add("BODY[" + part.PartID + "]")
                    Else
                        fetchRequestKeyList.Add("BODY.PEEK[HEADER]")
                        fetchRequestKeyList.Add("BODY.PEEK[TEXT]")

                        ' For BODY.PEEK[...] request the server will return BODY[...] response.
                        fetchResponseKeyList.Add("BODY[HEADER]")
                        fetchResponseKeyList.Add("BODY[TEXT]")
                    End If
                End If
            Next

            ' Second time, we'll get message by its UID. This will avoid the situation
            ' when new message arrives between two queries (and thus it could be possible
            ' to download wrong message second time).
            uids(i) = env.Uid

            ' Save the generated items for FETCH request and FETCH response.
            fetchRequestKeyListArray(i) = CType(fetchRequestKeyList.ToArray(GetType(String)), String())
            fetchResponseKeyListArray(i) = CType(fetchResponseKeyList.ToArray(GetType(String)), String())
        Next

        If envs.Count > 0 Then
            ' Download text parts.
            envs = imp.DownloadEnvelopesEx(uids, True, Nothing, Nothing, Nothing, fetchRequestKeyListArray)

            Dim env As Envelope
            For Each env In envs
                ' We need this to find FETCH request and response keys
                ' which correspond to the envelope being examined.
                Dim index As Integer = Array.IndexOf(uids, env.Uid)

                If index < 0 Then
                    ' For some odd reason, we got envelope we haven't requested.
                    ' Hope this will never happen. Anyway, skip such envelope.
                    ' In VB 2005 and higher you can use Continue statement instead of Goto.
                    GoTo ContinueHere
                End If

                Dim fetchRequestKeys() As String = fetchRequestKeyListArray(index)
                Dim fetchResponseKeys() As String = fetchResponseKeyListArray(index)

                Dim j As Integer
                For j = 0 To fetchRequestKeys.Length - 1 Step 2
                    ' Get MIME part header data.
                    Dim mimePartHeader, mimePartBody As Byte()
                    mimePartHeader = env.GetEnvelopeItem(CType(fetchResponseKeys(j), String), True)

                    ' Get MIME part body data.
                    mimePartBody = env.GetEnvelopeItem(CType(fetchResponseKeys(j + 1), String), True)

                    ' Build MIME part data from header data and body data.
                    Dim mimePartData As Byte()
                    ReDim mimePartData(mimePartHeader.Length + mimePartBody.Length)
                    Buffer.BlockCopy(mimePartHeader, 0, mimePartData, 0, mimePartHeader.Length)
                    Buffer.BlockCopy(mimePartBody, 0, mimePartData, mimePartHeader.Length, mimePartBody.Length)
                    mimePartHeader = Nothing
                    mimePartBody = Nothing

                    ' Build TextBodyPart object from the MIME part data.
                    Dim part As MimePart = MimePart.Parse(mimePartData)
                    Dim textPart As TextBodyPart = New TextBodyPart(part)

                    ' Print content-type and text content of the message.
                    Console.WriteLine("For message with UID=" & env.Uid)
                    Console.WriteLine("Content-Type=" & part.ContentType)
                    Console.WriteLine("The text follows...")
                    Console.WriteLine(textPart.Text)
                    Console.WriteLine("---------------------------------")
                    Console.WriteLine()
                Next
ContinueHere:
            Next
        End If

        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadEnvelopesExAsync Method

ImapDownloadEnvelopesExAsync Method
async/await version of DownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<EnvelopeCollection> DownloadEnvelopesExAsync(
    long[] messageIndices,
    bool indicesAreUids,
    EnvelopeParts[] parts,
    int[] bodyPreviewSizes,
    string[][] extraHeaders,
    string[][] extraItems
)
Public Function DownloadEnvelopesExAsync (
    messageIndices As Long(),
    indicesAreUids As Boolean,
    parts As EnvelopeParts(),
    bodyPreviewSizes As Integer(),
    extraHeaders As String()(),
    extraItems As String()()
) As Task(Of EnvelopeCollection)

Parameters

messageIndices
Type: SystemInt64
The array of UIDs or message numbers of the messages to be fetched.
indicesAreUids
Type: SystemBoolean
If true, messageIndices holds UIDs; otherwise, ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
For every message to be fetched, denotes its EnvelopeParts to be requested. If a null reference (Nothing in Visual Basic), MailBee will use Uid for all messages.
bodyPreviewSizes
Type: SystemInt32
For every message to be fetched, denotes how many bytes of the raw body part to download in addition to the raw header part. If a null reference, MailBee will use 0 for all messages.
extraHeaders
Type: SystemString
For every message to be fetched, denotes its extra MIME headers to be requested. If a null reference MailBee will not request any additional headers for any messages.
extraItems
Type: SystemString
For every message to be fetched, denotes its extra items to be requested. If a null reference MailBee will not request any additional items for any messages.

Return Value

Type: Task EnvelopeCollection
A task that represents the asynchronous operation. The value of TResult parameter is EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadFolders Method

ImapDownloadFolders Method
Downloads the list of IMAP folders.
Overload List
Name | Description
DownloadFolders | Downloads the list of all IMAP folders of the mail account.
DownloadFolders(Boolean) | Downloads the list of IMAP folders of the mail account.
DownloadFolders(Boolean, String, String) | Downloads the list of IMAP folders matching the specified criteria.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadFolders Method

ImapDownloadFolders Method
Downloads the list of all IMAP folders of the mail account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderCollection DownloadFolders()
Public Function DownloadFolders As FolderCollection

Return Value

Type: FolderCollection
FolderCollection object if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the server supports XLIST or SPECIAL-USE extensions (Gmail does), well-known folder flags like Drafts or Trash will be available. See UseXList topic for details.
Examples
This sample downloads the list of all folders of the mail account, and displays them with in user-friendly view with indentation of folder nesting levels.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.server.com");
        imp.Login("jdoe", "secret");

        // Download all the folders.
        FolderCollection folders = imp.DownloadFolders();

        // Used for indentation of folder levels in the output.
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        foreach (Folder fold in folders)
        {
            // Indent each nesting level with two space characters.
            sb.Length = 0;
            sb.Append(' ', fold.NestingLevel * 2);

            // Print formatted name of the folder.
            Console.WriteLine(sb.ToString() + fold.ShortName);
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Download only subscribed folders.
        Dim folders As FolderCollection = imp.DownloadFolders()

        ' Used for indentation of folder levels in the output.
        Dim sb As New System.Text.StringBuilder

        ' Print full names of the folders.
        For Each fold As Folder In folders
            ' Indent each nesting level with two space characters.
            sb.Length = 0
            sb.Append(" ", fold.NestingLevel * 2)

            ' Print formatted name of the folder.
            Console.WriteLine(sb.ToString() & fold.ShortName)
        Next

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
DownloadFolders Overload
MailBee.ImapMail Namespace
ImapBeginDownloadFolders(Boolean, String, String, AsyncCallback, Object)


Imap.DownloadFolders Method (Boolean)

ImapDownloadFolders Method (Boolean)
Downloads the list of IMAP folders of the mail account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderCollection DownloadFolders(
    bool subscribedOnly
)
Public Function DownloadFolders (
    subscribedOnly As Boolean
) As FolderCollection

Parameters

subscribedOnly
Type: SystemBoolean
If true, only subscribed folders will be downloaded; otherwise, all the folders.

Return Value

Type: FolderCollection
FolderCollection object if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If subscribedOnly is false, UseXList is true and the server supports XLIST extension, extended folder flags like Drafts or Trash will be available. See UseXList topic for details.
Note Note
If the server supports SPECIAL-USE IMAP extension (Gmail does), extended flags will be available in all modes (both "list all folders" and "list subscribed-only folders"), even if UseXList is disabled.
Examples
This sample downloads the list of all subscribed folders of the mail account, and displays their full names.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");

        // Download only subscribed folders.
        FolderCollection folders = imp.DownloadFolders(true);

        // Print full names of the folders.
        foreach (Folder fold in folders)
        {
            Console.WriteLine(fold.Name);
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Download only subscribed folders.
        Dim folders As FolderCollection = imp.DownloadFolders(True)

        ' Print full names of the folders.
        For Each fold As Folder In folders
            Console.WriteLine(fold.Name)
        Next

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
DownloadFolders Overload
MailBee.ImapMail Namespace
ImapBeginDownloadFolders(Boolean, String, String, AsyncCallback, Object)


Imap.DownloadFolders Method (Boolean, String, String)

ImapDownloadFolders Method (Boolean, String, String)
Downloads the list of IMAP folders matching the specified criteria.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderCollection DownloadFolders(
    bool subscribedOnly,
    string parentFolderName,
    string pattern
)
Public Function DownloadFolders (
    subscribedOnly As Boolean,
    parentFolderName As String,
    pattern As String
) As FolderCollection

Parameters

subscribedOnly
Type: SystemBoolean
If true, only subscribed folders will be downloaded; otherwise, all the folders.
parentFolderName
Type: SystemString
The full name of the folder which subfolders must be downloaded, or a null reference (Nothing in Visual Basic) to download all the folders.
pattern
Type: SystemString
The exact or wildcard name (relative to parentFolderName) of the folder or folders to be downloaded, or a null reference (Nothing in Visual Basic) to download all the folders.

Return Value

Type: FolderCollection
FolderCollection object if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This overload is the encapsulation of LIST and LSUB commands of the IMAP4 protocol described in RFC3501. It also supports XLIST command which can be used to get well-known folder flags like Sent, Drafts or Spam (Gmail and SPECIAL-USE capable servers can also support these flags with regular LIST/LSUB commands, see UseXList topic for details). parentFolderName parameter corresponds to 'reference name' argument of LIST/LSUB command, and pattern parameter corresponds to 'mailbox name' argument.

If parentFolderName is null, 'reference name' will be empty string.

If pattern is null, 'mailbox name' will be "*" wildcard.

parentFolderName specifies the root to returns subfolders for.

"*" wildcard used as pattern means all folders including subfolders of the given root. "%" wildcard will force the server to return only immediate subfolders of the given root, without their own subfolders. Wildcards can appear in patterns multiple times (see BeginDownloadFolders(Boolean, String, String, AsyncCallback, Object) topic for the sample code).

The developer can refer to RFC3501 to find the further information regarding listing folders.

This method fully supports international folder names in both parentFolderName and pattern parameters.

If your IMAP server supports CHILDREN extension (most servers do), HasChildren and HasNoChildren flags make it easier to build the nested list of folders in case if you have too many folders to get them at once. E.g. you may get only one level and show [+] controls for folders having sub-folders. Without CHILDREN extension you'd have to download the second level of folders just to determine if the first level folders have subfolders or not.

Examples

This sample downloads the list of Inbox's immediate subfolders (without sub-sub-folders) having names starting with "Order". Thus, "Inbox/Orders", "Inbox/Order", "Inbox/Orders April 2006" will be listed while "Orders", "Inbox/Other", "Inbox/Orders April 2006/29" will not.

In this description, it's assumed "/" character is a delimiter of folder levels (some servers may use another delimiter, such as "."). However, the sample code correctly determines the delimiter and does not rely on assumption that the delimiter is "/".

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");

        // Download both subscribed and unsubscribed immediate subfolders
        // of Inbox, having names starting with "Order".
        FolderCollection folders = imp.DownloadFolders(false, "Inbox", "Order%");

        // Display downloaded folders' names.
        foreach (Folder fold in folders)
        {
            Console.WriteLine(fold.Name);
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Download both subscribed and unsubscribed immediate subfolders
        ' of Inbox, having names starting with "Order".
        Dim folders As FolderCollection = imp.DownloadFolders(False, "Inbox", "Order%")

        ' Display downloaded folders' names.
        For Each fold As Folder In folders
            Console.WriteLine(fold.Name)
        Next

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
DownloadFolders Overload
MailBee.ImapMail Namespace
ImapBeginDownloadFolders(Boolean, String, String, AsyncCallback, Object)


Imap.DownloadFoldersAsync Method

ImapDownloadFoldersAsync Method
Overload List
 | Name | Description
Public method | DownloadFoldersAsync | async/await version of DownloadFolders.
Public method | DownloadFoldersAsync(Boolean) | async/await version of DownloadFolders(Boolean).
Public method | DownloadFoldersAsync(Boolean, String, String) | async/await version of DownloadFolders(Boolean, String, String).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadFoldersAsync Method

ImapDownloadFoldersAsync Method
async/await version of DownloadFolders.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderCollection> DownloadFoldersAsync()
Public Function DownloadFoldersAsync As Task(Of FolderCollection)

Return Value

Type: Task FolderCollection
A task that represents the asynchronous operation. The value of TResult parameter is FolderCollection object if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
DownloadFoldersAsync Overload
MailBee.ImapMail Namespace


Imap.DownloadFoldersAsync Method (Boolean)

ImapDownloadFoldersAsync Method (Boolean)
async/await version of DownloadFolders(Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderCollection> DownloadFoldersAsync(
    bool subscribedOnly
)
Public Function DownloadFoldersAsync (
    subscribedOnly As Boolean
) As Task(Of FolderCollection)

Parameters

subscribedOnly
Type: SystemBoolean
If true, only subscribed folders will be downloaded; otherwise, all the folders.

Return Value

Type: Task FolderCollection
A task that represents the asynchronous operation. The value of TResult parameter is FolderCollection object if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
DownloadFoldersAsync Overload
MailBee.ImapMail Namespace


Imap.DownloadFoldersAsync Method (Boolean, String, String)

ImapDownloadFoldersAsync Method (Boolean, String, String)
async/await version of DownloadFolders(Boolean, String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderCollection> DownloadFoldersAsync(
    bool subscribedOnly,
    string parentFolderName,
    string pattern
)
Public Function DownloadFoldersAsync (
    subscribedOnly As Boolean,
    parentFolderName As String,
    pattern As String
) As Task(Of FolderCollection)

Parameters

subscribedOnly
Type: SystemBoolean
If true, only subscribed folders will be downloaded; otherwise, all the folders.
parentFolderName
Type: SystemString
The full name of the folder which subfolders must be downloaded, or a null reference (Nothing in Visual Basic) to download all the folders.
pattern
Type: SystemString
The exact or wildcard name (relative to parentFolderName) of the folder or folders to be downloaded, or a null reference (Nothing in Visual Basic) to download all the folders.

Return Value

Type: Task FolderCollection
A task that represents the asynchronous operation. The value of TResult parameter is FolderCollection object if the folder list was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
DownloadFoldersAsync Overload
MailBee.ImapMail Namespace


Imap.DownloadMessageHeaders Method

ImapDownloadMessageHeaders Method
Downloads the header of each message in the specified set from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadMessageHeaders(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DownloadMessageHeaders (
    messageIndexSet As String,
    indexIsUid As Boolean
) As MailMessageCollection

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

This method will download all the message headers in a single network operation, which greatly increases performance and reduces network traffic. However, if the application needs message headers just to get common information about messages (From, To, Date, Subject, Size, etc), it's more efficient to use DownloadEnvelopes(String, Boolean) method. Typically, IMAP4 ENVELOPE structure and related information is 200-400 bytes in size, while message header sections are usually larger 500 bytes. ENVELOPE structure, however, does not contain header fields which describe priority/importance of the message, attachments presence, etc. On other hand, the application may avoid downloading message header section and still obtain all the necessary information by requesting envelopes, body structures, and the required headers using DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.

Note Note
To track downloading headers, EnvelopeDownloaded event should be used. There is no MessageDownloaded event since mail messages are actually downloaded within envelopes. Once an envelope is downloaded, the mail message data is extracted from it. Generally speaking, DownloadMessageHeaders(String, Boolean) is a kind of overload of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method.
Examples
This console sample downloads message header sections of the last 5 messages in the inbox, and displays them.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe@domain.com", "secret");
        imp.SelectFolder("INBOX");

        // Download the last 5 message headers. Note: we do not check if
        // there are less than 5 messages in the inbox. See sample code
        // in DownloadEnvelopes(string, bool) overload for more details.
        MailMessageCollection msgs = imp.DownloadMessageHeaders(
            (imp.MessageCount - 4).ToString() + ":*", false);

        // Display header sections of the downloaded message headers.
        foreach (MailMessage msg in msgs)
        {
            Console.WriteLine("Header section of message #" + msg.IndexOnServer);
            Console.WriteLine();
            Console.WriteLine(msg.RawHeader);
            Console.WriteLine("===============================================");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Download the last 5 message headers. Note: we do not check if
        ' there are less than 5 messages in the inbox. See sample code
        ' in DownloadEnvelopes(string, bool) overload for more details.
        Dim msgs As MailMessageCollection = _
            imp.DownloadMessageHeaders((imp.MessageCount - 4).ToString() & ":*", False)

        ' Display header sections of the downloaded message headers.
        For Each msg As MailMessage In msgs
            Console.WriteLine("Header section of message #" & msg.IndexOnServer)
            Console.WriteLine()
            Console.WriteLine(msg.RawHeader)
            Console.WriteLine("===============================================")
        Next

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.DownloadMessageHeadersAsync Method

ImapDownloadMessageHeadersAsync Method
async/await version of DownloadMessageHeaders(String, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadMessageHeadersAsync(
    string messageIndexSet,
    bool indexIsUid
)
Public Function DownloadMessageHeadersAsync (
    messageIndexSet As String,
    indexIsUid As Boolean
) As Task(Of MailMessageCollection)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.

Return Value

Type: Task MailMessageCollection
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.EndClose Method

ImapEndClose Method
Ends the pending asynchronous close folder request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndClose()
Public Function EndClose As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginClose(Boolean, AsyncCallback, Object)


Imap.EndConnect Method

ImapEndConnect Method
Ends the pending asynchronous connection request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndConnect()
Public Function EndConnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginConnect(String, Int32, Socket, EndPoint, AsyncCallback, Object)


Imap.EndCopyOrMoveMessages Method

ImapEndCopyOrMoveMessages Method
Ends a pending asynchronous request for copying or moving messages.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndCopyOrMoveMessages()
Public Function EndCopyOrMoveMessages As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginCopyOrMoveMessages(String, Boolean, String, UidPlusResult, Boolean, AsyncCallback, Object)


Imap.EndDisconnect Method

ImapEndDisconnect Method
Ends a pending asynchronous disconnection request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndDisconnect()
Public Function EndDisconnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginDisconnect(AsyncCallback, Object)


Imap.EndDownloadEnvelopes Method

ImapEndDownloadEnvelopes Method
Ends the pending asynchronous download envelopes request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection EndDownloadEnvelopes()
Public Function EndDownloadEnvelopes As EnvelopeCollection

Return Value

Type: EnvelopeCollection
On success, a EnvelopeCollection object representing the downloaded envelopes; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object)


Imap.EndDownloadEnvelopesEx Method

ImapEndDownloadEnvelopesEx Method
Ends the pending asynchronous request of pipelined downloading envelopes.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection EndDownloadEnvelopesEx()
Public Function EndDownloadEnvelopesEx As EnvelopeCollection

Return Value

Type: EnvelopeCollection
On success, a EnvelopeCollection object representing the downloaded envelopes; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginDownloadEnvelopesEx(Int64, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object)


Imap.EndDownloadFolders Method

ImapEndDownloadFolders Method
Ends the pending asynchronous download folders request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderCollection EndDownloadFolders()
Public Function EndDownloadFolders As FolderCollection

Return Value

Type: FolderCollection
On success, a FolderCollection object representing the downloaded folders; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginDownloadFolders(Boolean, String, String, AsyncCallback, Object)


Imap.EndExecuteCustomCommand Method

ImapEndExecuteCustomCommand Method
Ends the pending asynchronous request for sending user-defined command to the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndExecuteCustomCommand()
Public Function EndExecuteCustomCommand As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginExecuteCustomCommand(String, String, AsyncCallback, Object)


Imap.EndIdle Method

ImapEndIdle Method
Ends the pending asynchronous request for idling termination.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndIdle()
Public Function EndIdle As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Because idling is multi-step process (requesting idle, idling, requesting for idling termination), EndIdle call must be prepended with StopIdle call which initiates request to terminate idling. Thus, EndIdle itself finishes not idling itself (initiated with BeginIdle(AsyncCallback, Object)) but idling termination (IMAP4's DONE command, initiated with StopIdle method).
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginIdle(AsyncCallback, Object)
ImapStopIdle


Imap.EndLogin Method

ImapEndLogin Method
Ends the pending asynchronous login request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndLogin()
Public Function EndLogin As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod, AsyncCallback, Object)


Imap.EndSearch Method

ImapEndSearch Method
Ends the pending asynchronous search request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageIndexCollection EndSearch()
Public Function EndSearch As MessageIndexCollection

Return Value

Type: MessageIndexCollection
On success, a UidCollection or MessageNumberCollection object representing the indices (UIDs or ordinal message numbers) of the found messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The type of the collection returned (UidCollection or MessageNumberCollection) depends on the value of returnUids parameter of BeginSearch(Boolean, String, String, AsyncCallback, Object) method called to initiate the search.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginSearch(Boolean, String, String, AsyncCallback, Object)


Imap.EndSelectFolder Method

ImapEndSelectFolder Method
Ends the pending asynchronous select folder request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndSelectFolder()
Public Function EndSelectFolder As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginSelectFolder(String, Boolean, AsyncCallback, Object)


Imap.EndSetMessageFlags Method

ImapEndSetMessageFlags Method
Ends a pending asynchronous setting message flags request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndSetMessageFlags()
Public Function EndSetMessageFlags As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginSetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean, AsyncCallback, Object)


Imap.EndSortedSearch Method

ImapEndSortedSearch Method
Ends the pending asynchronous sorted search request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageIndexCollection EndSortedSearch()
Public Function EndSortedSearch As MessageIndexCollection

Return Value

Type: MessageIndexCollection
On success, a UidCollection or MessageNumberCollection object representing the indices (UIDs or ordinal message numbers) of the found messages in the specified order; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The type of the collection returned (UidCollection or MessageNumberCollection) depends on the value of returnUids parameter of BeginSortedSearch(Boolean, String, String, String, AsyncCallback, Object) method called to initiate the sorted search.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginSortedSearch(Boolean, String, String, String, AsyncCallback, Object)


Imap.EndStartTls Method

ImapEndStartTls Method
Ends a pending asynchronous TLS/SSL negotiation request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndStartTls()
Public Function EndStartTls As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginStartTls(AsyncCallback, Object)


Imap.EndUploadMessage Method

ImapEndUploadMessage Method
Ends the pending asynchronous upload message request.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndUploadMessage()
Public Function EndUploadMessage As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapBeginUploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult, AsyncCallback, Object)


Imap.ExamineFolder Method

ImapExamineFolder Method
Selects the specified folder (mailbox in IMAP4 terms) for read-only access.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ExamineFolder(
    string folderName
)
Public Function ExamineFolder (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The full name of the folder to be selected.

Return Value

Type: Boolean
true if the folder was selected successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

When the folder is selected for read-only access, the selected folder is identified as read-only. No changes to the permanent state of the folder, including per-user state, are permitted; in particular, when messages are downloaded, they won't lose the \Recent flag.

To select the folder for read-write access, the developer should use SelectFolder(String) method.

The developer should specify the full name of the folder (including all parent folders' names if the folder is subfolder of another existing folder). See CreateFolder(String) topic for details regarding folder names.

Examples
This sample connects to the IMAP4 server, logs in the mail account, selects Inbox folder in read-only mode, and downloads the last message without loosing \Recent flag (if the message has this flag set).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe", "secret");

        // Select the folder in read-only mode.
        imp.ExamineFolder("Inbox");

        if (imp.MessageCount > 0)
        {
            // Download and save last message into a file.
            // If the message is recent, it won't loose \Recent flag.
            MailMessage msg = imp.DownloadEntireMessage(imp.MessageCount, false);
            msg.SaveMessage(@"C:\Temp\msg.eml");
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample

    Sub Main(ByVal args As String())
        ' The actual code (put it into a method of your class)
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select the folder in read-only mode.
        imp.ExamineFolder("Inbox")

        If imp.MessageCount > 0 Then
            ' Download and save last message into a file.
            ' If the message is recent, it won't loose \Recent flag.
            Dim msg As MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)
            msg.SaveMessage("C:\Temp\msg.eml")
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSelectFolder(String)
ImapIsFolderSelected


Imap.ExamineFolderAsync Method

ImapExamineFolderAsync Method
async/await version of ExamineFolder(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ExamineFolderAsync(
    string folderName
)
Public Function ExamineFolderAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The full name of the folder to be selected.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ExecuteCustomCommand Method

ImapExecuteCustomCommand Method
Sends user-defined command to the server and receives the server response to this command.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ExecuteCustomCommand(
    string command,
    string commandID
)
Public Function ExecuteCustomCommand (
    command As String,
    commandID As String
) As Boolean

Parameters

command
Type: SystemString
User-defined command text (without line terminator).
commandID
Type: SystemString
The ID (tag in IMAP4 terms) which will be prepended to the command text, or an empty string to let MailBee autogenerate the ID value, or a null reference (Nothing in Visual Basic) to send command without ID.

Return Value

Type: Boolean
true if the command was executed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To use this method, the developer should have some knowledge of the IMAP4 protocol.

If commandID is non-empty string and not a null reference, MailBee will send the following request to the server (in C# terms): commandID + " " + command + "\r\n".

If commandID is "" (Empty), the entire request would be "MBNxxxxxxxx" + " " + command + "\r\n" where "xxxxxxxx" is an ordinal number of the issued command since the moment of establishing connection with the server.

If commandID is a null reference, the entire request would be command + "\r\n" (untagged request, also called "command continuation request").

To analyze results of user-defined commands, the developer can use GetServerResponse and GetServerResponses(String) methods.

To check if the server supports the particular extension/capability, the developer can use GetExtension(String) method passing the name of the capability.

Examples
This sample connects to the IMAP4 server, logs in the mail account, and sends IDLE and DONE commands (the server must support IDLE extension).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class)
Imap imp = new Imap();
imp.Connect("imap.company.com");
imp.Login("jdoe", "secret");
imp.ExecuteCustomCommand("IDLE", string.Empty);
imp.ExecuteCustomCommand("DONE", null);
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class)
Dim imp As New Imap
imp.Connect("imap.company.com")
imp.Login("jdoe", "secret")
imp.ExecuteCustomCommand("IDLE", String.Empty)
imp.ExecuteCustomCommand("DONE", Nothing)
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ExecuteCustomCommandAsync Method

ImapExecuteCustomCommandAsync Method
async/await version of ExecuteCustomCommand(String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ExecuteCustomCommandAsync(
    string command,
    string commandID
)
Public Function ExecuteCustomCommandAsync (
    command As String,
    commandID As String
) As Task(Of Boolean)

Parameters

command
Type: SystemString
User-defined command text (without line terminator).
commandID
Type: SystemString
The ID (tag in IMAP4 terms) which will be prepended to the command text, or an empty string to let MailBee autogenerate the ID value, or a null reference (Nothing in Visual Basic) to send command without ID.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Expunge Method

ImapExpunge Method
Permanently removes the messages marked as deleted from the currently selected folder.
Overload List
Name | Description
Expunge | Permanently removes all the messages marked as deleted from the currently selected folder.
Expunge(String, Boolean) | Permanently removes the messages marked as deleted from the currently selected folder.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Expunge Method

ImapExpunge Method
Permanently removes all the messages marked as deleted from the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Expunge()
Public Function Expunge As Boolean

Return Value

Type: Boolean
true if the command succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This overload can be used to expunge all messages marked as deleted from the current folder without closing it.

To expunge only certain messages (so that some messages having \Deleted flag set would remain), the developer should use Expunge(String, Boolean) overload.

To expunge deleted messages asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

Examples
This sample removes last 10 messages from Sent folder. If there were another messages marked as deleted in this folder, they will be removed as well.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap.domain.com");
        imp.Login("jdoe@domain.com", "secret");

        // Select Sent folder.
        imp.SelectFolder("Sent");

        // Mark last 10 messages as deleted.
        if (imp.MessageCount >= 10)
        {
            string range = (imp.MessageCount - 9).ToString() + ":" + imp.MessageCount.ToString();
            imp.SetMessageFlags(range, false, SystemMessageFlags.Deleted, MessageFlagAction.Add);
        }

        // Expunge all messages marked as deleted.
        imp.Expunge();

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select Sent folder.
        imp.SelectFolder("Sent")

        ' Mark last 10 messages as deleted.
        If (imp.MessageCount >= 10) Then
            Dim range As String = (imp.MessageCount - 9).ToString() & _
                ":" & imp.MessageCount.ToString()
            imp.SetMessageFlags(range, False, SystemMessageFlags.Deleted, _
                MessageFlagAction.Add)
        End If

        ' Expunge all messages marked as deleted.
        imp.Expunge()

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
Expunge Overload
MailBee.ImapMail Namespace
ImapClose(Boolean)


Imap.Expunge Method (String, Boolean)

ImapExpunge Method (String, Boolean)
Permanently removes the messages marked as deleted from the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Expunge(
    string uidSet,
    bool forceUidExpunge
)
Public Function Expunge (
    uidSet As String,
    forceUidExpunge As Boolean
) As Boolean

Parameters

uidSet
Type: SystemString
The comma-separated list of UIDs of the messages to be deleted, or a null reference (Nothing in Visual Basic) if all messages marked as deleted should be removed.
forceUidExpunge
Type: SystemBoolean
If true and uidSet is not a null reference, allows MailBee to use UID EXPUNGE command only to expunge the messages. If false, MailBee is allowed to simulate UID EXPUNGE using standard commands if UID EXPUNGE is not supported by the server.

Return Value

Type: Boolean
true if the command succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeProtocolExtensionNotSupportedException | UID EXPUNGE required but not supported by the server and ThrowExceptions is true.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This overload can be used to expunge the specified messages only. Often, it's required to remove certain message from the folder but leave other messages marked as deleted intact. The standard IMAP4 protocol does not allow this to be done but if the server supports UIDPLUS extension, it becomes possible (via UID EXPUNGE command).

This method always issues EXPUNGE if uidSet is not set. If uidSet is not a null reference, the method will attempt to delete the messages having UIDs from uidSet list and \Deleted flag set. If, however, UIDPLUS is not supported, the method will either simulate effect of UID EXPUNGE using a number of regular IMAP4 commands (if forceUidExpunge is false) or report error and do not expunge any messages (if forceUidExpunge is true).

In most cases, it's ok to set forceUidExpunge to false. The only reason for not doing so is when the component is used with the IMAP folder where messages are added very often by another clients. In this case, while the component executes a sequence of commands to expunge certain messages, another mail client can add, remove, or manage messages in the same folder. In this case, the folder state may go out of sync. In all other cases, if no other mail agents access the same folder at the same time, it's safe to use MailBee simulation of UID EXPUNGE command when it's not supported by the server.

Examples
This sample marks the first message in inbox as deleted, and then expunges it. It there are some other messages marked as deleted in inbox, they will not be expunged.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap.domain.com");
        imp.Login("jdoe@domain.com", "secret");

        // Select Inbox folder.
        imp.SelectFolder("INBOX");

        // Mark message #1 as deleted.
        imp.SetMessageFlags("1", false,
            SystemMessageFlags.Deleted, MessageFlagAction.Add);

        // To expunge specific message, we need to know its UID.
        EnvelopeCollection uidList = imp.DownloadEnvelopes("1", false, EnvelopeParts.Uid, 0);

        if (uidList.Count > 0)
        {
            // Expunge message #1 by its UID.
            imp.Expunge(uidList[0].Uid.ToString(), false);
        }

        // We do not call Close() here to prevent remaining messages
        // marked as deleted from being expunged.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select Inbox folder.
        imp.SelectFolder("INBOX")

        ' Mark message #1 as deleted.
        imp.SetMessageFlags("1", False, _
            SystemMessageFlags.Deleted, MessageFlagAction.Add)

        ' To expunge specific message, we need to know its UID.
        Dim uidList As EnvelopeCollection = _
            imp.DownloadEnvelopes("1", False, EnvelopeParts.Uid, 0)

        If uidList.Count > 0 Then
            ' Expunge message #1 by its UID.
            imp.Expunge(uidList(0).Uid.ToString(), False)
        End If

        ' We do not call Close() here to prevent remaining messages
        ' marked as deleted from being expunged.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
Expunge Overload
MailBee.ImapMail Namespace


Imap.ExpungeAsync Method

ImapExpungeAsync Method
Overload List
 | Name | Description
Public method | ExpungeAsync | async/await version of Expunge.
Public method | ExpungeAsync(String, Boolean) | async/await version of Expunge(String, Boolean).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ExpungeAsync Method

ImapExpungeAsync Method
async/await version of Expunge.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ExpungeAsync()
Public Function ExpungeAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
ExpungeAsync Overload
MailBee.ImapMail Namespace


Imap.ExpungeAsync Method (String, Boolean)

ImapExpungeAsync Method (String, Boolean)
async/await version of Expunge(String, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ExpungeAsync(
    string uidSet,
    bool forceUidExpunge
)
Public Function ExpungeAsync (
    uidSet As String,
    forceUidExpunge As Boolean
) As Task(Of Boolean)

Parameters

uidSet
Type: SystemString
The comma-separated list of UIDs of the messages to be deleted, or a null reference (Nothing in Visual Basic) if all messages marked as deleted should be removed.
forceUidExpunge
Type: SystemBoolean
If true and uidSet is not a null reference, allows MailBee to use UID EXPUNGE command only to expunge the messages. If false, MailBee is allowed to simulate UID EXPUNGE using standard commands if UID EXPUNGE is not supported by the server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
ExpungeAsync Overload
MailBee.ImapMail Namespace


Imap.GetAccountQuota Method

ImapGetAccountQuota Method
Gets the quota (resource usage limit) of the entire mail account on the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderQuota GetAccountQuota()
Public Function GetAccountQuota As FolderQuota

Return Value

Type: FolderQuota
FolderQuota object if the quota information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeProtocolExtensionNotSupportedException | QUOTA not supported by the server and ThrowExceptions is true.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method can be used to obtain the account quota and current usage (in bytes). Also, the current and the maximum number of messages in the account can be set too. However, most servers limit account usage in bytes only. Number of messages is usually not limited and not counted.

Note Note
This method uses QUOTA capability be supported by the IMAP4 server. The developer can check if QUOTA capability is supported using GetExtension(String) method. Also, some servers cannot return an account quota but they can return it for INBOX folder (however, this in fact designates the quota for the entire account). If you got such a server, use GetFolderQuota("INBOX") instead of GetAccountQuota.
Examples
This sample gets the account quota information and displays the maximum size (in bytes) and the current usage (in percent) of the account storage.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap.company.com");
        imp.Login("jdoe", "secret");

        if (imp.GetExtension("QUOTA") != null)
        {
            // Download quota information for the entire account.
            FolderQuota quota = imp.GetAccountQuota();

            if (quota.MaxStorageSize > -1 && quota.CurrentStorageSize > -1)
            {
                long percent = (quota.CurrentStorageSize * 100) / quota.MaxStorageSize;
                Console.WriteLine("You are using " + percent.ToString() + "% of your " +
                    quota.MaxStorageSize + " space");
            }
        }
        else
        {
            Console.WriteLine("QUOTA capability not supported, sorry");
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        If Not imp.GetExtension("QUOTA") Is Nothing Then
            ' Download Inbox folder status information.
            Dim quota As FolderQuota = imp.GetAccountQuota()

            If quota.MaxStorageSize > -1 AndAlso quota.CurrentStorageSize > -1 Then
                Console.WriteLine(quota.MaxStorageSize & _
                " is the maximum allowed total size (in bytes) " & _
                "of all messages in the folder.")
            End If
        Else
            Console.WriteLine("QUOTA capability not supported, sorry")
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapGetFolderQuota(String)


Imap.GetAccountQuotaAsync Method

ImapGetAccountQuotaAsync Method
async/await version of GetAccountQuota.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderQuota> GetAccountQuotaAsync()
Public Function GetAccountQuotaAsync As Task(Of FolderQuota)

Return Value

Type: Task FolderQuota
A task that represents the asynchronous operation. The value of TResult parameter is FolderQuota object if the quota information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetErrorDescription Method

ImapGetErrorDescription Method
Returns a textual description of the last occurred error.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetErrorDescription()
Public Function GetErrorDescription As String

Return Value

Type: String
A string value containing a textual description of the last occurred error.
Remarks
Error descriptions can be localized or edited by deriving from Resources class.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetExtension Method

ImapGetExtension Method
Returns the name of the specified IMAP4 capability if it's supported by the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetExtension(
    string name
)
Public Function GetExtension (
    name As String
) As String

Parameters

name
Type: SystemString
The name of the capability. This name is case-insensitive, e.g. uidplus and UIDPLUS mean the same.

Return Value

Type: String
If the specified capability is supported, the return value is the lowercased name of the capability. If the given capability is not supported, the return value is a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
You should already be connected to the IMAP4 server in order to use this method.
Examples
This sample displays whether the server supports UIDPLUS capability.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
string ext = imp.GetExtension("UIDPLUS");
if (ext == null)
{
    Console.WriteLine("The given IMAP4 server does not support UIDPLUS");
}
else
{
    Console.WriteLine("UIDPLUS is supported");
}
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
Dim ext As String = imp.GetExtension("UIDPLUS")
If ext Is Nothing Then
    Console.WriteLine("The given IMAP4 server does not support UIDPLUS")
Else
    Console.WriteLine("UIDPLUS is supported")
End If
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetExtensions Method

ImapGetExtensions Method
Returns a reference to the key-value list of the mail server capabilities.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary GetExtensions()
Public Function GetExtensions As StringDictionary

Return Value

Type: StringDictionary
The key-value list of the mail server capabilities, or a null reference (Nothing in Visual Basic) if the capabilities list is not available.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

You should already be connected to the IMAP4 server in order to use this method.

In the returned StringDictionary, each key is a capability name (always lowercase) and its value is an empty string (because IMAP4's capabilities have no parameters).

Examples
This sample displays the list of all capabilities supported by the mail server.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
System.Collections.Specialized.StringDictionary caps = imp.GetExtensions();
if (caps == null)
{
    Console.WriteLine("The given server does not support any IMAP4 extensions");
}
else
{
    foreach (string cap in caps.Keys)
    {
        Console.WriteLine(cap);
    }
}
imp.Disconnect();

// The output (the actual content will be different for a particular mail server).
auth=plain
multiappend
imap4
auth=login
literal+
auth=digest-md5
imap4rev1
auth=ntlm
quota
uidplus
starttls
auth=cram-md5
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
Dim caps As System.Collections.Specialized.StringDictionary = imp.GetExtensions()
If caps Is Nothing Then
    Console.WriteLine("The given server does not support any IMAP4 extensions")
Else
    For Each cap As String In caps.Keys
        Console.WriteLine(cap)
    Next
End If

imp.Disconnect()

' The output (the actual content will be different for a particular mail server).
auth=plain
multiappend
imap4
auth=login
literal+
auth=digest-md5
imap4rev1
auth=ntlm
quota
uidplus
starttls
auth=cram-md5
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetFolderQuota Method

ImapGetFolderQuota Method
Gets the quota (resource usage limit) of the specified folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderQuota GetFolderQuota(
    string folderName
)
Public Function GetFolderQuota (
    folderName As String
) As FolderQuota

Parameters

folderName
Type: SystemString
The full name of the folder to get the quota of.

Return Value

Type: FolderQuota
FolderQuota object if the quota information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeProtocolExtensionNotSupportedException | QUOTA not supported by the server and ThrowExceptions is true.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method can be used to obtain the folder quota information such as maximum allowed size of the folder, the current size of the folder, etc.

To get the quota set for the entire account on the IMAP4 server, the developer can use GetAccountQuota method.

Note Note
This method uses QUOTA capability be supported by the IMAP4 server. The developer can check if QUOTA capability is supported using GetExtension(String) method.
Examples
This sample gets Inbox folder quota information and displays the maximum allowed size of the folder (the top limit of the total size in bytes of all messages in the folder).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");

        if (imp.GetExtension("QUOTA") != null)
        {
            // Download Inbox folder quota information.
            FolderQuota quota = imp.GetFolderQuota("Inbox");

            if (quota.MaxStorageSize > -1)
            {
                Console.WriteLine(quota.MaxStorageSize +
                    " is the maximum allowed total size (in bytes) " +
                    "of all messages in the folder.");
            }
        }
        else
        {
            Console.WriteLine("QUOTA capability not supported, sorry");
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        If Not imp.GetExtension("QUOTA") Is Nothing Then
            ' Download Inbox folder status information.
            Dim quota As FolderQuota = imp.GetFolderQuota("Inbox")

            If quota.MaxStorageSize > -1 Then
                Console.WriteLine(quota.MaxStorageSize & _
                " is the maximum allowed total size (in bytes) " & _
                "of all messages in the folder.")
            End If
        Else
            Console.WriteLine("QUOTA capability not supported, sorry")
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapGetAccountQuota


Imap.GetFolderQuotaAsync Method

ImapGetFolderQuotaAsync Method
async/await version of GetFolderQuota(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderQuota> GetFolderQuotaAsync(
    string folderName
)
Public Function GetFolderQuotaAsync (
    folderName As String
) As Task(Of FolderQuota)

Parameters

folderName
Type: SystemString
The full name of the folder for which to get the quota.

Return Value

Type: Task FolderQuota
A task that represents the asynchronous operation. The value of TResult parameter is FolderQuota object if the quota information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetFolderSize Method

ImapGetFolderSize Method
Downloads the size of each message in the currently selected folder and returns the total size occupied by all messages in this folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long GetFolderSize()
Public Function GetFolderSize As Long

Return Value

Type: Int64
On success, return the total size occupied by all messages in this folder; otherwise, -1.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the application needs to calculate the total size of all messages in all folders of the mail account, it should use QUOTA extension (GetAccountQuota method) and fall back to multiple GetFolderSize calls only if QUOTA is not supported. However, iterating through all the folders and downloading messages' sizes may take considerable amount of time. Also, it's not possible to determine sizes of non-selectable folders and sizes of folders themselves (without their contained messages) using non-QUOTA approach. Thus, the storage size obtained from GetAccountQuota is usually larger (by 1% or so) than the size determined via a series of SelectFolder(String) and GetFolderSize calls.
Note Note
GetFolderSize method considers only messages belonging to the folder itself. If the folder contains any sub-folders, the sizes of messages in these subfolders will not be included into the returned value.
Examples
This sample attempts to gets the size of the currently used account storage using QUOTA extension. If QUOTA is not supported by the server, the sample selects all selectable folders in the account one by another, and calls GetFolderSize for each folder.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");

        long accountStorageUsedSize = -1;

        if (imp.GetExtension("QUOTA") != null)
        {
            // This may still return -1 if the QUOTA is supported
            // in general but storage quota in bytes is not.
            accountStorageUsedSize = imp.GetAccountQuota().CurrentStorageSize;
        }

        if (accountStorageUsedSize < 0)
        {
            // Fall back to a series of SelectFolder/GetFolderSize calls.
            accountStorageUsedSize = 0;
            FolderCollection folders = imp.DownloadFolders();

            foreach (Folder fold in folders)
            {
                // For each selectable folder, select it and
                // determine the total size of all messages.
                if ((fold.Flags & FolderFlags.Noselect) == 0)
                {
                    imp.SelectFolder(fold.Name);
                    accountStorageUsedSize += imp.GetFolderSize();
                }
            }
        }

        Console.WriteLine("Currently used account storage size is " +
            accountStorageUsedSize + " bytes");

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")

        Dim accountStorageUsedSize As Long = -1

        If Not imp.GetExtension("QUOTA") Is Nothing Then
            ' This may still return -1 if the QUOTA is supported
            ' in general but storage quota in bytes is not.
            accountStorageUsedSize = imp.GetAccountQuota().CurrentStorageSize
        End If

        If accountStorageUsedSize < 0 Then
            ' Fall back to a series of SelectFolder/GetFolderSize calls.
            accountStorageUsedSize = 0
            Dim folders As FolderCollection = imp.DownloadFolders()

            For Each fold As Folder In folders
                ' For each selectable folder, select it and
                ' determine the total size of all messages.
                If (fold.Flags And FolderFlags.Noselect) = 0 Then
                    imp.SelectFolder(fold.Name)
                    accountStorageUsedSize += imp.GetFolderSize()
                End If
            Next
        End If

        Console.WriteLine("Currently used account storage size is " & _
            accountStorageUsedSize & " bytes")

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetFolderSizeAsync Method

ImapGetFolderSizeAsync Method
async/await version of GetFolderSize.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<long> GetFolderSizeAsync()
Public Function GetFolderSizeAsync As Task(Of Long)

Return Value

Type: Task Int64
A task that represents the asynchronous operation. On success, the value of TResult parameter is the total size occupied by all messages in this folder; otherwise, -1.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetFolderStatus Method

ImapGetFolderStatus Method
Gets the status of the specified folder without selecting it.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public FolderStatus GetFolderStatus(
    string folderName
)
Public Function GetFolderStatus (
    folderName As String
) As FolderStatus

Parameters

folderName
Type: SystemString
The full name of the folder to get the status information of.

Return Value

Type: FolderStatus
FolderStatus object if the status information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method can be used to obtain the folder status information such as total count of messages, recent messages count, unseen messages count, etc without selecting the folder.
Examples
This sample gets Inbox status information and displays unseen messages count. No folder is selected.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
     static void Main(string[] args)
     {
         Imap imp = new Imap();

            // Connect to the server and log in the account.
            imp.Connect("imap.server.com");
            imp.Login("jdoe@server.com", "secret");

            // Download Inbox folder status information.
            FolderStatus status = imp.GetFolderStatus("Inbox");

            Console.WriteLine(status.UnseenCount + " unseen message(s) in inbox");

            imp.Disconnect();
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Download Inbox folder status information.
        Dim status As FolderStatus = imp.GetFolderStatus("Inbox")

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetFolderStatusAsync Method

ImapGetFolderStatusAsync Method
async/await version of GetFolderStatus(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<FolderStatus> GetFolderStatusAsync(
    string folderName
)
Public Function GetFolderStatusAsync (
    folderName As String
) As Task(Of FolderStatus)

Parameters

folderName
Type: SystemString
The full name of the folder for which to get the status information.

Return Value

Type: Task FolderStatus
A task that represents the asynchronous operation. The value of TResult parameter is FolderStatus object if the status information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetNamespaces Method

ImapGetNamespaces Method
Downloads the list of IMAP4 namespaces available for the currently logged mail user.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapNamespaceCollectionSet GetNamespaces()
Public Function GetNamespaces As ImapNamespaceCollectionSet

Return Value

Type: ImapNamespaceCollectionSet
ImapNamespaceCollectionSet object if the namespaces information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeProtocolExtensionNotSupportedException | NAMESPACE not supported by the server and ThrowExceptions is true.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

IMAP4 namespaces (if supported by your mail server) define prefixes you need to prepend folder names with when accessing folders of certain type (like Shared or Other Users' folders). Personal folders usually have no prefix but this can be different sometimes (usually, when more than one group of personal folders is available). Anyway, MailBee returns prefixes for all types of namespaces.

Typical prefixes most commonly used by mail servers are: "" (empty string) for Personal, "~" for Other Users', "~public/" or "#" for Shared folders. This way, when you use no prefix (empty string), you automatically use Personal folders.

Of course, the server returns namespace information which is only relevant to the given mail user. For instance, if the currently logged mail user does not have permission to access any Other Users' or Shared folders, the server won't return any information for these types of namespaces, and the corresponding properties of the returned ImapNamespaceCollectionSet object will be a null reference. This is not an error.

Note Note
It's not necessarily required to issue GetNamespaces command prior to selecting or other use of namespaces in folder names. If you already know the namespace without GetNamespaces call, you can immediately use that namespace in folder names.

To make sure the server does support namespaces, it's recommended to check this with GetExtension(String) method passing NAMESPACE as a value, prior to calling GetNamespaces. If NAMESPACE is not supported, this means only Personal folders are available, and the prefix is an empty string. Keep in mind that GetExtension(String) method doesn't make any extra requests to the IMAP server, therefore using it to check if the server supports any extension is always safe and won't degrade performance at all.

Also, note that even if the server lists certain namespace in the returned value, it does not yet mean you can actually select folders in that namespace because there may be none (empty namespace without any folders which belong to it). On other hand, the currently logged user may have access rights to select certain folder of another account but the server may not indicate this in the returned namespace results. This is all up to the server to decide. See the sample code below on how to find out which public folders are actually available to the currently logged mail user.

Examples
This sample downloads the list of all namespaces available for the given IMAP account. Then, it checks if that list of namespaces includes any Public (also known as Shared) namespaces. If yes, it uses this namespace name to download the list of all folders in that Public namespace (if there is more than one Public namespace, the last in the Public list is being used). Then, the sample picks the first folder in the downloaded Public folders list, selects this folder and reports the number of messages in it.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // When deal with selecting folders obtained from the results of DownloadFolders,
        // it's better to use this mode. This works around an ambiguity problem when
        // IMAP folder name contains international characters which are not UTF-7M encoded.
        // This is not specific to namespaces, it's just a better way to work with folder names.
        imp.Utf7EncodeFolderNames = false;

        // Log file can be useful for debugging.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        imp.Connect("mail.server.com", 143);
        imp.Login("user", "password");

        // IMAP namespace prefix. Empty value usually denotes Personal namespace which
        // is always available (when you specify no prefix, you in fact specify empty
        // prefix and thus select Personal namespace).
        string prefix = string.Empty;

        if (imp.GetExtension("NAMESPACE") == null)
        {
            Console.WriteLine("Unlucky you. This server does not support NAMESPACE extension.");
        }
        else
        {
            // Get the last namespace in the list of available Public (Shared) namespaces.
            // Usually, there is only one or none at all.
            ImapNamespaceCollectionSet namespaceSet = imp.GetNamespaces();
            if (namespaceSet.Shared != null)
            {
                foreach (ImapNamespace ns in namespaceSet.Shared)
                {
                    if (ns != null)
                    {
                        prefix = ns.Prefix;
                    }
                }
            }

            if (prefix == string.Empty)
            {
                Console.WriteLine("Namespace for public folders not set, will use a personal folder");
            }

            // This syntax lists all the folders in the given namespace.
            FolderCollection folders = imp.DownloadFolders(false, null, prefix + "%");

            if (folders.Count > 0)
            {
                // Select the first folder from the retured list of public folders.
                // We do not need to prepend names with the prefix here because the server
                // always returns folder names with the prefix already contained in them.
                // Also note using RawName (not Name) when selecting a folder (this works
                // around issues with international folder names which are not UTF-7M encoded).
                imp.SelectFolder(folders[0].RawName);
                Console.WriteLine(imp.MessageCount.ToString() + " message(s) in " + folders[0].Name + " folder");
            }
            else
            {
                Console.WriteLine("No folders found in the public namespace");
            }
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' When deal with selecting folders obtained from the results of DownloadFolders,
        ' it's better to use this mode. This works around an ambiguity problem when
        ' IMAP folder name contains international characters which are not UTF-7M encoded.
        ' This is not specific to namespaces, it's just a better way to work with folder names.
        imp.Utf7EncodeFolderNames = False

        ' Log file can be useful for debugging.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        imp.Connect("mail.server.com", 143)
        imp.Login("user", "password")

        ' IMAP namespace prefix. Empty value usually denotes Personal namespace which
        ' is always available (when you specify no prefix, you in fact specify empty
        ' prefix and thus select Personal namespace).
        Dim prefix As String = String.Empty

        If imp.GetExtension("NAMESPACE") Is Nothing Then
            Console.WriteLine("Unlucky you. This server does not support NAMESPACE extension.")
        Else
            ' Get the last namespace in the list of available Public (Shared) namespaces.
            ' Usually, there is only one or none at all.
            Dim namespaceSet As ImapNamespaceCollectionSet = imp.GetNamespaces()
            If Not namespaceSet.Shared Is Nothing Then
                Dim ns As ImapNamespace
                For Each ns In namespaceSet.Shared
                    If Not ns Is Nothing Then
                        prefix = ns.Prefix
                    End If
                Next
            End If

            If prefix = String.Empty Then
                Console.WriteLine("Namespace for public folders not set, will use a personal folder")
            End If

            ' This syntax lists all the folders in the given namespace.
            Dim folders As FolderCollection = imp.DownloadFolders(False, Nothing, prefix + "%")

            If folders.Count > 0 Then
                ' Select the first folder from the retured list of public folders.
                ' We do not need to prepend names with the prefix here because the server
                ' always returns folder names with the prefix already contained in them.
                ' Also note using RawName (not Name) when selecting a folder (this works
                ' around issues with international folder names which are not UTF-7M encoded).
                imp.SelectFolder(folders(0).RawName)
                Console.WriteLine(imp.MessageCount.ToString() + " message(s) in " + folders(0).Name + " folder")
            Else
                Console.WriteLine("No folders found in the public namespace")
            End If
        End If

        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetNamespacesAsync Method

ImapGetNamespacesAsync Method
async/await version of GetNamespaces.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<ImapNamespaceCollectionSet> GetNamespacesAsync()
Public Function GetNamespacesAsync As Task(Of ImapNamespaceCollectionSet)

Return Value

Type: Task ImapNamespaceCollectionSet
A task that represents the asynchronous operation. The value of TResult parameter is ImapNamespaceCollectionSet object if the namespaces information was downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetServerResponse Method

ImapGetServerResponse Method
Returns the last response from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetServerResponse()
Public Function GetServerResponse As String

Return Value

Type: String
A string value which contains the last response from the server, or a null reference (Nothing in Visual Basic) if not connected to the server.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetServerResponses Method

ImapGetServerResponses Method
Returns the specified individual responses from the last group of responses received from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GetServerResponses(
    string responseName
)
Public Function GetServerResponses (
    responseName As String
) As String()

Parameters

responseName
Type: SystemString
The name (case-insensitive) of the individual responses to be returned, or a null reference (Nothing in Visual Basic) if all available responses should be returned.

Return Value

Type: String
Array of strings containing the responses with the given name, or an empty array if not connected to the server.
Remarks

The IMAP4 server may return multiple responses to a single request from the client. While GetServerResponse method returns the very last response, GetServerResponses(String) method can be used to obtain any of the responses returned as the result of the last executed command.

The typical names of IMAP4 responses are: OK, BAD, FETCH, SEARCH, LIST, etc. This method can return both tagged and untagged responses. See the IMAP4 protocol specification (RFC3501) for more information regarding IMAP4 responses.

Note Note
Some items in the returned array can be a null reference (Nothing in Visual Basic) if their corresponding responses were considered large (a downloaded e-mail or envelope) and removed from memory to avoid wasting resources. This is applicable only to FETCH responses containing message envelope data. Unilateral FETCH responses won't be removed.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetSocket Method

ImapGetSocket Method
Returns the underlying Socket MailBee uses for the current network connection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Socket GetSocket()
Public Function GetSocket As Socket

Return Value

Type: Socket
A reference to the underlying Socket MailBee uses for the current network connection, or a null reference (Nothing in Visual Basic) if there is no active connection.
Remarks
In case of UWP edition, this method returns StreamSocket instead.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetSocketError Method

ImapGetSocketError Method
Returns a Win32 error code of the last socket-related error.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetSocketError()
Public Function GetSocketError As Integer

Return Value

Type: Int32
An integer value containing the last socket-related error code, or 0 if there is no error.
Remarks
This error code is obtained from NativeErrorCode.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetSpecialFolder Method

ImapGetSpecialFolder Method
Gets a reference to the special folder of the specified kind.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Folder GetSpecialFolder(
    FolderCollection folders,
    FolderFlags flag
)
Public Function GetSpecialFolder (
    folders As FolderCollection,
    flag As FolderFlags
) As Folder

Parameters

folders
Type: MailBee.ImapMailFolderCollection
A reference to the list of all folders in the IMAP account.
flag
Type: MailBee.ImapMailFolderFlags
The special folder kind.

Return Value

Type: Folder
A reference to the special folder, or a null reference (Nothing in Visual Basic) if no such folder was found in the provided list.
Remarks

This method itself does not make any network queries, it operates on an already retrieved folder list. To get the folder list, use DownloadFolders method.

Once you got the folder, you can use its Name for other operations (like SelectFolder(String), UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult), etc). Or, if you need to deal with international folder names, it's better to set Utf7EncodeFolderNames to false and pass RawName instead

Note Note
If the server does not support special folder flags, this method can be useless. The IMAP server must support SPECIAL-USE or XLIST extension for this to work.
Examples
This sample downloads the folders, then finds Sent Items folder and uploads a message there.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Logging is cool for debugging.
        imp.Log.Enabled = true;
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Clear();

        // Connect/login.
        imp.Connect("imap.server.com");
        imp.Login("user@domain", "password");

        // Create a message and fill it with some values (omitted for brevity).
        MailMessage msg = new MailMessage();

        // Get folders.
        FolderCollection fc = imp.DownloadFolders();

        Folder f = imp.GetSpecialFolder(fc, FolderFlags.Sent);
        if (f != null)
        {
            // Upload a message into Sent Items folder. Folder names can be international.
            imp.Utf7EncodeFolderNames = false;
            imp.UploadMessage(msg, f.RawName, SystemMessageFlags.Seen);
        }
        imp.Disconnect();
    }
}
Imports MailBee
Imports MailBee.Mime
Imports MailBee.ImapMail

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim imp As New Imap()

        ' Logging is cool for debugging.
        imp.Log.Enabled = True
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Clear()

        ' Connect/login.
        imp.Connect("imap.server.com")
        imp.Login("user@domain", "password")

        ' Create a message and fill it with some values (omitted for brevity).
        Dim msg As New MailMessage()

        ' Get folders.
        Dim fc As FolderCollection = imp.DownloadFolders()

        Dim f As Folder = imp.GetSpecialFolder(fc, FolderFlags.Sent)
        If f IsNot Nothing Then
            ' Upload a message into Sent Items folder. Folder names can be international.
            imp.Utf7EncodeFolderNames = False
            imp.UploadMessage(msg, f.RawName, SystemMessageFlags.Seen)
        End If
        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetStream Method

ImapGetStream Method
Returns the underlying Stream MailBee uses for the current network connection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Stream GetStream()
Public Function GetStream As Stream

Return Value

Type: Stream
A reference to the underlying Stream MailBee uses for the current network connection, or a null reference (Nothing in Visual Basic) if there is no active connection.
Remarks
Typically this will be an instance of a class inherited from NetworkStream or SslStream.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.GetSupportedAuthMethods Method

ImapGetSupportedAuthMethods Method
Returns a set of flags indicating which authentication methods are supported by the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods GetSupportedAuthMethods()
Public Function GetSupportedAuthMethods As AuthenticationMethods

Return Value

Type: AuthenticationMethods
A set of flags indicating which authentication methods are supported by the server.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the IMAP4 server advertises LOGINDISABLED capability, regular authentication may not be supported by the server. However, this often indicates the client should call StartTls method to establish TLS/SSL secure connection. After that, regular authentication option will become available.
Examples
This sample indicates whether NTLM authentication (also known as Secure Password Authentication - SPA) is supported by the server.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
AuthenticationMethods authMethods = imp.GetSupportedAuthMethods();

if ((authMethods & AuthenticationMethods.SaslNtlm) > 0)
{
    Console.WriteLine("NTLM secure authentication (SPA) is supported");
}
else
{
    Console.WriteLine("The IMAP4 server does not support NTLM (SPA)");
}
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
Dim authMethods As AuthenticationMethods = imp.GetSupportedAuthMethods()

If ((authMethods And AuthenticationMethods.SaslNtlm) > 0) Then
    Console.WriteLine("NTLM secure authentication (SPA) is supported")
Else
    Console.WriteLine("The IMAP4 server does not support NTLM (SPA)")
End If
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapGetExtensions


Imap.Idle Method

ImapIdle Method
Attempts to start idling mode which makes the client wait for any notifications from the server regarding the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Idle()
Public Function Idle As Boolean

Return Value

Type: Boolean
true if idling was finished successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Once idling mode has started, MailBee will wait for any responses from the server until StopIdle method has been called. The developer can use idling to monitor the current state of the folder and keep track of new or amended messages in the folder. Usually, the application listens to MessageStatus and ServerStatus events for this. Also, the application can listen to Idling event (which is raised 100 times per second) for performing any background activities if needed.

This topic has a very simple code example of IDLE. You can find more advanced sample at http://www.afterlogic.com/files/IdleSample.zip (http://www.afterlogic.com/files/IdleAsyncSample.zip for .NET 4.5+ async version).

Read more on IMAP IDLE and polling in Getting notifications about new messages in mailbox article.

Note Note
The mail server must support idling ("idle" capability must be listed in GetExtensions results). IDLE extension is described in RFC 2177 document.
Examples
This WinForms sample demonstrates using IDLE. The sample also takes care of checking if IDLE is supported by the server, stoppping idling if requested or if the application is closed by the user. In order to run this sample, please put button1 button on the form and attach Form1_Closing method to Closing event of the form.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// Imap object declared global because it's accessed from several methods.
Imap imp = null;

bool finished = false;
bool started = false;

// Idling event is used to keep UI responsive and stop idling is desired.
private void imp_Idling(object sender, ImapIdlingEventArgs e)
{
    Application.DoEvents();
    if (finished)
    {
        ((Imap)sender).StopIdle();
        button1.Text = "Go idle";
    }
}

// Monitor folder changes and save them in the log file.
private void imp_MessageStatus(object sender, ImapMessageStatusEventArgs e)
{
    ((Imap)sender).Log.WriteLine("Got " + e.StatusID + " status update");
}

// Start/stop idling.
// Add button1 on the form to make this sample working.
private void button1_Click(object sender, System.EventArgs e)
{
    if (started)
    {
        finished = true;
    }
    else
    {
        started = true;

        imp = new Imap();

        // Enable logging into a file.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Connect to the server and check if IDLE is supported.
        imp.Connect("mail.domain.com");
        if (imp.GetExtension("IDLE") == null)
        {
            MessageBox.Show("IDLE not supported");
        }
        else
        {
            // Login and select inbox.
            imp.Login("jdoe", "secret");
            imp.SelectFolder("Inbox");

            // Attach event handlers.
            imp.Idling += new ImapIdlingEventHandler(imp_Idling);
            imp.MessageStatus +=new ImapMessageStatusEventHandler(imp_MessageStatus);

            button1.Text = "Stop idle";

            // Go idle. This call will block until imp.StopIdle()
            // is called from elsewhere.
            imp.Idle();
        }

        // Disconnect from the server.
        imp.Disconnect();

        started = false;
        finished = false;
    }
}

// Finish idling if the user closes the application.
// To make this method work, attach it to Closing event of the form.
private void Form1_Closing(object sender,
    System.ComponentModel.CancelEventArgs e)
{
    if (imp != null && imp.IsBusy)
    {
        imp.StopIdle();
    }
}
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

' Imap object declared global because it's accessed from several methods.
Dim imp As Imap = Nothing

Dim finished As Boolean = False
Dim started As Boolean = False

' Idling event is used to keep UI responsive and stop idling is desired.
Private Sub imp_Idling(ByVal sender As Object, ByVal e As ImapIdlingEventArgs)
    Application.DoEvents()
    If finished Then
        CType(sender, Imap).StopIdle()
        button1.Text = "Go idle"
    End If
End Sub

' Monitor folder changes and save them in the log file.
Private Sub imp_MessageStatus(ByVal sender As Object, ByVal e As ImapMessageStatusEventArgs)
    CType(sender, Imap).Log.WriteLine("Got " & e.StatusID & " status update")
End Sub

' Start/stop idling.
' Add button1 on the form to make this sample working.
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    If started Then
        finished = True
    Else
        started = True

        imp = New Imap

        ' Enable logging into a file.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Connect to the server and check if IDLE is supported.
        imp.Connect("mail.domain.com")
        If imp.GetExtension("IDLE") Is Nothing Then
            MessageBox.Show("IDLE not supported")
        Else
            ' Login and select inbox.
            imp.Login("jdoe", "secret")
            imp.SelectFolder("Inbox")

            ' Attach event handlers.
            AddHandler imp.Idling, AddressOf imp_Idling
            AddHandler imp.MessageStatus, AddressOf imp_MessageStatus

            button1.Text = "Stop idle"

            ' Go idle. This call will block until imp.StopIdle()
            ' is called from elsewhere.
            imp.Idle()
        End If

        ' Disconnect from the server.
        imp.Disconnect()

        started = False
        finished = False
    End If
End Sub

' Finish idling if the user closes the application.
' To make this method work, attach it to Closing event of the form.
Private Sub Form1_Closing(ByVal sender As Object, _
    ByVal e As System.ComponentModel.CancelEventArgs)
    If Not imp Is Nothing And imp.IsBusy Then
        imp.StopIdle()
    End If
End Sub
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapStopIdle
ImapIdling
ImapMessageStatus
ImapServerStatus


Imap.IdleAsync Method

ImapIdleAsync Method
async/await version of Idle.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> IdleAsync()
Public Function IdleAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
You can find an advanced sample at http://www.afterlogic.com/files/IdleAsyncSample.zip.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Login Method

ImapLogin Method
Overload List
Name | Description
Login(String, String) | Logs in a mail account on the IMAP4 server.
Login(String, String, AuthenticationMethods) | Logs in a mail account on the IMAP4 server.
Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mail account on the IMAP4 server.
Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mail account on the IMAP4 server.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Login Method (String, String)

ImapLogin Method (String, String)
Logs in a mail account on the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string accountName,
    string password
)
Public Function Login (
    accountName As String,
    password As String
) As Boolean

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method will try to authenticate using the best (the most secure) authentication method supported by the server, but will downgrade to less secure methods (to the simplest "LOGIN account password" authentication in the worst case) if better methods are not available.

You can also force using a particular authentication method with Login(String, String, AuthenticationMethods) overload passing a method like Regular.

Note Note
If SafeMode is true, MailBee will use the simplest "LOGIN account password" authentication by default (Regular option). This can often help to troubleshoot login problems (some mail servers implement secure authentication methods incorrectly).
To use OAuth 2.0 authentication (XOAUTH2 in Gmail), see the example in OAuth2 topic.
Examples
This sample connects to an IMAP4 server, logs in a user account, selects Inbox folder, and displays the total number of messages in this folder.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("jdoe", "secret");
imp.SelectFolder("INBOX");
Console.WriteLine(imp.MessageCount + " message(s) in inbox");
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
imp.Login("jdoe", "secret")
imp.SelectFolder("INBOX")
Console.WriteLine(imp.MessageCount & " message(s) in inbox")
imp.Disconnect()
See Also

Reference

Imap Class
Login Overload
MailBee.ImapMail Namespace


Imap.Login Method (String, String, AuthenticationMethods)

ImapLogin Method (String, String, AuthenticationMethods)
Logs in a mail account on the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string accountName,
    string password,
    AuthenticationMethods authMethods
)
Public Function Login (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods
) As Boolean

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Authentication methods are tried from more secure to less secure. If authMethods is set to Auto, MailBee will try to use the most secure method supported by the server but will downgrade to less secure methods (to the simplest "LOGIN account password" authentication in the worst case) if better methods are not available.

To use OAuth 2.0 authentication (XOAUTH2 in Gmail), see the example in OAuth2 topic.

Examples
This sample connects to an IMAP4 server and logs in a user account using secure authentication methods only. Use of insecure methods is not allowed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("jdoe@domain.com", "secret", AuthenticationMethods.SaslCramMD5 | AuthenticationMethods.SaslNtlm);
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
imp.Login("jdoe@domain.com", "secret", AuthenticationMethods.SaslCramMD5 Or AuthenticationMethods.SaslNtlm)
imp.Disconnect()
See Also

Reference

Imap Class
Login Overload
MailBee.ImapMail Namespace


Imap.Login Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

ImapLogin Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
Logs in a mail account on the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function Login (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Boolean

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

By default, MailBee won't even try to use authentication methods which are not listed by the server in its capabilities. This behavior can be changed by setting TryUnsupportedMethods bit in authOptions. If, during the authentication attempt, the server reports that the method is unsupported, MailBee will try the next method in authMethods until the compatible method is found or no more methods left. This behavior can be changed by setting UseSingleMethodOnly bit in authOptions.

Authentication methods are tried from more secure to less secure. If authMethods is set to Auto and authOptions is None, MailBee will try to use the most secure method supported by the server but will downgrade to less secure methods (to the simplest "LOGIN account password" authentication in the worst case) if better methods are not available. However, if the IMAP4 server prohibits using LOGIN command (LOGINDISABLED extension is enabled), regular authentication option won't be available.

To use OAuth 2.0 authentication (XOAUTH2 in Gmail), see the example in OAuth2 topic.

Examples
This sample connects to an IMAP4 server and attempts to log in a user account using SASL NTLM method in Integrated Windows Authentication mode (passing credentials of the currently logged Windows user) even if NTLM is not listed in the server capabilities (the server may still support NTLM while not advertising this). Use of other authentication methods is not allowed by this sample (they do not support obtaining the current Windows user's credentials and thus will raise exception is empty credentials are supplied by the caller).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login(null, null, AuthenticationMethods.SaslNtlm, AuthenticationOptions.TryUnsupportedMethods, null);
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
imp.Login(Nothing, Nothing, AuthenticationMethods.SaslNtlm, AuthenticationOptions.TryUnsupportedMethods, Nothing)
imp.Disconnect()
See Also

Reference

Imap Class
Login Overload
MailBee.ImapMail Namespace
MailBeeSaslMethod


Imap.Login Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

ImapLogin Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
Logs in a mail account on the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string targetName,
    string domain,
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function Login (
    targetName As String,
    domain As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Boolean

Parameters

targetName
Type: SystemString
The Service Principal Name (SPN) of the IMAP4 server. Only used with GSSAPI authentication method. If an empty string, NTLM method will be used for GSSAPI. If a null reference (Nothing in Visual Basic), MailBee will autodetect SPN as "IMAP/serverName" and use Kerberos for GSSAPI. If set to a non-empty string, MailBee will also select Kerberos for GSSAPI and use this value as SPN.
domain
Type: SystemString
The user account domain on the server. Only used with NTLM and GSSAPI authentication methods. You can leave it a null reference to use the current domain.
accountName
Type: SystemString
The user account name on the server (can be empty for NTLM and GSSAPI).
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Use this overload if you need to authenticate with NTLM and GSSAPI (usually, against MS Exchange or MS IIS) and need to explicitly specify user domain or custom SPN. For other cases, you can use simpler overloads.
Examples
This sample connects to an IMAP4 server and attempts to log in a user account using SASL GSSAPI method in Integrated Windows Authentication mode and NTLM is selected as the underlying implementation because targetName is an empty string.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
imp.Login("", null, null, null, AuthenticationMethods.SaslGssApi, AuthenticationOptions.TryUnsupportedMethods, null);
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
imp.Login("", Nothing, Nothing, Nothing, AuthenticationMethods.SaslGssApi, AuthenticationOptions.TryUnsupportedMethods, Nothing)
imp.Disconnect()
See Also

Reference

Imap Class
Login Overload
MailBee.ImapMail Namespace
MailBeeSaslMethod


Imap.LoginAsync Method

ImapLoginAsync Method
Overload List
 | Name | Description
Public method | LoginAsync(String, String) | async/await version of Login(String, String).
Public method | LoginAsync(String, String, AuthenticationMethods) | async/await version of Login(String, String, AuthenticationMethods).
Public method | LoginAsync(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Public method | LoginAsync(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.LoginAsync Method (String, String)

ImapLoginAsync Method (String, String)
async/await version of Login(String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string accountName,
    string password
)
Public Function LoginAsync (
    accountName As String,
    password As String
) As Task(Of Boolean)

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
LoginAsync Overload
MailBee.ImapMail Namespace


Imap.LoginAsync Method (String, String, AuthenticationMethods)

ImapLoginAsync Method (String, String, AuthenticationMethods)
async/await version of Login(String, String, AuthenticationMethods).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string accountName,
    string password,
    AuthenticationMethods authMethods
)
Public Function LoginAsync (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods
) As Task(Of Boolean)

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
LoginAsync Overload
MailBee.ImapMail Namespace


Imap.LoginAsync Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

ImapLoginAsync Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function LoginAsync (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Task(Of Boolean)

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
LoginAsync Overload
MailBee.ImapMail Namespace


Imap.LoginAsync Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

ImapLoginAsync Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string targetName,
    string domain,
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function LoginAsync (
    targetName As String,
    domain As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Task(Of Boolean)

Parameters

targetName
Type: SystemString
The Service Principal Name (SPN) of the IMAP4 server. Only used with GSSAPI authentication method. If an empty string, NTLM method will be used for GSSAPI. If a null reference (Nothing in Visual Basic), MailBee will autodetect SPN as "IMAP/serverName" and use Kerberos for GSSAPI. If set to a non-empty string, MailBee will also select Kerberos for GSSAPI and use this value as SPN.
domain
Type: SystemString
The user account domain on the server. Only used with NTLM and GSSAPI authentication methods. You can leave it a null reference to use the current domain.
accountName
Type: SystemString
The user account name on the server (can be empty for NTLM and GSSAPI).
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
LoginAsync Overload
MailBee.ImapMail Namespace


Imap.MoveMessages Method

ImapMoveMessages Method
Overload List
Name | Description
MoveMessages(String, Boolean, String) | Moves the specified messages from the currently selected folder to the specified folder.
MoveMessages(String, Boolean, String, UidPlusResult) | Moves the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the moved messages in the destination folder.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.MoveMessages Method (String, Boolean, String)

ImapMoveMessages Method (String, Boolean, String)
Moves the specified messages from the currently selected folder to the specified folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MoveMessages(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName
)
Public Function MoveMessages (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.

Return Value

Type: Boolean
true if the messages were moved successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

Note Note
The IMAP4 protocol might not directly support moving messages between folders (unless the server supports MOVE extension). If MOVE command is not supported by the server, MailBee emulates moving messages as a sequence of copying, marking copied messages as deleted in the source folder, and then expunging deleted messages. You can find more detailed description of this process in MoveMessages(String, Boolean, String, UidPlusResult) overload topic.
Examples

This sample moves all seen (already read) messages from the Inbox folder into the Archive folder.

The sample assumes "Archive" folder had already been created in the past. To learn how to make sure the folder exists, see UploadMessage(MailMessage, String, String, DateTime) or UploadMessage(MailMessage, String, String, String) samples.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.server.com");
        imp.Login("jdoe@server.com", "secret");
        imp.SelectFolder("INBOX");

        // Find all messages which are already read.
        UidCollection uids = (UidCollection)imp.Search(true, "SEEN", null);

        if (uids.Count > 0)
        {
            // Move all SEEN messages into Archive.
            imp.MoveMessages(uids.ToString(), true, "Archive");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.somehost.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Find all messages which are already read.
        Dim uids As UidCollection = CType(imp.Search(True, "SEEN", Nothing), UidCollection)

        If uids.Count > 0 Then
            ' Move all SEEN messages into Archive.
            imp.MoveMessages(uids.ToString(), True, "Archive")
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MoveMessages Overload
MailBee.ImapMail Namespace
ImapCopyMessages(String, Boolean, String, UidPlusResult)


Imap.MoveMessages Method (String, Boolean, String, UidPlusResult)

ImapMoveMessages Method (String, Boolean, String, UidPlusResult)
Moves the specified messages from the currently selected folder to the specified folder, and retrieves UIDs assigned to the moved messages in the destination folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MoveMessages(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName,
    UidPlusResult result
)
Public Function MoveMessages (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String,
    result As UidPlusResult
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the move operation reported by UIDPLUS enabled server (the outcome includes the UIDs of the source messages being moved, the UIDs assigned to the moved messages in the destination folder, and the UIDVALIDITY of the destination folder), or a null reference (Nothing in Visual Basic) if the application does not need this information.

Return Value

Type: Boolean
true if the messages were moved successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

When result is specified and the server supports UIDPLUS extension, CopyMessages(String, Boolean, String, UidPlusResult) method will set the supplied UidPlusResult object properties as below:

Property | Value
IsValid | true
IsSupported | true
SrcUids | The UidCollection object containing the UIDs of the messages which had been moved from the source folder.
SrcUidString | The string containing the message sequence of UIDs of the messages which had been moved from the source folder.
DestUids | The UidCollection object containing the UIDs assigned to the moved messages in targetFolderName folder.
DestUidString | The string containing the message sequence of UIDs assigned to the moved messages in targetFolderName folder.
DestUidValidity | The UIDVALIDITY of the targetFolderName folder.
If UIDPLUS capability is not supported by the server, IsSupported will be set to false.

Note Note
The IMAP4 protocol might not directly support moving messages between folders (unless the server supports MOVE extension). If MOVE command is not supported by the server, MailBee emulates moving messages as a sequence of copying, marking copied messages as deleted in the source folder, and then expunging deleted messages. This operation performs quicker when the server supports UIDPLUS extension (because UIDPLUS allows the client to expunge specific "\Deleted" messages rather than all such messages in the folder). If UIDPLUS is not supported, it takes a bit longer to move messages since MailBee needs to preserve messages which have already had "\Deleted" flag set to the moment when MoveMessages(String, Boolean, String, UidPlusResult) method started. If MailBee just expunged the deleted messages from the folder, this would affect not only messages being copied but rather all messages which have already had "\Deleted" flag set. MailBee avoids this by temporary removing "\Deleted" flag from the messages which have already had this flag, and then restoring this flag back when the moving completes. However, when all messages in the folder are being moved, it's not required to care about remaining messages. Thus, when UIDPLUS is not supported, moving all messages is performed in less count of steps than moving specific messages only. Again, all of the above only makes sense when MOVE command is not supported. With MOVE command, moving messages is fast and straight-forward process.
Examples
This sample moves the first message from the inbox folder to the Sent folder (it's assumed the Sent folder already exists and the inbox contains at least 1 message). The UIDs assigned to the moved messages in the destination folder is displayed if UIDPLUS capability is supported by the server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.somehost.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Prepare the object that will receive moving results.
        UidPlusResult res = new UidPlusResult();

        // Move the first message from Inbox into Sent.
        imp.MoveMessages("1", false, "Sent", res);

        if (res.IsSupported)
        {
            Console.WriteLine("UID assigned to the moved message is " +
                res.DestUidString);
        }
        else
        {
            Console.WriteLine("Sorry, UIDPLUS is not supported by the server");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.somehost.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Prepare the object that will receive moving results.
        Dim res As New UidPlusResult

        ' Move the first message from Inbox into Sent.
        imp.MoveMessages("1", False, "Sent", res)

        If res.IsSupported Then
            Console.WriteLine("UID assigned to the moved message is " & res.DestUidString)
        Else
            Console.WriteLine("Sorry, UIDPLUS is not supported by the server")
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MoveMessages Overload
MailBee.ImapMail Namespace
ImapCopyMessages(String, Boolean, String, UidPlusResult)


Imap.MoveMessagesAsync Method

ImapMoveMessagesAsync Method
Overload List
 | Name | Description
Public method | MoveMessagesAsync(String, Boolean, String) | async/await version of MoveMessages(String, Boolean, String).
Public method | MoveMessagesAsync(String, Boolean, String, UidPlusResult) | async/await version of MoveMessages(String, Boolean, String, UidPlusResult).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.MoveMessagesAsync Method (String, Boolean, String)

ImapMoveMessagesAsync Method (String, Boolean, String)
async/await version of MoveMessages(String, Boolean, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> MoveMessagesAsync(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName
)
Public Function MoveMessagesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MoveMessagesAsync Overload
MailBee.ImapMail Namespace


Imap.MoveMessagesAsync Method (String, Boolean, String, UidPlusResult)

ImapMoveMessagesAsync Method (String, Boolean, String, UidPlusResult)
async/await version of MoveMessages(String, Boolean, String, UidPlusResult).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> MoveMessagesAsync(
    string messageIndexSet,
    bool indexIsUid,
    string targetFolderName,
    UidPlusResult result
)
Public Function MoveMessagesAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    targetFolderName As String,
    result As UidPlusResult
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
targetFolderName
Type: SystemString
The full name of the destination folder.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the move operation reported by UIDPLUS enabled server (the outcome includes the UIDs of the source messages being moved, the UIDs assigned to the moved messages in the destination folder, and the UIDVALIDITY of the destination folder), or a null reference (Nothing in Visual Basic) if the application does not need this information.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MoveMessagesAsync Overload
MailBee.ImapMail Namespace


Imap.Noop Method

ImapNoop Method
Sends a NOOP command to the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Noop()
Public Function Noop As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method is useful for keeping the connection alive when there is no real activity.

To issue NOOP asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.NoopAsync Method

ImapNoopAsync Method
async/await version of Noop.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> NoopAsync()
Public Function NoopAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.OnConnected Method

ImapOnConnected Method
Used by MailBee to raise Connected event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnConnected(
    ConnectedEventArgs args
)
Protected Sub OnConnected (
    args As ConnectedEventArgs
)

Parameters

args
Type: MailBeeConnectedEventArgs
The object containing event data.
Remarks

When RaiseEventsViaMessageLoop is true (i.e. default value), MailBee uses this method to raise Connected event. In WinForms application, the event will be raised on the message loop thread. In other applications (such as web or console applications), threading is not a concern, and the current thread MailBee is running on will be used.

You can override this method in a derived class to force MailBee execute your own code instead of raising Connected event. This may help to avoid threading issues in WinForms applications (because events may not be raised if the message loop thread is blocked for some reason, while calling overridden methods does not depend on the message loop thread state).

Another solution of this problem is setting RaiseEventsViaMessageLoop to false and using Wait method to block the message loop thread if needed. This way, you do not need to derive any descendant class from Imap class.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapConnected
ImapRaiseEventsViaMessageLoop


Imap.OnDataReceived Method

ImapOnDataReceived Method
Used by MailBee to raise DataReceived event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDataReceived
ImapOnConnected(ConnectedEventArgs)


Imap.OnDataSent Method

ImapOnDataSent Method
Used by MailBee to raise DataSent event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataSent(
    DataTransferEventArgs args
)
Protected Sub OnDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDataSent
ImapOnConnected(ConnectedEventArgs)


Imap.OnDisconnected Method

ImapOnDisconnected Method
Used by MailBee to raise Disconnected event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDisconnected(
    DisconnectedEventArgs args
)
Protected Sub OnDisconnected (
    args As DisconnectedEventArgs
)

Parameters

args
Type: MailBeeDisconnectedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDisconnected
ImapOnConnected(ConnectedEventArgs)


Imap.OnEnvelopeDataChunkReceived Method

ImapOnEnvelopeDataChunkReceived Method
Used by MailBee to raise EnvelopeDataChunkReceived event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnEnvelopeDataChunkReceived(
    ImapEnvelopeDataChunkReceivedEventArgs args
)
Protected Sub OnEnvelopeDataChunkReceived (
    args As ImapEnvelopeDataChunkReceivedEventArgs
)

Parameters

args
Type: MailBee.ImapMailImapEnvelopeDataChunkReceivedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapEnvelopeDataChunkReceived
ImapOnConnected(ConnectedEventArgs)


Imap.OnEnvelopeDownloaded Method

ImapOnEnvelopeDownloaded Method
Used by MailBee to raise EnvelopeDownloaded event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnEnvelopeDownloaded(
    ImapEnvelopeDownloadedEventArgs args
)
Protected Sub OnEnvelopeDownloaded (
    args As ImapEnvelopeDownloadedEventArgs
)

Parameters

args
Type: MailBee.ImapMailImapEnvelopeDownloadedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapEnvelopeDownloaded
ImapOnConnected(ConnectedEventArgs)


Imap.OnErrorOccurred Method

ImapOnErrorOccurred Method
Used by MailBee to raise ErrorOccurred event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnErrorOccurred(
    ErrorEventArgs args
)
Protected Sub OnErrorOccurred (
    args As ErrorEventArgs
)

Parameters

args
Type: MailBeeErrorEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapErrorOccurred
ImapOnConnected(ConnectedEventArgs)


Imap.OnHostResolved Method

ImapOnHostResolved Method
Used by MailBee to raise HostResolved event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnHostResolved(
    HostResolvedEventArgs args
)
Protected Sub OnHostResolved (
    args As HostResolvedEventArgs
)

Parameters

args
Type: MailBeeHostResolvedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapHostResolved
ImapOnConnected(ConnectedEventArgs)


Imap.OnIdling Method

ImapOnIdling Method
Used by MailBee to raise Idling event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnIdling(
    ImapIdlingEventArgs args
)
Protected Sub OnIdling (
    args As ImapIdlingEventArgs
)

Parameters

args
Type: MailBee.ImapMailImapIdlingEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapServerStatus
ImapOnConnected(ConnectedEventArgs)


Imap.OnLoggedIn Method

ImapOnLoggedIn Method
Used by MailBee to raise LoggedIn event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLoggedIn(
    LoggedInEventArgs args
)
Protected Sub OnLoggedIn (
    args As LoggedInEventArgs
)

Parameters

args
Type: MailBeeLoggedInEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLoggedIn
ImapOnConnected(ConnectedEventArgs)


Imap.OnLogNewEntry Method

ImapOnLogNewEntry Method
Used by MailBee to raise LogNewEntry event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLogNewEntry(
    LogNewEntryEventArgs args
)
Protected Sub OnLogNewEntry (
    args As LogNewEntryEventArgs
)

Parameters

args
Type: MailBeeLogNewEntryEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLogNewEntry
ImapOnConnected(ConnectedEventArgs)


Imap.OnLowLevelDataReceived Method

ImapOnLowLevelDataReceived Method
Used by MailBee to raise LowLevelDataReceived event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLowLevelDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnLowLevelDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLowLevelDataReceived
ImapOnConnected(ConnectedEventArgs)


Imap.OnLowLevelDataSent Method

ImapOnLowLevelDataSent Method
Used by MailBee to raise LowLevelDataSent event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLowLevelDataSent(
    DataTransferEventArgs args
)
Protected Sub OnLowLevelDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLowLevelDataSent
ImapOnConnected(ConnectedEventArgs)


Imap.OnMessageStatus Method

ImapOnMessageStatus Method
Used by MailBee to raise MessageStatus event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageStatus(
    ImapMessageStatusEventArgs args
)
Protected Sub OnMessageStatus (
    args As ImapMessageStatusEventArgs
)

Parameters

args
Type: MailBee.ImapMailImapMessageStatusEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapMessageStatus
ImapOnConnected(ConnectedEventArgs)


Imap.OnServerStatus Method

ImapOnServerStatus Method
Used by MailBee to raise ServerStatus event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnServerStatus(
    ImapServerStatusEventArgs args
)
Protected Sub OnServerStatus (
    args As ImapServerStatusEventArgs
)

Parameters

args
Type: MailBee.ImapMailImapServerStatusEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapServerStatus
ImapOnConnected(ConnectedEventArgs)


Imap.OnSocketConnected Method

ImapOnSocketConnected Method
Used by MailBee to raise SocketConnected event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSocketConnected(
    SocketConnectedEventArgs args
)
Protected Sub OnSocketConnected (
    args As SocketConnectedEventArgs
)

Parameters

args
Type: MailBeeSocketConnectedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSocketConnected
ImapOnConnected(ConnectedEventArgs)


Imap.OnSocketCreating Method

ImapOnSocketCreating Method
Used by MailBee to raise SocketCreating event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSocketCreating(
    SocketCreatingEventArgs args
)
Protected Sub OnSocketCreating (
    args As SocketCreatingEventArgs
)

Parameters

args
Type: MailBeeSocketCreatingEventArgs
The object containing event data.
Remarks
See OnSocketCreating(SocketCreatingEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSocketCreating
ImapOnConnected(ConnectedEventArgs)


Imap.OnTlsStarted Method

ImapOnTlsStarted Method
Used by MailBee to raise TlsStarted event.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnTlsStarted(
    TlsStartedEventArgs args
)
Protected Sub OnTlsStarted (
    args As TlsStartedEventArgs
)

Parameters

args
Type: MailBeeTlsStartedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapTlsStarted
ImapOnConnected(ConnectedEventArgs)


Imap.QuickDownloadMessage Method

ImapQuickDownloadMessage Method
Overload List
Name | Description
QuickDownloadMessage(String, String, String, String, Int32) | Completely downloads the specified message from the specified folder on the server, in a single line of code.
QuickDownloadMessage(String, String, String, String, Int32, Int32) | Downloads the specified message (entire message or message header only) from the specified folder on the server, in a single line of code.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.QuickDownloadMessage Method (String, String, String, String, Int32)

ImapQuickDownloadMessage Method (String, String, String, String, Int32)
Completely downloads the specified message from the specified folder on the server, in a single line of code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessage QuickDownloadMessage(
    string serverName,
    string accountName,
    string password,
    string folderName,
    int messageNumber
)
Public Shared Function QuickDownloadMessage (
    serverName As String,
    accountName As String,
    password As String,
    folderName As String,
    messageNumber As Integer
) As MailMessage

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
folderName
Type: SystemString
The full name of the folder to download the message from.
messageNumber
Type: SystemInt32
The ordinal position of the message in the folder, starting at 1 (can be negative, i.e. -1 denotes the last e-mail in the inbox).

Return Value

Type: MailMessage
A MailMessage object containing the downloaded message (including the header and all the body parts and attachments).
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the folder.

An account on the mail server is guaranteed to contain at least "Inbox" folder. The "Inbox" name is case-sensitive ("Inbox", "inbox", and "INBOX" are equivalent). Other folder names, however, may be case-senstive depending on the server implementation.

The common use of this method is to quickly receive the message when its index in the folder is already known. For instance, QuickDownloadMessages(String, String, String, String, Int32) method was used to download headers for all messages in the folder and build the message list where the user can click a particular message to view it completely. Once the user selected the message to be viewed, the application passes its index in the message list as a value of messageNumber parameter of QuickDownloadMessage(String, String, String, String, Int32, Int32) method to download the selected message (if the message list index is zero-based, the developer should also add 1 to the messageNumber value).

Note Note
Static methods still require the valid license key be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEntireMessageAsync(Int64, Boolean).

Examples
This sample downloads the first message in the inbox and saves it as .EML file to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = Imap.QuickDownloadMessage("imap.domain.com",
    "login@domain.com", "password", "Inbox", 1);
msg.SaveMessage(@"C:\Temp\message.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As MailMessage = Imap.QuickDownloadMessage("imap.domain.com", _
    "login@domain.com", "password", "Inbox", 1)
msg.SaveMessage("C:\Temp\message.eml")
See Also

Reference

Imap Class
QuickDownloadMessage Overload
MailBee.ImapMail Namespace
ImapQuickDownloadMessages(String, String, String, String, Int32)


Imap.QuickDownloadMessage Method (String, String, String, String, Int32, Int32)

ImapQuickDownloadMessage Method (String, String, String, String, Int32, Int32)
Downloads the specified message (entire message or message header only) from the specified folder on the server, in a single line of code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessage QuickDownloadMessage(
    string serverName,
    string accountName,
    string password,
    string folderName,
    int messageNumber,
    int bodyPreviewSize
)
Public Shared Function QuickDownloadMessage (
    serverName As String,
    accountName As String,
    password As String,
    folderName As String,
    messageNumber As Integer,
    bodyPreviewSize As Integer
) As MailMessage

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
folderName
Type: SystemString
The full name of the folder to download the message from.
messageNumber
Type: SystemInt32
The ordinal position of the message in the folder, starting at 1 (can be negative, i.e. -1 denotes the last e-mail in the inbox).
bodyPreviewSize
Type: SystemInt32
Number of bytes of the message source body to download in addition to the message source header, or -1 to download the entire message, or 0 to download the message header only.

Return Value

Type: MailMessage
A MailMessage object containing the downloaded message.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the folder.

An account on the mail server is guaranteed to contain at least "Inbox" folder. The "Inbox" name is case-sensitive ("Inbox", "inbox", and "INBOX" are equivalent). Other folder names, however, may be case-senstive depending on the server implementation.

The common use of this method is to quickly receive the message when its index in the folder is already known. For instance, QuickDownloadMessages(String, String, String, String, Int32) method was used to download headers for all messages in the folder and build the message list where the user can click a particular message to view it completely. Once the user selected the message to be viewed, the application passes its index in the message list as a value of messageNumber parameter of QuickDownloadMessage(String, String, String, String, Int32, Int32) method to download the selected message (if the message list index is zero-based, the developer should also add 1 to the messageNumber value).

Note Note
Static methods still require the valid license key to be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32).

Examples

This sample partially downloads the first message in the inbox (the header and the first 1000 bytes of the message source body are downloaded), and displays preview of the plain-text body of the message. This may be useful if the entire message is very large, and the user wants to take a look at the beginning of the body text in order to decide whether to download the entire message.

If the message has HTML part but does not have plain-text part, the plain-text version will be generated automatically.

C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = Imap.QuickDownloadMessage("mail.server.com", "login", "password", "Inbox", 1, 1000);
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;
Console.WriteLine(msg.BodyPlainText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As MailMessage = Imap.QuickDownloadMessage("mail.server.com", "login", "password", "Inbox", 1, 1000)
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain
Console.WriteLine(msg.BodyPlainText)
See Also

Reference

Imap Class
QuickDownloadMessage Overload
MailBee.ImapMail Namespace
ImapQuickDownloadMessages(String, String, String, String, Int32)


Imap.QuickDownloadMessages Method

ImapQuickDownloadMessages Method
Overload List
Name | Description
QuickDownloadMessages(String, String, String, String) | Completely downloads all the messages in the specified folder on the server, in a single line of code.
QuickDownloadMessages(String, String, String, String, Int32) | Downloads all the messages (entire messages or message headers only) in the specified folder on the server, in a single line of code.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.QuickDownloadMessages Method (String, String, String, String)

ImapQuickDownloadMessages Method (String, String, String, String)
Completely downloads all the messages in the specified folder on the server, in a single line of code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessageCollection QuickDownloadMessages(
    string serverName,
    string accountName,
    string password,
    string folderName
)
Public Shared Function QuickDownloadMessages (
    serverName As String,
    accountName As String,
    password As String,
    folderName As String
) As MailMessageCollection

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
folderName
Type: SystemString
The full name of the folder to download the messages from.

Return Value

Type: MailMessageCollection
A MailMessageCollection object containing the downloaded messages.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the folder.

An account on the mail server is guaranteed to contain at least "Inbox" folder. The "Inbox" name is case-sensitive ("Inbox", "inbox", and "INBOX" are equivalent). Other folder names, however, may be case-senstive depending on the server implementation.

Since MailBee is capable of downloading multiple messages in a batch, using this method is much more efficient than calling QuickDownloadMessage(String, String, String, String, Int32, Int32) method multiple times.

Note Note
Static methods still require the valid license key be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEntireMessagesAsync(String, Boolean).

Examples
This sample downloads all the messages in the inbox, and displays the index (an ordinal position in the inbox) and the attachments count of each message which has any attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessageCollection msgs = Imap.QuickDownloadMessages("imap.host.com",
    "login", "password", "Inbox");
foreach (MailMessage msg in msgs)
{
    if (msg.HasAttachments)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer +
            " has " + msg.Attachments.Count + " attachment(s)");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msgs As MailMessageCollection = Imap.QuickDownloadMessages("imap.host.com", _
    "login", "password", "Inbox")

For Each msg As MailMessage In msgs
    If msg.HasAttachments Then
        Console.WriteLine("Message #" & msg.IndexOnServer & " has " & _
            msg.Attachments.Count & " attachment(s)")
    End If
Next
See Also

Reference

Imap Class
QuickDownloadMessages Overload
MailBee.ImapMail Namespace
ImapQuickDownloadMessage(String, String, String, String, Int32, Int32)


Imap.QuickDownloadMessages Method (String, String, String, String, Int32)

ImapQuickDownloadMessages Method (String, String, String, String, Int32)
Downloads all the messages (entire messages or message headers only) in the specified folder on the server, in a single line of code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessageCollection QuickDownloadMessages(
    string serverName,
    string accountName,
    string password,
    string folderName,
    int bodyPreviewSize
)
Public Shared Function QuickDownloadMessages (
    serverName As String,
    accountName As String,
    password As String,
    folderName As String,
    bodyPreviewSize As Integer
) As MailMessageCollection

Parameters

serverName
Type: SystemString
The name or IP address of the IMAP4 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
folderName
Type: SystemString
The full name of the folder to download the messages from.
bodyPreviewSize
Type: SystemInt32
Number of bytes of a message source body to download in addition to a message source header, or -1 to download entire messages, or 0 to download message headers only.

Return Value

Type: MailMessageCollection
A MailMessageCollection object containing the downloaded messages.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the folder.

An account on the mail server is guaranteed to contain at least "Inbox" folder. The "Inbox" name is case-sensitive ("Inbox", "inbox", and "INBOX" are equivalent). Other folder names, however, may be case-senstive depending on the server implementation.

Since MailBee is capable of downloading multiple messages in a batch, using this method is much more efficient than calling QuickDownloadMessage(String, String, String, String, Int32, Int32) method multiple times.

Note Note
Static methods still require the valid license key be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEnvelopesAsync(String, Boolean, EnvelopeParts, Int32).

Examples
This sample downloads headers of all the messages in the inbox, and displays indices (ordinal positions in the inbox) of all messages which likely have any attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessageCollection msgs = Imap.QuickDownloadMessages("mail.company.com", "login", "password", "Inbox", 0);
foreach (MailMessage msg in msgs)
{
    if (msg.HasAttachments)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer +
            " seems to have any attachments");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msgs As MailMessageCollection = Imap.QuickDownloadMessages("mail.company.com", _
    "login", "password", "Inbox", 0)
For Each msg As MailMessage In msgs
    If msg.HasAttachments Then
        Console.WriteLine("Message #" & msg.IndexOnServer & _
            " seems to have any attachments")
    End If
Next
See Also

Reference

Imap Class
QuickDownloadMessages Overload
MailBee.ImapMail Namespace
ImapQuickDownloadMessage(String, String, String, String, Int32, Int32)


Imap.RenameFolder Method

ImapRenameFolder Method
Renames an existing folder (mailbox in IMAP4 terms) of the IMAP4 account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RenameFolder(
    string oldName,
    string newName
)
Public Function RenameFolder (
    oldName As String,
    newName As String
) As Boolean

Parameters

oldName
Type: SystemString
The full name of the folder to be renamed.
newName
Type: SystemString
The new full name of the folder.

Return Value

Type: Boolean
true if the folder was renamed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The developer should specify the full names of the folder (including all parent folders' names if the folder is or should become a subfolder of another existing folder). See CreateFolder(String) topic for details regarding folder names.
Note Note
Inbox folder cannot be renamed.

To rename a folder asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

Examples
This sample connects to the IMAP4 server, logs in the mail account, and renames "Sent" to "Sent Items". Before renaming, the sample code checks if "Sent" exists and "Sent Items" does not already exist, and displays the corresponding warning is these conditions are not met.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class)
Imap imp = new Imap();

// Connect to the server and log in the account.
imp.Connect("imap4.company.com");
imp.Login("jdoe@company.com", "secret");

// First, check if "Sent" exists and "Sent Items" does not exist. To
// determine this, we'll will get the list of root level folders only
// (we could have received all the folders, but it's more effecient
// to download only root ones since we're going to rename a root level
// folder into another root level name).

string sentFolderName = null;
bool isSentItems = false;
FolderCollection folders = imp.DownloadFolders(false, string.Empty, "%");

foreach (Folder imapFolder in folders)
{
    string folderName = imapFolder.Name.ToLower();
    if (folderName == "sent")
    {
        sentFolderName = imapFolder.Name;
    }
    else if (folderName == "sent items")
    {
        isSentItems = true;
    }
}

if (sentFolderName == null)
{
    Console.WriteLine("Sent folder does not exist.");
}
else if (isSentItems)
{
    Console.WriteLine("'Sent Items' folder already exists.");
}
else
{
    imp.RenameFolder(sentFolderName, "Sent Items");
    Console.WriteLine(sentFolderName + " renamed to 'Sent Items'.");
}

imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class)
Dim imp As New Imap

' Connect to the server and log in the account.
imp.Connect("imap4.company.com")
imp.Login("jdoe@company.com", "secret")

' First, check if "Sent" exists and "Sent Items" does not exist. To
' determine this, we'll will get the list of root level folders only
' (we could have received all the folders, but it's more efficient
' to download only root ones since we're going to rename a root level
' folder into another root level name).

Dim sentFolderName As String = Nothing
Dim isSentItems As Boolean = False
Dim folders As FolderCollection = _
    imp.DownloadFolders(False, String.Empty, "%")

For Each imapFolder As Folder In folders
    Dim folderName As String = imapFolder.Name.ToLower()
    If folderName = "sent" Then
        sentFolderName = imapFolder.Name
    ElseIf folderName = "sent items" Then
        isSentItems = True
    End If
Next

If sentFolderName Is Nothing Then
    Console.WriteLine("Sent folder does not exist.")
ElseIf isSentItems Then
    Console.WriteLine("'Sent Items' folder already exists.")
Else
    imp.RenameFolder(sentFolderName, "Sent Items")
    Console.WriteLine(sentFolderName & " renamed to 'Sent Items'.")
End If

imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.RenameFolderAsync Method

ImapRenameFolderAsync Method
async/await version of RenameFolder(String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> RenameFolderAsync(
    string oldName,
    string newName
)
Public Function RenameFolderAsync (
    oldName As String,
    newName As String
) As Task(Of Boolean)

Parameters

oldName
Type: SystemString
The full name of the folder to be renamed.
newName
Type: SystemString
The new full name of the folder.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ResetState Method

ImapResetState Method
Resets the internal state of the component.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ResetState()
Public Sub ResetState
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method will close the connection if it's open, and will remove IsAborted status if Abort method was previously called. Typically, the developer may use this method to reuse the component after it went into aborted state due to Abort method call.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Search Method

ImapSearch Method
Searches the currently selected folder for messages that meet the specified criteria.
Overload List
Name | Description
Search | Returns the collection of UIDs of all messages in the currently selected folder.
Search(Boolean, String, String) | Searches the currently selected folder for messages that meet the specified criteria.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Search Method

ImapSearch Method
Returns the collection of UIDs of all messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public UidCollection Search()
Public Function Search As UidCollection

Return Value

Type: UidCollection
UidCollection object if the command succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method can be used to enumerate UID values of all messages in the folder.
Examples
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("mail.host.com");

        imp.Login("jdoe@host.com", "secret");

        // Select Inbox folder.
        imp.SelectFolder("INBOX");

        // Enumerate UIDs into uids variable.
        UidCollection uids = imp.Search();

        // Print UID list as a message set (this message set can then be
        // supplied as messageIndexSet argument of Imap object methods).
        Console.WriteLine("uids as message set (i.e. message sequence):");
        Console.WriteLine(uids.ToString());

        // Print each UID value individually.
        Console.WriteLine();
        Console.WriteLine("uids as a list of UIDs:");
        foreach (long uid in uids)
        {
            Console.WriteLine(uid);
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select Inbox folder.
        imp.SelectFolder("INBOX")

        ' Enumerate UIDs into uids variable.
        Dim uids As UidCollection = imp.Search()

        ' Print UID list as a message set (this message set can then be
        ' supplied as messageIndexSet argument of Imap object methods).
        Console.WriteLine("uids as message set (i.e. message sequence):")
        Console.WriteLine(uids.ToString())

        ' Print each UID value individually.
        Console.WriteLine()
        Console.WriteLine("uids as a list of UIDs:")
        For Each uid As Long In uids
            Console.WriteLine(uid)
        Next

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
Search Overload
MailBee.ImapMail Namespace
MailBee.ImapMailUidCollection


Imap.Search Method (Boolean, String, String)

ImapSearch Method (Boolean, String, String)
Searches the currently selected folder for messages that meet the specified criteria.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageIndexCollection Search(
    bool returnUids,
    string searchCondition,
    string charset
)
Public Function Search (
    returnUids As Boolean,
    searchCondition As String,
    charset As String
) As MessageIndexCollection

Parameters

returnUids
Type: SystemBoolean
If true, search results will be returned as UidCollection; otherwise, as MessageNumberCollection.
searchCondition
Type: SystemString
Search expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method return all messages in the folder.
charset
Type: SystemString
Charset used in searchCondition, or a null reference to use US-ASCII setting.

Return Value

Type: MessageIndexCollection
UidCollection or MessageNumberCollection object if the command succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

The developer must type-cast returned value to UidCollection type (if returnUids was true) or to MessageNumberCollection (if returnUids was false).

If searchCondition is specified, it must strictly match search expression rules defined by the IMAP4 protocol (RFC3501). MailBee simply passes this value to the server without alteration.

When multiple keys are specified, the result is the intersection (AND function) of all the messages that match those keys. For example, the criteria DELETED FROM "SMITH" SINCE 1-Feb-1994 refers to all deleted messages from Smith that were placed in the folder since February 1, 1994. A search key can also be a parenthesized list of one or more search keys (e.g., for use with the OR and NOT keys).

AllOf(String) (AND), AnyOf(String) (OR), Not(String) (NOT) methods simplify building complex queries.

When passing strings to search query, you should use the syntax like "TEXT " + ImapUtils.ToQuotedString(textToSearch) to enclose the text string in quotes. Or, when searching for non-English text, set charset to "UTF-8" and instead of ToQuotedString(String) use ToUtf8QuotedString(String) (with Gmail, use ToLiteral(String)). This is true for all IMAP keys which search for text (such as BODY, CC, FROM, SUBJECT, TEXT, TO).

The entire list of the currently defined IMAP4 search keys:

Key | Meaning
<sequence set> | Messages with message sequence numbers corresponding to the specified message sequence number set. Examples: "1", "589, 1067", "1:*", "5,7,10:25,37:*", "3:4". Multiple values are delimited with commas (,). Colon (:) is used to specify a range. For instance, "1:10" designates message indices in the range from 1 to 10. "*" is a wildcard. When used in a range, sets higher boundary of the range to the index of the last message in the folder.
ALL | All messages in the folder; the default initial key for ANDing.
ANSWERED | Messages with the \Answered flag set.
BCC <string> | Messages that contain the specified string in the envelope structure's BCC field.
BEFORE <date> | Messages whose internal date (disregarding time and timezone) is earlier than the specified date.
BODY <string> | Messages that contain the specified string in the body of the message.
CC <string> | Messages that contain the specified string in the envelope structure's CC field.
DELETED | Messages with the \Deleted flag set.
DRAFT | Messages with the \Draft flag set.
FLAGGED | Messages with the \Flagged flag set.
FROM <string> | Messages that contain the specified string in the envelope structure's FROM field.
HEADER <field-name> <string> | Messages that have a header with the specified field-name (as defined in [RFC-2822]) and that contains the specified string in the text of the header (what comes after the colon). If the string to search is zero-length, this matches all messages that have a header line with the specified field-name regardless of the contents.
KEYWORD <flag> | Messages with the specified keyword flag set.
LARGER <n> | Messages with an [RFC-2822] size larger than the specified number of octets.
NEW | Messages that have the \Recent flag set but not the \Seen flag. This is functionally equivalent to "(RECENT UNSEEN)".
NOT <search-key> | Messages that do not match the specified search key.
OLD | Messages that do not have the \Recent flag set. This is functionally equivalent to "NOT RECENT" (as opposed to "NOT NEW").
ON <date> | Messages whose internal date (disregarding time and timezone) is within the specified date.
OR <search-key1> <search-key2> | Messages that match either search key.
RECENT | Messages that have the \Recent flag set.
SEEN | Messages that have the \Seen flag set.
SENTBEFORE <date> | Messages whose [RFC-2822] Date: header (disregarding time and timezone) is earlier than the specified date.
SENTON <date> | Messages whose [RFC-2822] Date: header (disregarding time and timezone) is within the specified date.
SENTSINCE <date> | Messages whose [RFC-2822] Date: header (disregarding time and timezone) is within or later than the specified date.
SINCE <date> | Messages whose internal date (disregarding time and timezone) is within or later than the specified date.
SMALLER <n> | Messages with an [RFC-2822] size smaller than the specified number of octets.
SUBJECT <string> | Messages that contain the specified string in the envelope structure's SUBJECT field.
TEXT <string> | Messages that contain the specified string in the header or body of the message.
TO <string> | Messages that contain the specified string in the envelope structure's TO field.
UID <sequence set> | Messages with unique identifiers corresponding to the specified unique identifier set. Sequence set ranges are permitted.
UNANSWERED | Messages that do not have the \Answered flag set.
UNDELETED | Messages that do not have the \Deleted flag set.
UNDRAFT | Messages that do not have the \Draft flag set.
UNFLAGGED | Messages that do not have the \Flagged flag set.
UNKEYWORD <flag> | Messages that do not have the specified keyword flag set.
UNSEEN | Messages that do not have the \Seen flag set.
<string> means a quoted string (like "Annual report" or "String with quote \" and backslash \\ inside"). Certain key arguments specifying numbers (like <n>) must not be quoted.

Dates must be written in IMAP4 format and enclosed with quotes. Example: "06-Apr-2006". See the sample code in BeginSearch(Boolean, String, String, AsyncCallback, Object) topic on how to perform search by date.

Angle brackets (i.e. <> in <string>) only indicate placeholder for actual value, they are not actually a part of the key. For instance, TO <string> means the actual key will look like TO "jdoe@domain.com".

Note Note
Although searching is case-insensitive, some server implementations cannot perform search of strings containing international characters in case-insensitive manner even if the correct charset value is specified. Also, most IMAP server implementations cannot find searched string when it appears in the message in encoded form (such as Base64, quoted-printable, etc). Due to this, text search via IMAP4 is not as reliable as downloading entire messages and performing search over local copies.

If you are using Gmail and perform search of international text in non-ASCII charset (e.g. UTF-8), use ToLiteral(String) method instead of ToQuotedString(String). Gmail does not support non-ASCII data in quoted strings. See Gmail IMAP and POP3 issues topic on how to build search queries with ToLiteral(String) method.

With Gmail, however, you have an option to use extended syntax of Gmail search. It supports non-ASCII as well. See GmailSearch(String) for details.

Also, you can search for Gmail labels assigned to messages using X-GM-LABELS verb. For instance: imap.Search(true, ImapUtils.AnyOf(@"X-GM-LABELS label1", @"X-GM-LABELS sent"), null) (in C# syntax). This returns UIDs of all e-mails which have "label1" or "sent" labels set.

Note Note
MS Exchange (including Office 365) can search ASCII only. You cannot search for international content there. You can switch to Exchange Web Services ([!:Ews]) when working with MS Exchange.
Examples
This sample highlights common practices of IMAP4 search. You can also find additional examples in BeginSearch(Boolean, String, String, AsyncCallback, Object) and DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) topics.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // In the log, you can find the actual search queries sent to the server.
        imp.Log.Filename = "C:\\Temp\\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        imp.Connect("imap.company.com");
        imp.Login("jdoe@company.com", "secret");

        // Select Inbox folder.
        imp.SelectFolder("INBOX");

        UidCollection uids = null;
        MessageNumberCollection msgNums = null;
        string input = null;

        // Determine charset to use. This will let us perform search of
        // messages written in the charset of the current computer.
        string localComputerCharset = System.Text.Encoding.Default.WebName;

        // -----------------------------------------------------------------
        // Section 1: Search in Subject field.
        // Demonstrates text search and usage of charsets (for international
        // applications) and quoted strings (for searching arbitrary text,
        // including spaces, quotes, and other special characters).
        // -----------------------------------------------------------------

        Console.WriteLine("Input string to be searched in Subject field:");
        input = Console.ReadLine();

        // 1.1: US-ASCII search (case-insensitive).

        // 1.1.1: Search for UIDs.
        uids = (UidCollection)imp.Search(true,
            "SUBJECT " + ImapUtils.ToQuotedString(input), null);

        Console.WriteLine();
        Console.WriteLine("UIDs of found messages (US-ASCII mode):");
        Console.WriteLine(uids.ToString());

        // 1.1.2: Search for ordinal message numbers. This demonstrates
        // how to get search results as message numbers rather UIDs.
        msgNums = (MessageNumberCollection)imp.Search(false,
            "SUBJECT " + ImapUtils.ToQuotedString(input), null);

        Console.WriteLine();
        Console.WriteLine("Message numbers of found messages (US-ASCII mode):");
        Console.WriteLine(msgNums.ToString());

        // 1.2: Search with support of international characters of the current
        // computer's charset. US-ASCII characters will be searched in case-insensitive
        // manner but there is no such guarantee for non-US-ASCII characters.
        uids = (UidCollection)imp.Search(true,
            "SUBJECT " + ImapUtils.ToQuotedString(input),
            localComputerCharset);

        Console.WriteLine();
        Console.WriteLine("UIDs of found messages (" + localComputerCharset + " mode):");
        Console.WriteLine(uids.ToString());

        // 1.3: Search with support of UTF-8. This will let us perform search of any text in any language.
        uids = (UidCollection)imp.Search(true,
            "SUBJECT " + ImapUtils.ToUtf8QuotedString(input),
            System.Text.Encoding.UTF8.WebName);

        Console.WriteLine();
        Console.WriteLine("UIDs of found messages (UTF-8 mode):");
        Console.WriteLine(uids.ToString());

        // -----------------------------------------------------------------
        // Section 2: Search of messages with specific flags set.
        // Also demonstrates how to specify OR and AND conditions.
        // -----------------------------------------------------------------

        // 2.1: Search for messages having \Deleted flag set.
        uids = (UidCollection)imp.Search(true, "DELETED", null);

        Console.WriteLine();
        Console.WriteLine(@"UIDs of \Deleted messages:");
        Console.WriteLine(uids.ToString());

        // 2.2: Search for messages having \Deleted or \Seen flags set.
        uids = (UidCollection)imp.Search(true, "OR DELETED SEEN", null);

        Console.WriteLine();
        Console.WriteLine(@"UIDs of \Deleted or \Seen messages:");
        Console.WriteLine(uids.ToString());

        // 2.3: Search for messages having \Deleted or \Seen or \Answered flags set.
        uids = (UidCollection)imp.Search(true, "OR (OR DELETED SEEN) ANSWERED", null);

        Console.WriteLine();
        Console.WriteLine(@"UIDs of \Deleted or \Seen or \Answered messages:");
        Console.WriteLine(uids.ToString());

        // 2.4: Search for messages having \Deleted or (\Seen and \Answered) flags set.
        uids = (UidCollection)imp.Search(true, "OR DELETED (SEEN ANSWERED)", null);

        Console.WriteLine();
        Console.WriteLine(@"UIDs of \Deleted or (\Seen and \Answered) messages:");
        Console.WriteLine(uids.ToString());

        // ------------------------------------------------------------------
        // Section 3: Search of messages meeting complex criteria.
        // The criteria set (in C# syntax):
        // (size > 10000 || Flagged || !Spam) && BodyContains(string).
        // I.e. the message is larger than 10000 bytes or flagged or not spam
        // (there is no standard \Spam attribute so custom $Spam attribute
        // is used) and, besides that, the message must contain the specified
        // string (taken from user input) in the body.
        // ------------------------------------------------------------------

        uids = (UidCollection)imp.Search(true,
            "OR (OR LARGER 10000 FLAGGED) UNKEYWORD " + ImapUtils.ToQuotedString("$Spam") +
            " BODY " + ImapUtils.ToQuotedString(input), null);

        Console.WriteLine();
        Console.WriteLine("UIDs of messages meeting complex criteria:");
        Console.WriteLine(uids.ToString());

        // Using helper methods to repeat the same search:
        // (size > 10000 || Flagged || !Spam) && BodyContains(string).
        uids = (UidCollection)imp.Search(true,
            ImapUtils.AllOf(ImapUtils.AnyOf(
            "LARGER 10000", "FLAGGED", "UNKEYWORD " + ImapUtils.ToQuotedString("$Spam")),
            "BODY " + ImapUtils.ToQuotedString(input)), null);

        Console.WriteLine();
        Console.WriteLine("The same search repeated with helper methods:");
        Console.WriteLine(uids.ToString());

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' In the log, you can find the actual search queries sent to the server.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        imp.Connect("imap.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select Inbox folder.
        imp.SelectFolder("INBOX")

        Dim uids As UidCollection = Nothing
        Dim msgNums As MessageNumberCollection = Nothing
        Dim input As String = Nothing

        ' Determine charset to use. This will let us perform search of
        ' messages written in the charset of the current computer.
        Dim localComputerCharset As String = System.Text.Encoding.Default.WebName

        ' -----------------------------------------------------------------
        ' Section 1: Search in Subject field.
        ' Demonstrates text search and usage of charsets (for international
        ' applications) and quoted strings (for searching arbitrary text,
        ' including spaces, quotes, and other special characters).
        ' -----------------------------------------------------------------

        Console.WriteLine("Input string to be searched in Subject field:")
        input = Console.ReadLine()

        ' 1.1: US-ASCII search (case-insensitive).
        ' 1.1.1: Search for UIDs.
        uids = CType(imp.Search(True, "SUBJECT " & ImapUtils.ToQuotedString(input), _
            Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of found messages (US-ASCII mode):")
        Console.WriteLine(uids.ToString())

        ' 1.1.2: Search for ordinal message numbers. This demonstrates
        ' how to get search results as message numbers rather UIDs.
        msgNums = CType(imp.Search(False, "SUBJECT " & ImapUtils.ToQuotedString(input), _
            Nothing), MessageNumberCollection)

        Console.WriteLine()
        Console.WriteLine("Message numbers of found messages (US-ASCII mode):")
        Console.WriteLine(msgNums.ToString())

        ' 1.2: Search with support of international characters of the current
        ' computer's charset. US-ASCII characters will be searched in case-insensitive
        ' manner but there is no such guarantee for non-US-ASCII characters.
        uids = CType(imp.Search(True, "SUBJECT " & ImapUtils.ToQuotedString(input), _
            localComputerCharset), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of found messages (" & localComputerCharset & " mode):")
        Console.WriteLine(uids.ToString())

        ' 1.3: Search with support of UTF-8. This will let us perform search of any text in any language.
        uids = CType(imp.Search(True, "SUBJECT " & ImapUtils.ToUtf8QuotedString(input), _
            System.Text.Encoding.UTF8.WebName), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of found messages (UTF-8 mode):")
        Console.WriteLine(uids.ToString())

        ' -----------------------------------------------------------------
        ' Section 2: Search of messages with specific flags set.
        ' Also demonstrates how to specify OR and AND conditions.
        ' -----------------------------------------------------------------

        ' 2.1: Search for messages having \Deleted flag set.
        uids = CType(imp.Search(True, "DELETED", Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of \Deleted messages:")
        Console.WriteLine(uids.ToString())

        ' 2.2: Search for messages having \Deleted or \Seen flags set.
        uids = CType(imp.Search(True, "OR DELETED SEEN", Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of \Deleted or \Seen messages:")
        Console.WriteLine(uids.ToString())

        ' 2.3: Search for messages having \Deleted or \Seen or \Answered flags set.
        uids = CType(imp.Search(True, "OR (OR DELETED SEEN) ANSWERED", Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of \Deleted or \Seen or \Answered messages:")
        Console.WriteLine(uids.ToString())

        ' 2.4: Search for messages having \Deleted or (\Seen and \Answered) flags set.
        uids = CType(imp.Search(True, "OR DELETED (SEEN ANSWERED)", Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of \Deleted or (\Seen and \Answered) messages:")
        Console.WriteLine(uids.ToString())

        ' ------------------------------------------------------------------
        ' Section 3: Search of messages meeting complex criteria.
        ' The criteria set (in Visual Baisc syntax):
        ' (size > 10000 OrElse Flagged OrElse Not Spam) AndAlso BodyContains(string).
        ' I.e. the message is larger than 10000 bytes or flagged or not spam
        ' (there is no standard \Spam attribute so custom $Spam attribute
        ' is used) and, besides that, the message must contain the specified
        ' string (taken from user input) in the body.
        ' ------------------------------------------------------------------

        uids = CType(imp.Search(True, "OR (OR LARGER 10000 FLAGGED) UNKEYWORD " & _
            ImapUtils.ToQuotedString("$Spam") & " BODY " & _
            ImapUtils.ToQuotedString(input), Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("UIDs of messages meeting complex criteria:")
        Console.WriteLine(uids.ToString())

        ' Using helper methods to repeat the same search:
        ' (size > 10000 || Flagged || !Spam) && BodyContains(string).
        uids = CType(imp.Search(True, _
            ImapUtils.AllOf(ImapUtils.AnyOf( _
            "LARGER 10000", "FLAGGED", "UNKEYWORD " + ImapUtils.ToQuotedString("$Spam")), _
            "BODY " + ImapUtils.ToQuotedString(input)), Nothing), UidCollection)

        Console.WriteLine()
        Console.WriteLine("The same search repeated with helper methods:")
        Console.WriteLine(uids.ToString())

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
Search Overload
MailBee.ImapMail Namespace
ImapBeginSearch(Boolean, String, String, AsyncCallback, Object)
ImapUtilsGmailSearch(String)


Imap.SearchAsync Method

ImapSearchAsync Method
Overload List
 | Name | Description
Public method | SearchAsync | async/await version of Search.
 | SearchAsync(Boolean, String, String) | async/await version of Search(Boolean, String, String).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SearchAsync Method

ImapSearchAsync Method
async/await version of Search.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<UidCollection> SearchAsync()
Public Function SearchAsync As Task(Of UidCollection)

Return Value

Type: Task UidCollection
A task that represents the asynchronous operation. The value of TResult parameter is UidCollection object if the command succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
SearchAsync Overload
MailBee.ImapMail Namespace


Imap.SearchAsync Method (Boolean, String, String)

ImapSearchAsync Method (Boolean, String, String)
async/await version of Search(Boolean, String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MessageIndexCollection> SearchAsync(
    bool returnUids,
    string searchCondition,
    string charset
)
Public Function SearchAsync (
    returnUids As Boolean,
    searchCondition As String,
    charset As String
) As Task(Of MessageIndexCollection)

Parameters

returnUids
Type: SystemBoolean
If true, search results will be returned as UidCollection; otherwise, as MessageNumberCollection.
searchCondition
Type: SystemString
Search expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method return all messages in the folder.
charset
Type: SystemString
Charset used in searchCondition, or a null reference to use US-ASCII setting.

Return Value

Type: Task MessageIndexCollection
A task that represents the asynchronous operation. The value of TResult parameter is UidCollection or MessageNumberCollection object if the command succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Examples
This WinForms example gets UIDs of all unseen messages in the inbox. The sample requires button1 control on the form and MailBee.ImapMail namespace imported.
C#
VB
Copy
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        Imap imp = new Imap();
        await imp.ConnectAsync("mail.afterlogic.com");
        await imp.LoginAsync("test@afterlogic.com", "secret");
        await imp.SelectFolderAsync("Inbox");
        UidCollection uids = (UidCollection) await imp.SearchAsync(true, "unseen", null);
        await imp.DisconnectAsync();
    }
}
Public Class Form1
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim imp As New Imap
        Await imp.ConnectAsync("mail.afterlogic.com")
        Await imp.LoginAsync("test@afterlogic.com", "secret")
        Await imp.SelectFolderAsync("Inbox")
        Dim uids As UidCollection = CType(Await imp.SearchAsync(True, "unseen", Nothing), UidCollection)
        Await imp.DisconnectAsync()
    End Sub
End Class
See Also

Reference

Imap Class
SearchAsync Overload
MailBee.ImapMail Namespace


Imap.SelectFolder Method

ImapSelectFolder Method
Selects the specified folder (mailbox in IMAP4 terms) for read-write access.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SelectFolder(
    string folderName
)
Public Function SelectFolder (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The full name of the folder to be selected.

Return Value

Type: Boolean
true if the folder was selected successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To select the folder for read-only access, the developer should use ExamineFolder(String) method.

The developer should specify the full name of the folder (including all parent folders' names if the folder is subfolder of another existing folder). See CreateFolder(String) topic for details regarding folder names.

Examples
This sample connects to the IMAP4 server, logs in the mail account, selects Inbox folder, and marks all messages as seen (read).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
     static void Main(string[] args)
     {
         Imap imp = new Imap();

         // Connect to the server and log in the account.
         imp.Connect("imap.company.com");
         imp.Login("jdoe", "secret");

         // Select the folder.
         imp.SelectFolder("Inbox");

         imp.SetMessageFlags(Imap.AllMessages, false,
             SystemMessageFlags.Seen, MessageFlagAction.Add);

         imp.Disconnect();
     }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample

    Sub Main(ByVal args As String())
        ' The actual code (put it into a method of your class)
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("imap4.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Select the folder.
        imp.SelectFolder("Inbox")

        If imp.MessageCount > 0 Then
            ' Download and save last message into a file.
            ' If the message is recent, it won't loose \Recent flag.
            Dim msg As MailBee.Mime.MailMessage = _
                imp.DownloadEntireMessage(imp.MessageCount, False)
            msg.SaveMessage("C:\Temp\msg.eml")
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapExamineFolder(String)
ImapIsFolderSelected


Imap.SelectFolderAsync Method

ImapSelectFolderAsync Method
async/await version of SelectFolder(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SelectFolderAsync(
    string folderName
)
Public Function SelectFolderAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The full name of the folder to be selected.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SetMessageFlags Method

ImapSetMessageFlags Method
Overload List
Name | Description
SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction) | Sets or resets the specified flags for the specified messages in the currently selected folder.
SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) | Sets or resets the specified flags for the specified messages in the currently selected folder.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SetMessageFlags Method (String, Boolean, SystemMessageFlags, MessageFlagAction)

ImapSetMessageFlags Method (String, Boolean, SystemMessageFlags, MessageFlagAction)
Sets or resets the specified flags for the specified messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetMessageFlags(
    string messageIndexSet,
    bool indexIsUid,
    SystemMessageFlags systemFlags,
    MessageFlagAction action
)
Public Function SetMessageFlags (
    messageIndexSet As String,
    indexIsUid As Boolean,
    systemFlags As SystemMessageFlags,
    action As MessageFlagAction
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
systemFlags
Type: MailBee.ImapMailSystemMessageFlags
A set of flags to be set or reset.
action
Type: MailBee.ImapMailMessageFlagAction
The action to perform with the specified flags (set, reset, etc).

Return Value

Type: Boolean
true if the message flags have been updated successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.
Note Note
This method can also set Gmail-specific labels for messages (see MessageFlagAction topic for details). If the label contains international characters, you should encode it with UTF-7M unless it's already encoded. You can use ToUtf7QuotedString(String) method for that.
Examples
This sample undeletes all messages marked as deleted in the inbox folder.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap4.server.com");
        imp.Login("jdoe@server.com", "secret");
        imp.SelectFolder("INBOX");

        // Get UIDs of deleted messages. We could have also skipped this
        // stage and just tell the server to remove \Deleted flag for
        // all messages (even for those message which do not have this
        // flag set - such messages won't be affected). We call Search()
        // method and then consume its results in SetMessageFlags() just
        // for purposes of illustration.
        UidCollection uids = (UidCollection)imp.Search(true, "DELETED", null);

        if (uids.Count > 0)
        {
            // Remove \Deleted flag from the deleted messages.
            imp.SetMessageFlags(uids.ToString(), true,
                SystemMessageFlags.Deleted, MessageFlagAction.Remove);
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap4.server.com")
        imp.Login("jdoe@server.com", "secret")
        imp.SelectFolder("INBOX")

        ' Get UIDs of deleted messages. We could have also skipped this
        ' stage and just tell the server to remove \Deleted flag for
        ' all messages (even for those message which do not have this
        ' flag set - such messages won't be affected). We call Search()
        ' method and then consume its results in SetMessageFlags() just
        ' for purposes of illustration.
        Dim uids As UidCollection = CType(imp.Search(True, "DELETED", Nothing), UidCollection)

        If uids.Count > 0 Then
            ' Remove \Deleted flag from the deleted messages.
            imp.SetMessageFlags(uids.ToString(), True, SystemMessageFlags.Deleted, MessageFlagAction.Remove)
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
SetMessageFlags Overload
MailBee.ImapMail Namespace


Imap.SetMessageFlags Method (String, Boolean, String, MessageFlagAction, Boolean)

ImapSetMessageFlags Method (String, Boolean, String, MessageFlagAction, Boolean)
Sets or resets the specified flags for the specified messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetMessageFlags(
    string messageIndexSet,
    bool indexIsUid,
    string flags,
    MessageFlagAction action,
    bool silentMode
)
Public Function SetMessageFlags (
    messageIndexSet As String,
    indexIsUid As Boolean,
    flags As String,
    action As MessageFlagAction,
    silentMode As Boolean
) As Boolean

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
flags
Type: SystemString
The string containing IMAP4 flags to be set or reset.
action
Type: MailBee.ImapMailMessageFlagAction
The action to perform with the specified flags (set, reset, etc).
silentMode
Type: SystemBoolean
If true, the server will NOT respond with the new values of flags of the affected messages; otherwise, the server will produce a series of untagged FETCH responses containing the updated flag lists of affected messages.

Return Value

Type: Boolean
true if the message flags have been updated successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To learn how to specify a valid message sequence (messageIndexSet value), see DownloadEnvelopes(String, Boolean) topic.

To clear flag list for certain message(s), call this method passing a null reference or empty string as flags value and Replace as action value.

MailBee ignores the FETCH response returned by the server when silentMode is false. If the application needs to process this data, the developer can use GetServerResponses(String) method to analyze the server response.

Another reason to set silentMode to false is to determine if the server really applied the specified flags by examining the log file (see the sample code below).

Other overloads of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) method set silentMode to true.

Examples

This sample replaces all flags of the last message in the inbox with the non-standard "$Spam" flag. Also demonstrates how to quickly check if the server really applied the specified flags using log file or console output.

Note Note
This sample may throw an exception or do nothing if the mail server forbids using non-standard message flags. Or, the server may set the flag in memory but discard the state change when the current session ends. See the sample in UploadMessage(MailMessage, String, String, String) topic on how to programmatically determine whether the server allows using non-standard flags.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Set where to save log file. However, we do
        // not enable logging here. We'll enable it
        // later for a single moment of setting flags.
        imp.Log.Filename = @"C:\Temp\log.txt";

        // Connect to the server, login and select inbox.
        imp.Connect("imap.somedomain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        if (imp.MessageCount > 0)
        {
            // Enable logging into a file to track
            // the status of setting flags.
            imp.Log.Enabled = true;

            // Replace all flags of the last message with "$Spam" flag.
            // The developer can then take a look at C:\Temp\log.txt file
            // to find out if untagged "* FETCH (FLAGS)" response to
            // STORE command contains "$Spam" element. If it does, the
            // server indeed applied this flag to the message.
            imp.SetMessageFlags(imp.MessageCount.ToString(), false,
                "$Spam", MessageFlagAction.Replace, false);

            // Disable logging again. Thus, the log file will be pretty
            // small, and the developer will be able to read it easily.
            imp.Log.Enabled = false;

            // Demonstrate alternative way of analyzing FETCH responses.
            string[] flagResponses = imp.GetServerResponses("FETCH");
            foreach (string response in flagResponses)
            {
                Console.WriteLine(response);
            }
        }
        else
        {
            Console.WriteLine("The inbox is empty");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' The actual code.
    Sub Main()
        Dim imp As New Imap

        ' Set where to save log file. However, we do
        ' not enable logging here. We'll enable it
        ' later for a single moment of setting flags.
        imp.Log.Filename = "C:\Temp\log.txt"

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.somedomain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        If imp.MessageCount > 0 Then
            ' Enable logging into a file to track
            ' the status of setting flags.
            imp.Log.Enabled = True

            ' Replace all flags of the last message with "$Spam" flag.
            ' The developer can then take a look at C:\Temp\log.txt file
            ' to find out if untagged "* FETCH (FLAGS)" response to
            ' STORE command contains "$Spam" element. If it does, the
            ' server indeed applied this flag to the message.
            imp.SetMessageFlags(imp.MessageCount.ToString(), False, "$Spam", _
                MessageFlagAction.Replace, False)

            ' Disable logging again. Thus, the log file will be pretty
            ' small, and the developer will be able to read it easily.
            imp.Log.Enabled = False

            ' Demonstrate alternative way of analyzing FETCH responses.
            Dim flagResponses As String() = imp.GetServerResponses("FETCH")
            For Each response As String In flagResponses
                Console.WriteLine(response)
            Next
        Else
            Console.WriteLine("The inbox is empty")
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
SetMessageFlags Overload
MailBee.ImapMail Namespace


Imap.SetMessageFlagsAsync Method

ImapSetMessageFlagsAsync Method
Overload List
 | Name | Description
Public method | SetMessageFlagsAsync(String, Boolean, SystemMessageFlags, MessageFlagAction) | async/await version of SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction).
Public method | SetMessageFlagsAsync(String, Boolean, String, MessageFlagAction, Boolean) | async/await version of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SetMessageFlagsAsync Method (String, Boolean, SystemMessageFlags, MessageFlagAction)

ImapSetMessageFlagsAsync Method (String, Boolean, SystemMessageFlags, MessageFlagAction)
async/await version of SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SetMessageFlagsAsync(
    string messageIndexSet,
    bool indexIsUid,
    SystemMessageFlags systemFlags,
    MessageFlagAction action
)
Public Function SetMessageFlagsAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    systemFlags As SystemMessageFlags,
    action As MessageFlagAction
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
systemFlags
Type: MailBee.ImapMailSystemMessageFlags
A set of flags to be set or reset.
action
Type: MailBee.ImapMailMessageFlagAction
The action to perform with the specified flags (set, reset, etc).

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
SetMessageFlagsAsync Overload
MailBee.ImapMail Namespace


Imap.SetMessageFlagsAsync Method (String, Boolean, String, MessageFlagAction, Boolean)

ImapSetMessageFlagsAsync Method (String, Boolean, String, MessageFlagAction, Boolean)
async/await version of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SetMessageFlagsAsync(
    string messageIndexSet,
    bool indexIsUid,
    string flags,
    MessageFlagAction action,
    bool silentMode
)
Public Function SetMessageFlagsAsync (
    messageIndexSet As String,
    indexIsUid As Boolean,
    flags As String,
    action As MessageFlagAction,
    silentMode As Boolean
) As Task(Of Boolean)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
flags
Type: SystemString
The string containing IMAP4 flags to be set or reset.
action
Type: MailBee.ImapMailMessageFlagAction
The action to perform with the specified flags (set, reset, etc).
silentMode
Type: SystemBoolean
If true, the server will NOT respond with the new values of flags of the affected messages; otherwise, the server will produce a series of untagged FETCH responses containing the updated flag lists of affected messages.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
SetMessageFlagsAsync Overload
MailBee.ImapMail Namespace


Imap.SortedSearch Method

ImapSortedSearch Method
Searches the currently selected folder for messages that meet the specified criteria and returns them as a collection sorted by the specified condition.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageIndexCollection SortedSearch(
    bool returnUids,
    string searchCondition,
    string charset,
    string orderBy
)
Public Function SortedSearch (
    returnUids As Boolean,
    searchCondition As String,
    charset As String,
    orderBy As String
) As MessageIndexCollection

Parameters

returnUids
Type: SystemBoolean
If true, search results will be returned as UidCollection; otherwise, as MessageNumberCollection.
searchCondition
Type: SystemString
Search expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method return all messages in the folder.
charset
Type: SystemString
Charset used in searchCondition, or a null reference to use US-ASCII setting.
orderBy
Type: SystemString
Sorting order expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method downgrade to the regular Search(Boolean, String, String).

Return Value

Type: MessageIndexCollection
UidCollection or MessageNumberCollection object if the command succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
All parameters except orderBy have the same meaning as for Search(Boolean, String, String) method.
Note Note
Sorted search capability must be supported by the server ("sort" must be listed in GetExtensions results). See "IMAP SORT" internet draft for more information.

If orderBy is specified, it must strictly match sort expression rules defined by "IMAP SORT" internet draft. MailBee simply passes this value to the server without alteration.

Sorting is in ascending order. Earlier dates sort before later dates; smaller sizes sort before larger sizes; and strings are sorted according to ascending values established by their collation algorithm.

To sort in descending order (e.g. "newer first"), prepend the sorting key with REVERSE (e.g. REVERSE ARRIVAL.

If two or more messages exactly match according to the sorting criteria, these messages are sorted according to the order in which they appear in the mailbox. In other words, there is an implicit sort criterion of "sequence number".

When multiple sort criteria are specified, the result is sorted in the priority order that the criteria appear. For example, "SUBJECT DATE" will sort messages in order by their base subject text; and for messages with the same base subject text will sort by their sent date.

If the associated message header for a particular criterion is absent in the message, it is treated as the empty string. The empty string always collates before non-empty strings.

The defined sort criteria are as follows:

Key | Meaning
ARRIVAL | Internal date and time of the message. This differs from the ON criteria in SEARCH, which uses just the internal date.
CC | RFC-822 local-part of the first "cc" address.
DATE | Sent date and time from the Date: header, adjusted by timezone. This differs from the SENTON criteria in SEARCH, which uses just the date and not the time, nor adjusts by time zone.
FROM | RFC-822 local-part of the first "From" address.
REVERSE | Followed by another sort criterion, has the effect of that criterion but in reverse (descending) order. Note: REVERSE only reverses a single criterion.
SIZE | Size of the message in bytes.
SUBJECT | Subject text.
TO | RFC-822 local-part of the first "To" address.
Examples
This sample performs sorted search in the inbox and downgrades to the regular search if SORT capability is not supported by the server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");
        imp.SelectFolder("INBOX");

        // Set to true if SORT extension is available.
        bool sortAvail = (imp.GetExtension("SORT") != null);

        // If SORT is supported, order messages by FROM field first (primary sort condition)
        // and then order each group of messages coming from the same FROM by arrival date
        // in descending order (secondary sort condition). If SORT is not supported, orderBy
        // criteria will not be set and SortedSearch will downgrade to the regular Search.
        string orderByCriteria = sortAvail ? "FROM REVERSE ARRIVAL" : null;

        // Get UIDs of all messages in the inbox, sorted accordingly orderByCriteria.
        UidCollection uids = (UidCollection)imp.SortedSearch(true, "ALL", null, orderByCriteria);

        Console.WriteLine("SORT capability is " + (!sortAvail ? "NOT " : "") + "available");
        Console.WriteLine("UIDs found: " + uids.ToString());

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("jdoe@company.com", "secret")
        imp.SelectFolder("INBOX")

        ' Set to true if SORT extension is available.
        Dim sortAvail As Boolean = (Not imp.GetExtension("SORT") Is Nothing)

        ' If SORT is supported, order messages by FROM field first (primary sort condition)
        ' and then order each group of messages coming from the same FROM by arrival date
        ' in descending order (secondary sort condition). If SORT is not supported, orderBy
        ' criteria will not be set and SortedSearch will downgrade to the regular Search.
        Dim orderByCriteria As String = IIf(sortAvail, "FROM REVERSE ARRIVAL", Nothing)

        ' Get UIDs of all messages in the inbox, sorted accordingly orderByCriteria.
        Dim uids As UidCollection = CType(imp.SortedSearch(True, "ALL", Nothing, orderByCriteria), UidCollection)

        Console.WriteLine("SORT capability is " & IIf(Not sortAvail, "NOT ", "") & "available")
        Console.WriteLine("UIDs found: " & uids.ToString())

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)
ImapBeginSortedSearch(Boolean, String, String, String, AsyncCallback, Object)


Imap.SortedSearchAsync Method

ImapSortedSearchAsync Method
async/await version of SortedSearch(Boolean, String, String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MessageIndexCollection> SortedSearchAsync(
    bool returnUids,
    string searchCondition,
    string charset,
    string orderBy
)
Public Function SortedSearchAsync (
    returnUids As Boolean,
    searchCondition As String,
    charset As String,
    orderBy As String
) As Task(Of MessageIndexCollection)

Parameters

returnUids
Type: SystemBoolean
If true, search results will be returned as UidCollection; otherwise, as MessageNumberCollection.
searchCondition
Type: SystemString
Search expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method return all messages in the folder.
charset
Type: SystemString
Charset used in searchCondition, or a null reference to use US-ASCII setting.
orderBy
Type: SystemString
Sorting order expression in IMAP4 language, or a null reference (Nothing in Visual Basic) to make the method downgrade to the regular Search(Boolean, String, String).

Return Value

Type: Task MessageIndexCollection
A task that represents the asynchronous operation. The value of TResult parameter is UidCollection or MessageNumberCollection object if the command succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.StartTls Method

ImapStartTls Method
Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool StartTls()
Public Function StartTls As Boolean

Return Value

Type: Boolean
true if TLS/SSL negotiation succeeded and the connection is now secured with TLS/SSL layer; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method lets the developer to switch the existing, already opened connection (usually, on port 110), to SSL/TLS mode. If the connection has been opened on a dedicated SSL port from the start (usually, port 993), the developer doesn't need to call this method.

As alternative to calling StartTls method, the developer can ask MailBee to start TLS/SSL negotiation automatically by setting SslMode property value to OnConnect or UseStartTls.

AutodetectPortAndSslMode property may cause MailBee to automatically enable TLS/SSL for some well-known hosts or ports even if SslMode property of the current connection has its default value. Be sure to always check IsSslConnection value prior to calling StartTls.

Note Note
Not all mail servers support STARTTLS functionality.
Examples
This sample attempts to establish TLS/SSL connection with the IMAP4 server and displays the number of messages in the inbox on success.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Connect("mail.domain.com");
if (!imp.IsSslConnection)
{
    imp.StartTls();
}
imp.Login("jdoe", "secret");
imp.SelectFolder("Inbox");
Console.WriteLine(imp.MessageCount);
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Connect("mail.domain.com")
If Not imp.IsSslConnection Then
    imp.StartTls()
End If
imp.Login("jdoe", "secret")
imp.SelectFolder("Inbox")
Console.WriteLine(imp.MessageCount)
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSslMode
ImapSslProtocol
ImapBeginStartTls(AsyncCallback, Object)


Imap.StartTlsAsync Method

ImapStartTlsAsync Method
async/await version of StartTls.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> StartTlsAsync()
Public Function StartTlsAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.StopIdle Method

ImapStopIdle Method
Notifies MailBee to terminate idling when appropriate.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void StopIdle()
Public Sub StopIdle
Remarks

Calling this method does not have immediate effect (although the method itself returns control instantly). It just notifies MailBee to start IDLE DONE procedure when finished processing the current responses.

Calling this method when the component is not idling does nothing.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapIdle
ImapBeginIdle(AsyncCallback, Object)
ImapEndIdle


Imap.SubscribeFolder Method

ImapSubscribeFolder Method
Subscribes to the specified folder (mailbox in IMAP4 terms) of the IMAP4 account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SubscribeFolder(
    string folderName
)
Public Function SubscribeFolder (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The full name of the folder to be subscribed.

Return Value

Type: Boolean
true if the folder was subscribed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method adds the specified folder to the server's set of "active" or "subscribed" folders as returned by DownloadFolders(Boolean) method when subscribedOnly is set to true.

The developer should specify the full name of the folder (including all parent folders' names if the folder is subfolder of another existing folder). See CreateFolder(String) topic for details regarding folder names.

To subscribe to a folder asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDownloadFolders(Boolean)


Imap.SubscribeFolderAsync Method

ImapSubscribeFolderAsync Method
async/await version of SubscribeFolder(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SubscribeFolderAsync(
    string folderName
)
Public Function SubscribeFolderAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The full name of the folder to be subscribed.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.UnsubscribeFolder Method

ImapUnsubscribeFolder Method
Unsubscribes the previously subscribed folder (mailbox in IMAP4 terms) of the IMAP4 account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UnsubscribeFolder(
    string folderName
)
Public Function UnsubscribeFolder (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The full name of the folder to be unsubscribed.

Return Value

Type: Boolean
true if the folder was unsubscribed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method removes the specified folder from the server's set of "active" or "subscribed" folders as returned by DownloadFolders(Boolean) method when subscribedOnly is set to true.

The developer should specify the full name of the folder (including all parent folders' names if the folder is subfolder of another existing folder). See CreateFolder(String) topic for details regarding folder names.

To unsubscribe a folder asynchronously, see the sample code in BeginExecuteCustomCommand(String, String, AsyncCallback, Object) topic.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDownloadFolders(Boolean)


Imap.UnsubscribeFolderAsync Method

ImapUnsubscribeFolderAsync Method
async/await version of UnsubscribeFolder(String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UnsubscribeFolderAsync(
    string folderName
)
Public Function UnsubscribeFolderAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The full name of the folder to be unsubscribed.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.UploadMessage Method

ImapUploadMessage Method
Overload List
Name | Description
UploadMessage(MailMessage, String) | Uploads a mail message to the specified folder.
UploadMessage(MailMessage, String, SystemMessageFlags) | Uploads a mail message to the specified folder and assigns the specified flags to this message.
UploadMessage(MailMessage, String, String, DateTime) | Uploads a mail message to the specified folder and assigns the specified date and flags to this message.
UploadMessage(MailMessage, String, String, String) | Uploads a mail message to the specified folder and assigns the specified date and flags to this message.
UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) | Uploads a mail message to the specified folder, assigns the specified date and flags to this message, and retrieves UID assigned to the uploaded message by the server.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.UploadMessage Method (MailMessage, String)

ImapUploadMessage Method (MailMessage, String)
Uploads a mail message to the specified folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    MailMessage msg,
    string folderName
)
Public Function UploadMessage (
    msg As MailMessage,
    folderName As String
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.

Return Value

Type: Boolean
true if the message was uploaded successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method implements APPEND command of the IMAP4 protocol. For uploaded messages, the mail server automatically assigns "\Recent" flag. The date of receiving the message by the server (INTERNALDATE in IMAP4 terms) will be set to the current datetime/timezone of the local computer (not the mail server).

To upload a file, the developer can first load it into MailMessage object using LoadMessage(String) method, and then call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) passing a reference to this MailMessage object. There is no extra overhead on parsing the message since LoadMessage(String) just reads a file into memory. The MailMessage won't parse the contained message unless the application starts accessing its properties or methods (so-called "lazy" model).

To upload a mail message just sent using Smtp component, the developer call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method passing a reference to the Message property (see UploadMessage(MailMessage, String, SystemMessageFlags) sample).

To obtain the UID value assigned to the uploaded message, the developer should either examine DestUidString property of UidPlusResult object passed in res parameter of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method (the server must support UIDPLUS capability), or obtain UidNext value calling GetFolderStatus(String) method before making upload (this approach is compatible with all servers).

Examples

This sample loads the message from a file and uploads it into "Archive" folder.

The sample assumes "Archive" folder had already been created in the past. To learn how to make sure the folder exists, see UploadMessage(MailMessage, String, String, DateTime) or UploadMessage(MailMessage, String, String, String) samples.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the IMAP4 server and log in the account.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");

        // Load the message from C:\Temp\message.eml file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\message.eml");

        // Upload the message into "Archive" folder.
        imp.UploadMessage(msg, "Archive");

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the IMAP4 server and log in the account.
        imp.Connect("mail.company.com")
        imp.Login("jdoe@company.com", "secret")

        ' Load the message from C:\Temp\message.eml file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Temp\message.eml")

        ' Upload the message into "Archive" folder.
        imp.UploadMessage(msg, "Archive")

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
UploadMessage Overload
MailBee.ImapMail Namespace


Imap.UploadMessage Method (MailMessage, String, SystemMessageFlags)

ImapUploadMessage Method (MailMessage, String, SystemMessageFlags)
Uploads a mail message to the specified folder and assigns the specified flags to this message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    MailMessage msg,
    string folderName,
    SystemMessageFlags systemFlags
)
Public Function UploadMessage (
    msg As MailMessage,
    folderName As String,
    systemFlags As SystemMessageFlags
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
systemFlags
Type: MailBee.ImapMailSystemMessageFlags
A set of flags to be assigned to the message.

Return Value

Type: Boolean
true if the message was uploaded successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method implements APPEND command of the IMAP4 protocol. The uploaded message will have the specified flags assigned + "\Recent" flag which is always added by the server for uploaded messages. The date of receiving the message by the server (INTERNALDATE in IMAP4 terms) will be set to the current datetime/timezone of the local computer (not the mail server).

To upload a file, the developer can first load it into MailMessage object using LoadMessage(String) method, and then call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) passing a reference to this MailMessage object. There is no extra overhead on parsing the message since LoadMessage(String) just reads a file into memory. The MailMessage won't parse the contained message unless the application starts accessing its properties or methods (so-called "lazy" model).

To upload a mail message just sent using Smtp component, the developer call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method passing a reference to the Message property.

To obtain the UID value assigned to the uploaded message, the developer should either examine DestUidString property of UidPlusResult object passed in res parameter of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method (the server must support UIDPLUS capability), or obtain UidNext value calling GetFolderStatus(String) method before making upload (this approach is compatible with all servers).

Examples

This sample sends a mail message using Smtp component and then uploads it into "Sent" folder setting "\Seen" and "\Answered" flags.

The sample assumes "Sent" folder had already been created in the past. To learn how to make sure the folder exists, see UploadMessage(MailMessage, String, String, DateTime) or UploadMessage(MailMessage, String, String, String) samples.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Send the message using Smtp object.
        Smtp mailer = new Smtp();

        // Send directly (via MX lookup). To send via SMTP server,
        // comment the next line and uncomment 2nd or 3rd statement below.
        mailer.DnsServers.Autodetect();

        // Uncomment to send via SMTP server not using SMTP authentication.
        // mailer.SmtpServers.Add("smtp.host.com");

        // Uncomment to send via SMTP server using SMTP authentication.
        // mailer.SmtpServers.Add("smtp.host.com", "jdoe", "secret");

        mailer.From = new EmailAddress("jdoe@host.com", "John Doe");
        mailer.To.Add("sally@company.com", "Sally Smith");
        mailer.Subject = "Annual report";
        mailer.BodyPlainText = "The report contents";
        mailer.Send();

        Imap imp = new Imap();

        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Connect to the IMAP4 server and log in the account.
        imp.Connect("imap.host.com");
        imp.Login("jdoe", "secret");

        // Upload the message just sent into "Sent" folder and set
        // \Seen and \Answered flags.
        imp.UploadMessage(mailer.Message, "Sent",
            SystemMessageFlags.Seen | SystemMessageFlags.Answered);

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main()
        ' Send the message using Smtp object.
        Dim mailer As New Smtp

        ' Send directly (via MX lookup). To send via SMTP server,
        ' comment the next line and uncomment 2nd or 3rd statement below.
        mailer.DnsServers.Autodetect()

        ' Uncomment to send via SMTP server not using SMTP authentication.
        ' mailer.SmtpServers.Add("smtp.host.com")

        ' Uncomment to send via SMTP server using SMTP authentication.
        ' mailer.SmtpServers.Add("smtp.host.com", "jdoe", "secret")

        mailer.From = New EmailAddress("jdoe@host.com", "John Doe")
        mailer.To.Add("sally@company.com", "Sally Smith")
        mailer.Subject = "Annual report"
        mailer.BodyPlainText = "The report contents"
        mailer.Send()

        Dim imp As New Imap

        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Connect to the IMAP4 server and log in the account.
        imp.Connect("imap.host.com")
        imp.Login("jdoe", "secret")

        ' Upload the message just sent into "Sent" folder and set
        ' \Seen and \Answered flags.
        imp.UploadMessage(mailer.Message, "Sent", _
            SystemMessageFlags.Seen Or SystemMessageFlags.Answered)

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
UploadMessage Overload
MailBee.ImapMail Namespace
MailBee.SmtpMailSmtp


Imap.UploadMessage Method (MailMessage, String, String, DateTime)

ImapUploadMessage Method (MailMessage, String, String, DateTime)
Uploads a mail message to the specified folder and assigns the specified date and flags to this message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    MailMessage msg,
    string folderName,
    string flags,
    DateTime dt
)
Public Function UploadMessage (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dt As DateTime
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dt
Type: SystemDateTime
The datetime to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server). If MinValue, the server will assign this date itself.

Return Value

Type: Boolean
true if the message was uploaded successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method implements APPEND command of the IMAP4 protocol.

To upload a file, the developer can first load it into MailMessage object using LoadMessage(String) method, and then call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) passing a reference to this MailMessage object. There is no extra overhead on parsing the message since LoadMessage(String) just reads a file into memory. The MailMessage won't parse the contained message unless the application starts accessing its properties or methods (so-called "lazy" model).

To upload a mail message just sent using Smtp component, the developer call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method passing a reference to the Message property.

To obtain the UID value assigned to the uploaded message, the developer should either examine DestUidString property of UidPlusResult object passed in res parameter of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method (the server must support UIDPLUS capability), or obtain UidNext value calling GetFolderStatus(String) method before making upload (this approach is compatible with all servers).

To get standard message flags as string in IMAP4 format (e.g. "\Seen \Flagged"), the developer can use SystemFlagsToString(SystemMessageFlags) method.

In addition to the flags specified by the application, the server also sets "\Recent" flag. Thus, the uploaded message will always have at least "\Recent" flag set.

Examples
This sample creates a new mail message and saves it into "Draft" folder (creating the folder if necessary) assigning the current datetime/timezone of the local computer and setting "\Draft" flag. Also, the server will implicitly add "\Recent" flag.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("imap4.company.com");
        imp.Login("jdoe", "secret");

        // Create a new message. Assume we need to save a draft of the message.
        MailMessage msg = new MailMessage();

        // Create Draft folder if needed.
        FolderCollection folders = imp.DownloadFolders(false, null, "Draft");
        if (folders.Count == 0)
        {
            imp.CreateFolder("Draft");
        }

        // Upload the message and assign the current datetime and timezone
        // of the client as the date of receiving the message by the server
        // (INTERNALDATE in IMAP4 terms).
        // "\Draft" string is set directly. Alternatively, we could have
        // used MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Draft);
        imp.UploadMessage(msg, "Draft", @"\Draft", DateTime.Now);

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")

        ' Create a new message. Assume we need to save a draft of the message.
        Dim msg As New MailMessage

        ' Create Draft folder if needed.
        Dim folders As FolderCollection = imp.DownloadFolders(False, Nothing, "Draft")

        If (folders.Count = 0) Then
            imp.CreateFolder("Draft")
        End If

        ' Upload the message and assign the current datetime and timezone
        ' of the client as the date of receiving the message by the server
        ' (INTERNALDATE in IMAP4 terms).
        ' "\Draft" string is set directly. Alternatively, we could have
        ' used MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Draft)
        imp.UploadMessage(msg, "Draft", "\Draft", DateTime.Now)

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
UploadMessage Overload
MailBee.ImapMail Namespace


Imap.UploadMessage Method (MailMessage, String, String, String)

ImapUploadMessage Method (MailMessage, String, String, String)
Uploads a mail message to the specified folder and assigns the specified date and flags to this message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    MailMessage msg,
    string folderName,
    string flags,
    string dateTimeString
)
Public Function UploadMessage (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dateTimeString As String
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dateTimeString
Type: SystemString
The string containing datetime (in IMAP4 format) to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server), or a null reference to let the server assign its current datetime value.

Return Value

Type: Boolean
true if the message was uploaded successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method implements APPEND command of the IMAP4 protocol.

To upload a file, the developer can first load it into MailMessage object using LoadMessage(String) method, and then call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) passing a reference to this MailMessage object. There is no extra overhead on parsing the message since LoadMessage(String) just reads a file into memory. The MailMessage won't parse the contained message unless the application starts accessing its properties or methods (so-called "lazy" model).

To upload a mail message just sent using Smtp component, the developer call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method passing a reference to the Message property.

To obtain the UID value assigned to the uploaded message, the developer should either examine DestUidString property of UidPlusResult object passed in res parameter of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method (the server must support UIDPLUS capability), or obtain UidNext value calling GetFolderStatus(String) method before making upload (this approach is compatible with all servers).

To get standard message flags as string in IMAP4 format (e.g. "\Seen \Flagged"), the developer can use SystemFlagsToString(SystemMessageFlags) method.

In addition to the flags specified by the application, the server also sets "\Recent" flag. Thus, the uploaded message will always have at least "\Recent" flag set.

To get datetime string in IMAP4 format (e.g. "01-May-2004 05:26:59 -0600"), the developer can use GetImapDateTimeString method.

Examples

This sample creates a new mail message and saves it into "Draft" folder (creating the folder if necessary) using the current datetime/timezone of the mail server. "\Draft" and non-standard "$Personal" flag are set (and the server will implicitly add "\Recent" flag).

However, it may be forbidden by the server to set non-standard flags for messages. For this purpose, we check if PermanentFlags includes CanCreate flag. If not, we set "\Draft" flag only.

Note Note
In this sample, we do not check if "$Personal" flag is already available. Real-world applications should first check if the specified non-standard flag is already available in PermanentFlags and try to add new flag only if it's not already available.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");

        // Create a new message. Assume we need to save a draft of the message.
        MailMessage msg = new MailMessage();

        // Try to select Draft folder and create it if needed.
        // We do not need to select the folder for uploading but
        // we need to check if it's permitted to use non-system flags
        // (such as "$Personal") in this folder.
        try
        {
            imp.ExamineFolder("Draft");
        }
        catch (MailBeeImapNegativeResponseException e)
        {
            if (e.CompletionResult == "NO")
            {
                imp.CreateFolder("Draft");
                imp.ExamineFolder("Draft");
            }
            else
            {
                throw;
            }
        }

        string flags = MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Draft);

        // Add "$Personal" flag if it's allowed for this folder.
        if ((imp.PermanentFlags.SystemFlags & SystemMessageFlags.CanCreate) > 0)
        {
            flags += " $Personal";
        }

        // May close the folder since it's not needed any longer. This will not
        // expunge any deleted messages (which usually occurs on Close() call)
        // since we used ExamineFolder to select the folder. Unlike SelectFolder,
        // ExamineFolder selects folder in read-only mode.
        imp.Close();

        // Upload the message and assign the current datetime and timezone
        // of the server as the date of receiving the message by the server
        // (INTERNALDATE in IMAP4 terms).
        imp.UploadMessage(msg, "Draft", flags, null);

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Connect to the server and log in the account.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")

        ' Create a new message. Assume we need to save a draft of the message.
        Dim msg As New MailMessage

        ' Try to select Draft folder and create it if needed.
        ' We do not need to select the folder for uploading but
        ' we need to check if it's permitted to use non-system flags
        ' (such as "$Personal") in this folder.
        Try
            imp.ExamineFolder("Draft")
        Catch e As MailBeeImapNegativeResponseException
            If e.CompletionResult = "NO" Then
                imp.CreateFolder("Draft")
                imp.ExamineFolder("Draft")
            Else
                Throw
            End If
        End Try

        Dim flags As String = MessageFlagSet.SystemFlagsToString(SystemMessageFlags.Draft)

        ' Add "$Personal" flag if it's allowed for this folder.
        If (imp.PermanentFlags.SystemFlags And SystemMessageFlags.CanCreate) > 0 Then
            flags &= " $Personal"
        End If

        ' May close the folder since it's not needed any longer. This will not
        ' expunge any deleted messages (which usually occurs on Close() call)
        ' since we used ExamineFolder to select the folder. Unlike SelectFolder,
        ' ExamineFolder selects folder in read-only mode.
        imp.Close()

        ' Upload the message and assign the current datetime and timezone
        ' of the server as the date of receiving the message by the server
        ' (INTERNALDATE in IMAP4 terms).
        imp.UploadMessage(msg, "Draft", flags, CType(Nothing, String))

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
UploadMessage Overload
MailBee.ImapMail Namespace


Imap.UploadMessage Method (MailMessage, String, String, String, Boolean, UidPlusResult)

ImapUploadMessage Method (MailMessage, String, String, String, Boolean, UidPlusResult)
Uploads a mail message to the specified folder, assigns the specified date and flags to this message, and retrieves UID assigned to the uploaded message by the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UploadMessage(
    MailMessage msg,
    string folderName,
    string flags,
    string dateTimeString,
    bool batchMode,
    UidPlusResult result
)
Public Function UploadMessage (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dateTimeString As String,
    batchMode As Boolean,
    result As UidPlusResult
) As Boolean

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dateTimeString
Type: SystemString
The string containing datetime (in IMAP4 format) to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server), or a null reference to let the server assign its current datetime value.
batchMode
Type: SystemBoolean
If true and LITERAL+ extension is supported by the server, the message will be uploaded in a single network operation; otherwise, in two operations.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the upload operation reported by UIDPLUS enabled server (the outcome includes the UID assigned to the uploaded message and the UIDVALIDITY of the folder the message was uploaded to), or a null reference if the application does not need this information.

Return Value

Type: Boolean
true if the message was uploaded successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method implements APPEND command of the IMAP4 protocol.

To upload a file, the developer can first load it into MailMessage object using LoadMessage(String) method, and then call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) passing a reference to this MailMessage object. There is no extra overhead on parsing the message since LoadMessage(String) just reads a file into memory. The MailMessage won't parse the contained message unless the application starts accessing its properties or methods (so-called "lazy" model).

To upload a mail message just sent using Smtp component, the developer call UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method passing a reference to the Message property.

To get standard message flags as string in IMAP4 format (e.g. "\Seen \Flagged"), the developer can use SystemFlagsToString(SystemMessageFlags) method.

In addition to the flags specified by the application, the server also sets "\Recent" flag. Thus, the uploaded message will always have at least "\Recent" flag set.

To get datetime string in IMAP4 format (e.g. "01-May-2004 05:26:59 -0600"), the developer can use GetImapDateTimeString method.

batchMode value is ignored if the server does not support LITERAL+ extension. However, even if LITERAL+ is supported, the developer may still decide not to use batch mode if there is a risk that the server will reject the message due to its size. If this happens, the client will waste bandwidth transferring the entire message. If the client wouldn't have used the LITERAL+, this could have been avoided, because the server would have rejected the initial small request containing the length of the data to be uploaded, and thus second large request containing the actual message data would have never been sent. In general, however, if the application is not going to upload very large messages frequently, it's more effective to keep batch mode on. Other overloads of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method always upload messages in batch mode if LITERAL+ is supported.

When result is specified and the server supports and correctly implements UIDPLUS extension, UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method will set the supplied UidPlusResult object properties as below:

Property | Value
IsValid | true
IsSupported | true
SrcUids | null
SrcUidString | null
DestUids | The UidCollection object containing a single value of the UID assigned to the uploaded message.
DestUidString | The string containing the UID assigned to the uploaded message.
DestUidValidity | The UIDVALIDITY of the folder the message was uploaded to.

If UIDPLUS capability is not supported by the server, IsSupported will be set to false. When working with the server which lacks UIDPLUS support, the application can obtain UID of the uploaded message from UidNext value of FolderStatus object returned by GetFolderStatus(String) method. However, the application must call GetFolderStatus(String) method BEFORE making upload (see the sample).

The developer can also try to avoid calling GetFolderStatus(String) method if the UIDNEXT value is already available in UidNext property (the destination folder must be selected in this case, and some other restrictions apply, see remarks in UidNext topic for more information).

Some servers claim they support UIDPLUS but in fact there is no UIDPLUS data in the response (of the data has incorrect format). IsSupported will still be true but IsValid will be false in this case.

Examples
This sample loads the mail message from a file, and then uploads it to the Inbox folder on the server specifying "12-Apr-2006 19:30:00 +0100" as date of receiving the message by the server (INTERNALDATE), and setting "\Seen" and "\Flagged" flags (the server will also set "\Recent" flag). Finally, the UID value assigned to the message is displayed in the console. If UIDPLUS extension is supported, it's used. Otherwise, the application obtains the UID value downloading the status of Inbox folder prior to making upload.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server and log in the account.
        imp.Connect("mail.server.com");
        imp.Login("jdoe", "secret");

        // Load the message from C:\Temp\message.eml file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\message.eml");

        // Prepare the object that will receive upload results.
        UidPlusResult res = new UidPlusResult();

        long uid = 0;

        if (imp.GetExtension("UIDPLUS") == null)
        {
            FolderStatus status = imp.GetFolderStatus("Inbox");
            uid = status.UidNext;
        }

        // Upload the message and fill res with upload results.
        imp.UploadMessage(msg, "Inbox",
            MessageFlagSet.SystemFlagsToString(
            SystemMessageFlags.Seen | SystemMessageFlags.Flagged),
            "12-Apr-2006 19:30:00 +0100", true, res);

        if (res.IsSupported)
        {
            Console.WriteLine("UID of the uploaded message is " +
                res.DestUidString + ", UIDPLUS supported.");
        }
        else
        {
            Console.WriteLine("UID of the uploaded message is " +
                uid.ToString() + ", UIDPLUS not supported.");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    Sub Main()
        Dim imp As New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")

        ' Load the message from C:\Temp\message.eml file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Temp\message.eml")

        ' Prepare the object that will receive upload results.
        Dim res As New UidPlusResult

        Dim uid As Long = 0

        If Not imp.GetExtension("UIDPLUS") Is Nothing Then
            Dim status As FolderStatus = imp.GetFolderStatus("Inbox")
            uid = status.UidNext
        End If

        ' Upload the message and fill res with upload results.
        imp.UploadMessage(msg, "Inbox", _
            MessageFlagSet.SystemFlagsToString( _
            SystemMessageFlags.Seen Or SystemMessageFlags.Flagged), _
            "12-Apr-2006 19:30:00 +0100", True, res)

        If res.IsSupported Then
            Console.WriteLine("UID of the uploaded message is " & _
             res.DestUidString & ", UIDPLUS supported.")
        Else
            Console.WriteLine("UID of the uploaded message is " & _
             uid.ToString() & ", UIDPLUS not supported.")
        End If

        ' Disconnect from the server.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
UploadMessage Overload
MailBee.ImapMail Namespace
MailBee.ImapMailUidPlusResult


Imap.UploadMessageAsync Method

ImapUploadMessageAsync Method
Overload List
 | Name | Description
Public method | UploadMessageAsync(MailMessage, String) | async/await version of UploadMessage(MailMessage, String).
Public method | UploadMessageAsync(MailMessage, String, SystemMessageFlags) | async/await version of UploadMessage(MailMessage, String, SystemMessageFlags).
Public method | UploadMessageAsync(MailMessage, String, String, DateTime) | async/await version of UploadMessage(MailMessage, String, String, DateTime).
Public method | UploadMessageAsync(MailMessage, String, String, String) | async/await version of UploadMessage(MailMessage, String, String, String).
Public method | UploadMessageAsync(MailMessage, String, String, String, Boolean, UidPlusResult) | async/await version of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult).
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.UploadMessageAsync Method (MailMessage, String)

ImapUploadMessageAsync Method (MailMessage, String)
async/await version of UploadMessage(MailMessage, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    MailMessage msg,
    string folderName
)
Public Function UploadMessageAsync (
    msg As MailMessage,
    folderName As String
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
UploadMessageAsync Overload
MailBee.ImapMail Namespace


Imap.UploadMessageAsync Method (MailMessage, String, SystemMessageFlags)

ImapUploadMessageAsync Method (MailMessage, String, SystemMessageFlags)
async/await version of UploadMessage(MailMessage, String, SystemMessageFlags).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    MailMessage msg,
    string folderName,
    SystemMessageFlags systemFlags
)
Public Function UploadMessageAsync (
    msg As MailMessage,
    folderName As String,
    systemFlags As SystemMessageFlags
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
systemFlags
Type: MailBee.ImapMailSystemMessageFlags
A set of flags to be assigned to the message.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
UploadMessageAsync Overload
MailBee.ImapMail Namespace


Imap.UploadMessageAsync Method (MailMessage, String, String, DateTime)

ImapUploadMessageAsync Method (MailMessage, String, String, DateTime)
async/await version of UploadMessage(MailMessage, String, String, DateTime).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    MailMessage msg,
    string folderName,
    string flags,
    DateTime dt
)
Public Function UploadMessageAsync (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dt As DateTime
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dt
Type: SystemDateTime
The datetime to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server). If MinValue, the server will assign this date itself.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
UploadMessageAsync Overload
MailBee.ImapMail Namespace


Imap.UploadMessageAsync Method (MailMessage, String, String, String)

ImapUploadMessageAsync Method (MailMessage, String, String, String)
async/await version of UploadMessage(MailMessage, String, String, String).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    MailMessage msg,
    string folderName,
    string flags,
    string dateTimeString
)
Public Function UploadMessageAsync (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dateTimeString As String
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dateTimeString
Type: SystemString
The string containing datetime (in IMAP4 format) to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server), or a null reference to let the server assign its current datetime value.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
UploadMessageAsync Overload
MailBee.ImapMail Namespace


Imap.UploadMessageAsync Method (MailMessage, String, String, String, Boolean, UidPlusResult)

ImapUploadMessageAsync Method (MailMessage, String, String, String, Boolean, UidPlusResult)
async/await version of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> UploadMessageAsync(
    MailMessage msg,
    string folderName,
    string flags,
    string dateTimeString,
    bool batchMode,
    UidPlusResult result
)
Public Function UploadMessageAsync (
    msg As MailMessage,
    folderName As String,
    flags As String,
    dateTimeString As String,
    batchMode As Boolean,
    result As UidPlusResult
) As Task(Of Boolean)

Parameters

msg
Type: MailBee.MimeMailMessage
A reference to the MailMessage object representing the message to be uploaded.
folderName
Type: SystemString
The full name of the folder to upload the message to.
flags
Type: SystemString
The string containing the message flags (in IMAP4 format) to be assigned to the message, or a null reference (Nothing in Visual Basic) to set default flags at the discretion of the server.
dateTimeString
Type: SystemString
The string containing datetime (in IMAP4 format) to be assigned to the INTERNALDATE attribute of the message (the date of receiving the message by the server), or a null reference to let the server assign its current datetime value.
batchMode
Type: SystemBoolean
If true and LITERAL+ extension is supported by the server, the message will be uploaded in a single network operation; otherwise, in two operations.
result
Type: MailBee.ImapMailUidPlusResult
A reference to the UidPlusResult object to be filled with the outcome of the upload operation reported by UIDPLUS enabled server (the outcome includes the UID assigned to the uploaded message and the UIDVALIDITY of the folder the message was uploaded to), or a null reference if the application does not need this information.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Imap Class
UploadMessageAsync Overload
MailBee.ImapMail Namespace


Imap.Wait Method

ImapWait Method
Overload List
 | Name | Description
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Wait Method

ImapWait Method

Note: This API is now obsolete.

Waits until the currently running (if any) asynchronous method is finished.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+.")]
public void Wait()
<ObsoleteAttribute("This method is obsolete in .NET 4.5+.")>
Public Sub Wait
Exceptions
Exception | Condition
MailBeeInvalidStateException | RaiseEventsViaMessageLoop is true
Remarks
This method should only be used in WinForms applications in the scenarios when the application message loop is blocked and events raised by asynchronous methods get no chance to be processed.
Caution note Caution
RaiseEventsViaMessageLoop property must be set to false prior to using this method. This is required in order to switch event marshaling mechanism from sending events to the application message loop to the internal thread-independent event processor.

Usually, when the developer uses asynchronous methods which might raise events, it's not possible to use methods like WaitOne(Int32, Boolean), since they would block the message loop and thus prevent events (which are raised on the message loop thread) from getting processed. Wait method provides an alternative approach which addresses the problem.

Another alternative (in WinForms application) to using Wait method is to never block the application message loop. See BeginExecuteCustomCommand(String, String, AsyncCallback, Object) method for the code example.

Note Note
In many cases, it's easier not to use events at all but derive a new class from Imap class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Imap Class
Wait Overload
MailBee.ImapMail Namespace


Imap.Wait Method (Int32)

ImapWait Method (Int32)

Note: This API is now obsolete.

Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+.")]
public bool Wait(
    int timeoutInterval
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+.")>
Public Function Wait (
    timeoutInterval As Integer
) As Boolean

Parameters

timeoutInterval
Type: SystemInt32
The amount of time (in milliseconds) the method will wait completion of the currently running asynchronous method before returning false.

Return Value

Type: Boolean
true if the asynchronous method has finished execution during the specified amount of time, false if it's still running.
Exceptions
Exception | Condition
MailBeeInvalidStateException | RaiseEventsViaMessageLoop is true
Remarks
Note Note
.NET 4.5+ apps should use XXXAsync methods which can be awaited. The current method is suitable for BeginXXX/EndXXX methods only which are now deprecated.
This method should only be used in WinForms applications in the scenarios when the application message loop is blocked and events raised by asynchronous methods get no chance to be processed.
Caution note Caution
RaiseEventsViaMessageLoop property must be set to false prior to using this method. This is required in order to switch event marshaling mechanism from sending events to the application message loop to the internal thread-independent event processor.
Usually, when the developer wants to use asynchronous methods which might raise events in a WinForm application, it's not possible to use methods like WaitOne(Int32, Boolean), since they would block the message loop and thus prevent events (which are raised on the message loop thread) from getting processed. Wait method provides an alternative approach which addresses the problem.
Note Note
The developer can also use this method with timeoutInterval set to 0 in order to process currently pending MailBee events. This is useful if some lengthy work is performed on the message loop thread, and the developer wants to periodically let MailBee events get processed and then continue the lengthy work without waiting for the completion of the asynchronous method. See BeginConnect(String, Int32, Socket, EndPoint, AsyncCallback, Object) method for examples.
Another alternative (in WinForms application) to using Wait method is to never block the application message loop. See BeginExecuteCustomCommand(String, String, AsyncCallback, Object) method for the code example.
Note Note
In many cases, it's easier not to use events at all but derive a new class from Imap class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Imap Class
Wait Overload
MailBee.ImapMail Namespace


Imap Properties

Imap Properties

The Imap type exposes the following members.

Properties
 | Name | Description
Public property | EnableLastDownloaded | Gets or sets whether MailBee should save currently downloaded envelopes in LastDownloadedEnvelopes property.
Public property | Flags | Gets the flags that are applicable for the currently selected folder.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | IsConnected | Indicates whether the component is connected to the server.
Public property | IsFolderSelected | Indicates if a folder is currently selected in the mail account.
Public property | IsIdle | Gets if the component is in IDLE state.
Public property | IsLoggedIn | Indicates whether the component has already successfully authenticated on the server and logged in the user account.
Public property | IsSslConnection | Indicates whether the current connection (if any) is secured with TLS/SSL layer.
 | LastDownloadedEnvelopes | Gets the collection of the envelopes downloaded to the current moment.
Public property | LastResult | Gets a numeric code of the last error.
 | LicenseKey | Obsolete. Assigns the license key.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
Public property | MessageCount | Gets the number of messages in the currently selected folder.
Public property | PermanentFlags | Gets the flags the client can change permanently.
 | Proxy | Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RaiseEventsViaMessageLoop | Gets or sets whether the events will be raised on the message loop of the application or not.
Public property | RecentCount | Gets the number of recent messages in the currently selected folder.
Public property | RequestEncoding | Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the mail server.
Public property | ResponseEncoding | Gets or sets the encoding used to convert a byte data received from the mail server into a string.
Public property | SetSeenForEntireMessages | Specifies if MailBee should also set SEEN flag when downloading entire messages.
Public property | Site | Gets or sets the object to be used as a site for the component.
 | SslCertificates | Provides access to the client and server SSL certificate settings.
 | SslMode | Gets or sets how the component should establish TLS/SSL connection with the mail server.
Public property | SslProtocol | Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | UidNext | Gets the UID to be assigned to the next message in the currently selected folder.
Public property | UidValidity | Gets the UIDVALIDITY value of the currently selected folder.
Public property | Unseen | Gets the ordinal message number of the first message which does not have "\Seen" flag set.
Public property | UseXList | Gets or sets whether to use XLIST extension which allows the application to detect special folders like Sent, Drafts, Trash.
Public property | Utf7EncodeFolderNames | Gets or sets whether MailBee should automatically encode folder names with UTF-7 Modified encoding.
Public property | Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.EnableLastDownloaded Property

ImapEnableLastDownloaded Property
Gets or sets whether MailBee should save currently downloaded envelopes in LastDownloadedEnvelopes property.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EnableLastDownloaded { get; set; }
Public Property EnableLastDownloaded As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, any method of Imap component which receives FETCH responses from the server (like DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String), DownloadEntireMessages(String, Boolean), GetFolderSize, etc) will populate LastDownloadedEnvelopes collection with Envelope objects received and parsed during the method execution; if false, LastDownloadedEnvelopes property will always return a null reference (Nothing in Visual Basic). The default value is false.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLastDownloadedEnvelopes


Imap.Flags Property

ImapFlags Property
Gets the flags that are applicable for the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageFlagSet Flags { get; }
Public ReadOnly Property Flags As MessageFlagSet
    Get

Property Value

Type: MessageFlagSet
A reference to the MessageFlagSet object representing the flags that are applicable for the currently selected folder.
Remarks

If the folder is selected, the flag list contains the system-defined flags at a minimum (except "\Recent" flag which cannot be edited by the client). Typically, the following flags are returned: "\Answered", "\Flagged", "\Deleted", "\Seen", "\Draft". Also, this list may contain other flags specific to certain servers (like "$Spam", "$Personal", etc).

If no folder is selected, the flag list will be empty.

To access the flag list as a string, the developer can use ToString method. To access the system-defined flags of the flag list, the SystemFlags property can be used.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.IsAborted Property

ImapIsAborted Property
Indicates whether Abort method has been called for the component.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsAborted { get; }
Public ReadOnly Property IsAborted As Boolean
    Get

Property Value

Type: Boolean
true if Abort method has already been called; otherwise, false. The default value is false.
Remarks

In aborted state, the component does not raise any events, and most methods, if called, will immediately return an error or throw an exception.

ResetState method can be used to restore the component back to operational state.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.IsBusy Property

ImapIsBusy Property
Indicates whether the component is performing a lengthy operation.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBusy { get; }
Public ReadOnly Property IsBusy As Boolean
    Get

Property Value

Type: Boolean
A bool value indicating whether the component is busy because it's doing some work.
Remarks
When the component is busy, it's not possible to start another lengthy operation. For instance, if the component connects to the server or transfers data over the network, no other network operation can be started at this time. Any attempt to do so will result in MailBeeInvalidStateException.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.IsConnected Property

ImapIsConnected Property
Indicates whether the component is connected to the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsConnected { get; }
Public ReadOnly Property IsConnected As Boolean
    Get

Property Value

Type: Boolean
true if the component is connected to the server; otherwise, false.
Remarks

This property only reflects the state of client side of the connection. If the server forcibly closed the connection on its side, the application won't know about this until it makes an attempt to send or receive data.

In other words, it reflectes the state of the connection at the time when the last data to the moment was received.

To check if you're still connected to the server from its point of view, issue a command to the server, such as Noop. If the method throws an exception, this means the server has closed the connection. If no exception occurred, the connection is still up.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.IsFolderSelected Property

ImapIsFolderSelected Property
Indicates if a folder is currently selected in the mail account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsFolderSelected { get; }
Public ReadOnly Property IsFolderSelected As Boolean
    Get

Property Value

Type: Boolean
true if a folder has already been selected; otherwise, false.
Remarks
Many methods of the Imap component require a folder be selected in order to perform successfully. To select a folder, the developer can use SelectFolder(String) or ExamineFolder(String) methods. An IMAP4 mail account is guaranteed to contain at least "Inbox" folder.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.IsIdle Property

ImapIsIdle Property
Gets if the component is in IDLE state.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsIdle { get; }
Public ReadOnly Property IsIdle As Boolean
    Get

Property Value

Type: Boolean
true if the component is passively waiting/receiving/processing responses from the server and not sending any commands to the server.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapIdle


Imap.IsLoggedIn Property

ImapIsLoggedIn Property
Indicates whether the component has already successfully authenticated on the server and logged in the user account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsLoggedIn { get; }
Public ReadOnly Property IsLoggedIn As Boolean
    Get

Property Value

Type: Boolean
true if already logged in the user account on the server; otherwise, false.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.IsSslConnection Property

ImapIsSslConnection Property
Indicates whether the current connection (if any) is secured with TLS/SSL layer.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSslConnection { get; }
Public ReadOnly Property IsSslConnection As Boolean
    Get

Property Value

Type: Boolean
true if the current connection is TLS/SSL; false if the connection is not secure.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.LastDownloadedEnvelopes Property

ImapLastDownloadedEnvelopes Property
Gets the collection of the envelopes downloaded to the current moment.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopeCollection LastDownloadedEnvelopes { get; }
Public ReadOnly Property LastDownloadedEnvelopes As EnvelopeCollection
    Get

Property Value

Type: EnvelopeCollection
A reference to the collection of the envelopes downloaded to the current moment by the corresponding method of Imap component, or a null reference (Nothing in Visual Basic) if EnableLastDownloaded is false or no method receiving envelopes has already been called (or if such method failed prior to starting receiving envelopes).
Remarks
Note Note
This is an advanced property which serves special purposes. It's activated via setting EnableLastDownloaded prior to calling a method which requests envelopes from the server.

This property can be used to get downloaded envelopes in the case if the corresponding method failed. Imap methods throw an exception or return a null reference on failure. Sometimes, however, the developer still wishes to get envelopes which had already been received to the moment of failure (for instance, if 100 envelopes had been received and error occurred for envelope #101). In this case, the developer can use this property to get envelopes which had already been received and parsed to the moment of the failure.

When this collection is not needed any longer, the developer should set EnableLastDownloaded to false to free the resources. Also, LastDownloadedEnvelopes will be reset to a null reference with a new call of any method requesting envelopes from the server.

Examples

This sample demonstrates reliable approach to downloading messages from an IMAP4 account. The code tolerates disconnections and other errors which may occur during downloading messages. If any problem occurs, the code reconnects to the server if needed and attempts to download the remaining messages (already downloaded messages are not downloaded again, however). Also, the code execution won't end up in an endless loop in the case of permanent errors (if no messages had been downloaded at all, the code won't try again).

To simulate connection drops during the IMAP4 session, the code suddenly closes the connection during getting message data from the server.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static int  traffic;
    static bool downloadingEnvelopes;

    // We use Imap.DataReceived event to simulate connection drop during
    // getting message data from the server. We do this through closing
    // the connection after 50000 bytes of message data has been received from the
    // server. This may occur multiple times (for instance, if there is 1MB of mail
    // in the inbox, the connection will be dropped about 20 times).
    // If, however, there is a message larger than 50KB in the inbox, the download process
    // will stop because it would otherwise end up in an endless loop (because this code
    // always disconnects on getting 50-th KB of the data and it would never have received
    // such message completely).
    static void imp_DataReceived(object sender, DataTransferEventArgs e)
    {
        if (downloadingEnvelopes)
        {
            traffic += e.Data.Length;

            // Increase 50000 to a larger value if you wish to test this code with
            // a mailbox containing large messages (larger than 50KB).
            if (traffic > 50000)
            {
                ((Imap)sender).Log.WriteLine("SIMULATE CONNECTION DROP");
                ((Imap)sender).GetSocket().Close();
            }
        }
    }

    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Enable logging IMAP4 session into a file. Useful for troubleshooting.
        // Also, this log can be used to track the history of disconnections and
        // reconnections during downloading messages.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Attach to a DataReceived event which will be used for simulating
        // connection failures.
        imp.DataReceived += new DataTransferEventHandler(imp_DataReceived);

        // Will set it to true once either everything has been downloaded
        // or a permanent error has occurred.
        bool finished = false;

        // Remember UID of the last message which had already been downloaded.
        // After reconnecting, we'll download envelopes with UIDs larger than
        // lastUid. For the first time, set it to 0 (which is less than UID of
        // any message because minimum value of UID is 1).
        long lastUid = 0;

        // We'll collect downloaded messages in this collection.
        EnvelopeCollection envs = new EnvelopeCollection();

        // Because we catch exceptions in this code but still want to know
        // which error has occurred in the case of permanent failure, we remember
        // the reason of it.
        MailBeeException permanentException = null;

        // Enable cache of envelopes downloaded during execution of the last method.
        imp.EnableLastDownloaded = true;

        do
        {
            // Prevent connection drop simulation when not downloading messages.
            downloadingEnvelopes = false;

            // Connect or reconnect to the server if required (and login/select inbox).
            if (!imp.IsConnected)
            {
                imp.Connect("mail.domain.com");
            }
            if (!imp.IsLoggedIn)
            {
                imp.Login("jdoe", "secret");
            }
            if (!imp.IsFolderSelected)
            {
                imp.SelectFolder("INBOX");
            }

            traffic = 0;

            try
            {
                // Enable connection drop simulation.
                downloadingEnvelopes = true;

                // Download the remaining messages.
                imp.DownloadEnvelopes((lastUid + 1).ToString() + ":*", true, EnvelopeParts.MessagePreview, -1);

                // Disable connection drop simulation.
                downloadingEnvelopes = false;

                // All's done.
                envs.Add(imp.LastDownloadedEnvelopes);
                finished = true;
            }
            catch (MailBeeException e)
            {
                downloadingEnvelopes = false;

                if (imp.LastDownloadedEnvelopes == null ||
                    imp.LastDownloadedEnvelopes.Count == 0)
                {
                    // Haven't got any messages. Assume this is permanent error
                    // (otherwise, we could get endless loop).
                    finished = true;
                    permanentException = e;
                }
                else
                {
                    // Error has occurred but some envelopes have still been
                    // downloaded. We'll proceed with getting the rest of messages.
                    envs.Add(imp.LastDownloadedEnvelopes);

                    // Get last UID from the value of UID of the last downloaded message.
                    lastUid = imp.LastDownloadedEnvelopes[imp.LastDownloadedEnvelopes.Count - 1].Uid;
                }
            }
        } while (!finished);

        // Clear and disable the cache of the last downloaded envelopes.
        imp.EnableLastDownloaded = false;

        if (imp.IsConnected)
        {
            // Attempt to disconnect (we need to catch MailBeeSocketObjectDisposedException
            // here because we simulated connection drop bypassing MailBee (using Socket.Close()
            // method) and Imap.IsConnected could remain true). In real world apps, this
            // is not required and Imap.IsConnected always reflects the actual state of
            // the connection.
            try
            {
                imp.Disconnect();
            }
            catch (MailBeeSocketObjectDisposedException) {}
        }

        // Display UIDs of the downloaded messages.
        foreach (Envelope env in envs)
        {
            Console.Write(env.Uid + " ");
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Class Sample
    Shared traffic As Integer
    Shared downloadingEnvelopes As Boolean

    ' We use Imap.DataReceived event to simulate connection drop during
    ' getting message data from the server. We do this through closing
    ' the connection after 50000 bytes of message data has been received from the
    ' server. This may occur multiple times (for instance, if there is 1MB of mail
    ' in the inbox, the connection will be dropped about 20 times).
    ' If, however, there is a message larger than 50KB in the inbox, the download process
    ' will stop because it would otherwise end up in an endless loop (because this code
    ' always disconnects on getting 50-th KB of the data and it would never have received
    ' such message completely).
    Shared Sub imp_DataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        If downloadingEnvelopes Then
            traffic += e.Data.Length

            ' Increase 50000 to a larger value if you wish to test this code with
            ' a mailbox containing large messages (larger than 50KB).
            If traffic > 50000 Then
                CType(sender, Imap).Log.WriteLine("SIMULATE CONNECTION DROP")
                CType(sender, Imap).GetSocket().Close()
            End If
        End If
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' Enable logging IMAP4 session into a file. Useful for troubleshooting.
        ' Also, this log can be used to track the history of disconnections and
        ' reconnections during downloading messages.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Attach to a DataReceived event which will be used for simulating
        ' connection failures.
        AddHandler imp.DataReceived, AddressOf imp_DataReceived

        ' Will set it to true once either everything has been downloaded
        ' or a permanent error has occurred.
        Dim finished As Boolean = False

        ' Remember UID of the last message which had already been downloaded.
        ' After reconnecting, we'll download envelopes with UIDs larger than
        ' lastUid. For the first time, set it to 0 (which is less than UID of
        ' any message because minimum value of UID is 1).
        Dim lastUid As Long = 0

        ' We'll collect downloaded messages in this collection.
        Dim envs As EnvelopeCollection = New EnvelopeCollection

        ' Because we catch exceptions in this code but still want to know
        ' which error has occurred in the case of permanent failure, we remember
        ' the reason of it.
        Dim permanentException As MailBeeException = Nothing

        ' Enable cache of envelopes downloaded during execution of the last method.
        imp.EnableLastDownloaded = True

        Do
            ' Prevent connection drop simulation when not downloading messages.
            downloadingEnvelopes = False

            ' Connect or reconnect to the server if required (and login/select inbox).
            If Not imp.IsConnected Then
                imp.Connect("mail.domain.com")
            End If
            If Not imp.IsLoggedIn Then
                imp.Login("jdoe", "secret")
            End If
            If Not imp.IsFolderSelected Then
                imp.SelectFolder("INBOX")
            End If

            traffic = 0

            Try
                ' Enable connection drop simulation.
                downloadingEnvelopes = True

                ' Download the remaining messages.
                imp.DownloadEnvelopes((lastUid + 1).ToString() & ":*", True, EnvelopeParts.MessagePreview, -1)

                ' Disable connection drop simulation.
                downloadingEnvelopes = False

                ' All's done.
                envs.Add(imp.LastDownloadedEnvelopes)
                finished = True
            Catch e As MailBeeException
                downloadingEnvelopes = False

                If imp.LastDownloadedEnvelopes Is Nothing Or imp.LastDownloadedEnvelopes.Count = 0 Then
                    ' Haven't got any messages. Assume this is permanent error
                    ' (otherwise, we could get endless loop).
                    finished = True
                    permanentException = e
                Else
                    ' Error has occurred but some envelopes have still been
                    ' downloaded. We'll proceed with getting the rest of messages.
                    envs.Add(imp.LastDownloadedEnvelopes)

                    ' Get last UID from the value of UID of the last downloaded message.
                    lastUid = imp.LastDownloadedEnvelopes(imp.LastDownloadedEnvelopes.Count - 1).Uid
                End If
            End Try
        Loop While Not finished

        ' Clear and disable the cache of the last downloaded envelopes.
        imp.EnableLastDownloaded = False

        If imp.IsConnected Then
            ' Attempt to disconnect (we need to catch MailBeeSocketObjectDisposedException
            ' here because we simulated connection drop bypassing MailBee (using Socket.Close()
            ' method) and Imap.IsConnected could remain true). In real world apps, this
            ' is not required and Imap.IsConnected always reflects the actual state of
            ' the connection.
            Try
                imp.Disconnect()
            Catch e As MailBeeSocketObjectDisposedException
            End Try
        End If

        ' Display UIDs of the downloaded messages.
        Dim env As Envelope
        For Each env In envs
            Console.Write(env.Uid & " ")
        Next
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapEnableLastDownloaded


Imap.LastResult Property

ImapLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.LicenseKey Property

ImapLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Log Property

ImapLog Property
Gets the object used for logging MailBee activities into a file or memory buffer.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Logger Log { get; }
Public ReadOnly Property Log As Logger
    Get

Property Value

Type: Logger
A reference to the object used for logging MailBee activities into a file or memory buffer.
Remarks
This property is never a null reference (Nothing in Visual Basic) even if logging is not used.
Examples
This sample sets file logging on and sets the filename of the log file.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.Log.Enabled = true;
imp.Log.Filename = @"C:\Temp\log.txt";
imp.Connect("mail.domain.com");
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.Log.Enabled = True
imp.Log.Filename = "C:\Temp\log.txt"
imp.Connect("mail.domain.com")
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.MessageCount Property

ImapMessageCount Property
Gets the number of messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageCount { get; }
Public ReadOnly Property MessageCount As Integer
    Get

Property Value

Type: Int32
The integer value containing the number of messages in the currently selected folder, or 0 if no folder is selected.
Remarks
Ordinal message number of the first message in a folder is 1 (not 0). Ordinal message number of the last message in a folder is MessageCount.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.PermanentFlags Property

ImapPermanentFlags Property
Gets the flags the client can change permanently.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageFlagSet PermanentFlags { get; }
Public ReadOnly Property PermanentFlags As MessageFlagSet
    Get

Property Value

Type: MessageFlagSet
A reference to the MessageFlagSet object representing the currently selected folder flags that can changed by the client permanently.
Remarks
Any flags that are in the Flags but not in the PermanentFlags, can not be set permanently (i.e. across sessions). If the client attempts to store a flag that is not in the PermanentFlags list, the server will either ignore the change or store the state change for the remainder of the current session only. The PermanentFlags list can also include the special flag "\*" (CanCreate), which indicates that it is possible to create new flags by attempting to apply those flags to the messages in the folder.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Proxy Property

ImapProxy Property
Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ProxyServer Proxy { get; }
Public ReadOnly Property Proxy As ProxyServer
    Get

Property Value

Type: ProxyServer
A reference to the proxy server settings.
Remarks
By default, proxy server is not used. The developer can change this to make MailBee use SOCKS4, SOCKS5, or HTTP proxy server. This is useful when a firewall prohibits direct connections with a mail server but permits connections via a proxy.
Examples
This console sample establishes connection with the mail server via an HTTP proxy server which requires clients to authenticate themselves.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Proxy;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();
        imp.Proxy.Name = "proxy.server.com";
        imp.Proxy.Protocol = ProxyProtocol.Http;
        imp.Proxy.Port = 808;
        imp.Proxy.AccountName = "jdoe";
        imp.Proxy.Password = "secret";
        imp.Connect("mail.company.com");
        Console.WriteLine("Connected via a proxy server");
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Proxy

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap
        imp.Proxy.Name = "proxy.server.com"
        imp.Proxy.Protocol = ProxyProtocol.Http
        imp.Proxy.Port = 808
        imp.Proxy.AccountName = "jdoe"
        imp.Proxy.Password = "secret"
        imp.Connect("mail.company.com")
        Console.WriteLine("Connected via a proxy server")
        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
MailBee.ProxyProxyServer


Imap.RaiseEvents Property

ImapRaiseEvents Property
Gets or sets whether the component will raise any events.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEvents { get; set; }
Public Property RaiseEvents As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will raise any events. The default value is true.
Remarks
If this property is false, OnEventName methods will also not be called.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.RaiseEventsViaMessageLoop Property

ImapRaiseEventsViaMessageLoop Property
Gets or sets whether the events will be raised on the message loop of the application or not.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEventsViaMessageLoop { get; set; }
Public Property RaiseEventsViaMessageLoop As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the events will be raised on the message loop of the application or not. The default value is true.
Remarks

This property is only meaningful in WinForms applications where events and asynchronous methods are used, and the developer needs to block the message loop for some reason (usually, to wait for completion of an asynchronous method).

In this case, you should set this property to false and use Wait method to wait until asynchronous MailBee method is finished. See Wait method for more information.

The above also applies to synchronous methods if they are called on worker (non-UI) threads. If, however, the application does not use asynchronous methods of MailBee (and never calls its synchronous methods on non-UI threads), it should NOT attempt to set RaiseEventsViaMessageLoop to false or use Wait method.

Note Note
If you develop non-WinForms application (such as web or console application), you do not need to set this property or use Wait method regardless if the application uses worker threads or not.
Another alternative (in WinForms application) to using Wait method is to never block the application message loop. See BeginExecuteCustomCommand(String, String, AsyncCallback, Object) method for the code example.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.RecentCount Property

ImapRecentCount Property
Gets the number of recent messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int RecentCount { get; }
Public ReadOnly Property RecentCount As Integer
    Get

Property Value

Type: Int32
The integer value containing the number of messages having "\Recent" flag in the currently selected folder, or 0 if no folder is selected.
Remarks

"\Recent" flag indicates a message is "recently" arrived in the folder. This session is the first session to have been notified about this message; if the session is read-write (the folder was selected using SelectFolder(String) method), subsequent sessions will not see "\Recent" set for this message. This flag can not be altered by the client.

If it is not possible to determine whether or not this session is the first session to be notified about a message, then that message SHOULD be considered recent.

If multiple connections have the same folder selected simultaneously, it is undefined which of these connections will see newly-arrived messages with "\Recent" set and which will see it without "\Recent" set.

To prevent messages from loosing "\Recent" flag (i.e. to monitor a folder keeping its state unchanged), the developer should select a folder using ExamineFolder(String) method instead of SelectFolder(String).

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.RequestEncoding Property

ImapRequestEncoding Property
Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding RequestEncoding { get; set; }
Public Property RequestEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert a string into a bytes stream which is then sent to the mail server. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ResponseEncoding Property

ImapResponseEncoding Property
Gets or sets the encoding used to convert a byte data received from the mail server into a string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ResponseEncoding { get; set; }
Public Property ResponseEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert a byte data received from the mail server into a string. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SetSeenForEntireMessages Property

ImapSetSeenForEntireMessages Property
Specifies if MailBee should also set SEEN flag when downloading entire messages.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetSeenForEntireMessages { get; set; }
Public Property SetSeenForEntireMessages As Boolean
    Get
    Set

Property Value

Type: Boolean
true if MailBee also sets SEEN flags when downloading entire messages; false if MailBee does not change message flags on downloading entire messages. The default value is false.
Remarks
By default, MailBee won't set SEEN flag when downloading a message. You can override this behavior with this property.
Note Note
This property affects only DownloadEntireMessage(Int64, Boolean) and DownloadEntireMessages(String, Boolean) methods. Methods like DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32) do not depend on this property and provide their own means of controlling whether to set SEEN flag or not.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Site Property

ImapSite Property
Gets or sets the object to be used as a site for the component.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual ISite Site { get; set; }
Public Overridable Property Site As ISite
    Get
    Set

Property Value

Type: ISite
A reference to the object to be used as a site for the component. The default value is a null reference (Nothing in Visual Basic).

Implements

IComponentSite
Remarks
The developer does not need to set this property. It's used by RAD tools such as form designers.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SslCertificates Property

ImapSslCertificates Property
Provides access to the client and server SSL certificate settings.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ClientServerCertificates SslCertificates { get; }
Public ReadOnly Property SslCertificates As ClientServerCertificates
    Get

Property Value

Type: ClientServerCertificates
A reference to the client and server SSL certificate settings.
Remarks

The following code should be used to access the server certificate (assuming imp is an Imap component instance): imp.SslCertificates.Server. To set the client certificate, the developer should assign imp.SslCertificates.Client property.

Note Note
To use SSL certificates, your license key must include Security license. See Powerup class for details.
Examples
This console sample establishes secure connection with the mail server using the private certificate of the client and then displays various information about the server certificate. The client certificate is taken from a file (MailBee can also read certificates from the registry, see CertificateStore class description for details).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Security;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();
        imp.SslMode = SslStartupMode.OnConnect;
        imp.SslCertificates.Client = new Certificate(@"C:\my.pfx", CertFileType.Pfx, "secret");
        imp.Connect("mail.domain.com", 993);
        Console.WriteLine("The server certificate info");
        Console.WriteLine("===========================");
        Console.WriteLine("Issued by:    " + imp.SslCertificates.Server.IssuedBy);
        Console.WriteLine("Issued to:    " + imp.SslCertificates.Server.IssuedTo);
        Console.WriteLine("Valid from:    " + imp.SslCertificates.Server.ValidFromDate);
        Console.WriteLine("Valid to:    " + imp.SslCertificates.Server.ValidToDate);
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Security

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap
        imp.SslMode = SslStartupMode.OnConnect
        imp.SslCertificates.Client = New Certificate("C:\my.pfx", CertFileType.Pfx, "secret")
        imp.Connect("mail.domain.com", 993)
        Console.WriteLine("The server certificate info")
        Console.WriteLine("===========================")
        Console.WriteLine("Issued by:    " & imp.SslCertificates.Server.IssuedBy)
        Console.WriteLine("Issued to:    " & imp.SslCertificates.Server.IssuedTo)
        Console.WriteLine("Valid from:    " & imp.SslCertificates.Server.ValidFromDate)
        Console.WriteLine("Valid to:    " & imp.SslCertificates.Server.ValidToDate)
        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
MailBee.SecurityCertificate
MailBee.SecurityCertificateStore


Imap.SslMode Property

ImapSslMode Property
Gets or sets how the component should establish TLS/SSL connection with the mail server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SslStartupMode SslMode { get; set; }
Public Property SslMode As SslStartupMode
    Get
    Set

Property Value

Type: SslStartupMode
One of SslStartupMode values specifying if and how the component should establish TLS/SSL connection with the mail server. The default value is Manual which means the connection won't be established in TLS/SSL mode unless the developer manually calls StartTls method.
Remarks

AutodetectPortAndSslMode property may cause MailBee to automatically enable TLS/SSL for some well-known hosts or ports even if SslMode property has its default value.

Note Note
Not all mail servers support TLS/SSL functionality. Also, some servers support only newest TLS versions (see SslProtocol topic for details).
Examples
This sample connects to the mail server on dedicated IMAP4 SSL port 993, logs in the mail account and displays the list of all folders in this account.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;
using MailBee.Security;

// The actual code (put it into a method of your class).
Imap imp = new Imap();
imp.SslMode = SslStartupMode.OnConnect;
imp.Connect("mail.domain.com", 993);
imp.Login("jdoe", "secret");
FolderCollection folders = imp.DownloadFolders();
foreach (Folder imapFolder in folders)
{
    Console.WriteLine(imapFolder.Name);
}
imp.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim imp As New Imap
imp.SslMode = SslStartupMode.OnConnect
imp.Connect("mail.domain.com", 993)
imp.Login("jdoe", "secret")
Dim folders As FolderCollection = imp.DownloadFolders()
For Each imapFolder As Folder In folders
    Console.WriteLine(imapFolder.Name)
Next
imp.Disconnect()
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSslProtocol
ImapStartTls


Imap.SslProtocol Property

ImapSslProtocol Property
Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SecurityProtocol SslProtocol { get; set; }
Public Property SslProtocol As SecurityProtocol
    Get
    Set

Property Value

Type: SecurityProtocol
One of SecurityProtocol values specifying the security protocol to be used for performing TLS/SSL negotiation and data encryption. The default value is Auto.
Remarks
The default value allows MailBee to select the best (the most secure) protocol supported by the mail server. However, if the mail server does not support automatic protocol negotiation, it will likely close the connection (MailBeeSocketResetException will be thrown). In this case, the application should set this property to non-Auto value (such as Tls1).
Note Note
In case of UWP platform, MailBee always uses TlsAuto setting.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.SynchronizingObject Property

ImapSynchronizingObject Property
Gets or sets the object used to marshal the calls of the event handlers.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ISynchronizeInvoke SynchronizingObject { get; set; }
Public Property SynchronizingObject As ISynchronizeInvoke
    Get
    Set

Property Value

Type: ISynchronizeInvoke
A reference to the object on whose thread the events should be raised. The default value is a null reference (Nothing in Visual Basic) which tells MailBee to determine the appropriate marshaling object automatically.
Remarks
Usually, you do not need to set this property because MailBee can automatically marshal events to proper threads.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.ThrowExceptions Property

ImapThrowExceptions Property
Gets or sets whether the component will throw exceptions on errors.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the component methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult, GetErrorDescription, GetServerResponse, GetSocketError members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee usage will still be thrown. Typical examples of such errors are: passing invalid arguments to methods, calling methods or settings properties in illegal state (for instance, an attempt to start an asynchronous method while another asynchronous method is not yet finished), etc. Such exceptions indicate programming errors in the application being developed, and thus cannot be suppressed.

ThrowExceptions property does not control whether to throw exceptions which occur due to logging errors (such as "log file cannot be written to", etc). To control whether logging exceptions should be thrown, the developer can use Log.DisableOnException property.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Timeout Property

ImapTimeout Property
Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Timeout { get; set; }
Public Property Timeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error, or zero to wait indefinitely. The default value is DefaultTimeout.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | Timeout is negative.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.TrialDaysLeft Property

ImapTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value indicating the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.UidNext Property

ImapUidNext Property
Gets the UID to be assigned to the next message in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long UidNext { get; }
Public ReadOnly Property UidNext As Long
    Get

Property Value

Type: Int64
A 32-bit positive value containing the UIDNEXT of the currently selected folder, or 0 if it's not available or no folder is selected.
Remarks
This value, if available, allows the application to predict the UID value that will be assigned to a new message in the folder.

For instance, if the application is going to upload a message into the folder and wants to know the UID assigned to this message, it can obtain this information passing UidPlusResult object as result parameter of UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method.

However, if the server does not support UIDPLUS extension, this won't work. If the server lacks UIDPLUS support, the application can query UidNext before making upload. If it's non-zero, this will be a value of UID to be assigned to the uploaded message.

Note Note
UidNext value is updated ONLY when a folder gets selected. Thus, if any messages arrived into the folder after it was selected, UidNext won't reflect the next UID value any longer. To request the current UIDNEXT value explicitly, the application should obtain the current FolderStatus of the folder using GetFolderStatus(String) method. This approach also has another advantage: some servers do not report UIDNEXT value on folder selection but they always report it when folder status is requested.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
MailBee.ImapMailFolderStatus


Imap.UidValidity Property

ImapUidValidity Property
Gets the UIDVALIDITY value of the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long UidValidity { get; }
Public ReadOnly Property UidValidity As Long
    Get

Property Value

Type: Int64
A 32-bit positive value containing the UIDVALIDITY of the currently selected folder, or 0 if no folder is selected.
Remarks

If UIDs from an earlier session fail to persist in this session, the UIDVALIDITY value MUST be greater than the one used in the earlier session.

Thus, the client should remember UidValidity value of each folder and compare the saved value and new value on next session. If new value is larger, it means the mail server is not capable of keeping UIDs unchanged between sessions. In this case, the client cannot make any assumptions that UIDs obtained during the previous session correspond to UIDs of the same messages on this session.

Nowadays, IMAP4 servers which fail to persist UIDs between session are very uncommon, and the UIDVALIDITY value is usually the same accross sessions. Nevertheless, the client should still check the UIDVALIDITY value due to the following reason: if, between two sessions, the folder was deleted and the folder with the same name was recreated, and this new folder was filled with some mails, their UIDs may coincide with UIDs of the messages in the original folder (which is now deleted). To avoid confusion, the application should check if UIDVALIDITY had changed.

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Unseen Property

ImapUnseen Property
Gets the ordinal message number of the first message which does not have "\Seen" flag set.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Unseen { get; }
Public ReadOnly Property Unseen As Integer
    Get

Property Value

Type: Int32
The integer value containing one-based message number of the first unseen message in the currently selected folder, or 0 if there are no unseen messages in the folder or no folder is selected.
Remarks

Messages can be flagged with "\Seen" tag when they are downloaded completely, see SetSeenForEntireMessages property on how to enable this.

Note Note
If the folder was selected in read-only mode (e.g. using ExamineFolder(String) method), the message flags will NOT be affected under any circumstances.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.UseXList Property

ImapUseXList Property
Gets or sets whether to use XLIST extension which allows the application to detect special folders like Sent, Drafts, Trash.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UseXList { get; set; }
Public Property UseXList As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will issue XLIST command instead of LIST when the application calls DownloadFolders(Boolean, String, String) method. If false, regular LIST command will be used (no flags denoting special folders will be available). The default value is true if the server supports XLIST.
Remarks

Even if you set this property to true, it may still return false if the server does not support XLIST. Usually, you do not need to set it explicitly as MailBee will set it to true automatically if the server supports XLIST. MailBee reads the IMAP capabilities at the moment of connecting to the server (in some cases, it can re-read the capabilities later but this does not affect XLIST extension). It's safe to assume that once Connect(String, Int32, Socket, EndPoint) method finished, you can examine the value of UseXList property to determine if the server supports well-known folder types.

If you want to disable using XLIST, keep in mind that MailBee automatically sets this property to match the server capabilities when it encounters XLIST support in the server response (usually, during login), so you'll need to set it AFTER you logged in. For instance, just before DownloadFolders(Boolean, String, String) call.

When UseXList is true, and you called DownloadFolders(Boolean, String, String) method specifying subscribedOnly=false, you can then examine Flags property of each Folder object in the retured collection for extra flags, like Drafts or Inbox.

A better alternative to XLIST is SPECIAL-USE extension. If it's supported by the server, extended flags will be returned by the regular LIST command. Gmail supports both XLIST and SPECIAL-USE (although SPECIAL-USE does not appear in its CAPABILITITES list).

Note Note

XLIST extension provides XLIST version of LIST command but no XLSUB command (LSUB lists subscribed-only folders). Thus, it's not possible to get extended flags only for subscribed folders, XLIST extension has no effect when you call DownloadFolders(Boolean) method passing subscribedOnly as true.

However, this can be different with SPECIAL-USE capable servers and Gmail. Gmail provides extended folder flags for all commands: LIST, LSUB, XLIST. Most SPECIAL-USE capable servers support extended flags for both LIST and LSUB (although SPECIAL-USE RFC document requires this only for LIST).

With Gmail, as it in fact supports SPECIAL-USE, you can even set UseXList to false and still get all the flags. Small differences between LIST and XLIST output still exist in Gmail at the moment of writing (e.g. XLIST provides localized INBOX name when Gmail interface is not English while LIST always returns "INBOX").

See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Utf7EncodeFolderNames Property

ImapUtf7EncodeFolderNames Property
Gets or sets whether MailBee should automatically encode folder names with UTF-7 Modified encoding.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Utf7EncodeFolderNames { get; set; }
Public Property Utf7EncodeFolderNames As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, any method of Imap component which can send requests containing folder names will automatically apply UTF-7 Modified transformation to these names; otherwise, MailBee will leave folder names intact. The default value is true.
Remarks
The developer might need to disable automatic UTF-7 Modified transformations when working with folders whose names do not comply with IMAP4 naming convention which requires non-ASCII characters be encoded with UTF-7M. In this case, the developer can use RawName and RawFolderName instead of Name and FolderName when passing folder name to the Imap class method, or ToUtf7String(String) and FromUtf7String(String) methods to manually perform UTF-7M transformations when desired.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
FolderRawName
FolderStatusRawFolderName
ImapUtilsFromUtf7String(String)
ImapUtilsToUtf7String(String)


Imap.Version Property

ImapVersion Property
Gets the version of the MailBee assembly.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap Events

Imap Events

The Imap type exposes the following members.

Events
 | Name | Description
 | Connected | Occurs when the connection with the server is successfully established.
 | DataReceived | Occurs when data is received from the IMAP4 server.
 | DataSent | Occurs when data is sent to the IMAP4 server.
 | Disconnected | Occurs when the connection with the server gets closed.
Public event | Disposed | Occurs after the component was disposed.
 | EnvelopeDataChunkReceived | Occurs on progress of downloading FETCH responses (containing message source data, envelopes, and other message-related information) from the server.
 | EnvelopeDownloaded | Occurs when a FETCH response is received from the IMAP4 server and the method which receives mail messages or envelopes (such as DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)) is in progress.
 | ErrorOccurred | Occurs when the MailBeeException is thrown.
 | HostResolved | Occurs when the IMAP4 server name is successfully resolved into IP address(es).
 | Idling | Ticks every 10 milliseconds while in idle state.
 | LoggedIn | Occurs when the component successfully authenticates the user on the server and logs in the user account.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Imap.Log.MemoryLog is true).
 | LowLevelDataReceived | Occurs when data is received from the connected socket.
 | LowLevelDataSent | Occurs when data is sent to the connected socket.
 | MessageStatus | Occurs when the IMAP4 server informs the client of any changes to mail messages in the currently selected folder.
 | ServerStatus | Occurs when the IMAP4 server reports mailbox or server status information to the client.
 | SocketConnected | Occurs when the IMAP4 server accepts the connection attempt and opens the transmission channel between the remote host (IMAP4 server) and the client (MailBee).
 | SocketCreating | Occurs when MailBee needs a new socket object for establishing a connection with the IMAP4 server.
 | TlsStarted | Occurs when the connection with the server becomes secure.
Top
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.Connected Event

ImapConnected Event
Occurs when the connection with the server is successfully established.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ConnectedEventHandler Connected
Public Event Connected As ConnectedEventHandler

Value

Type: MailBeeConnectedEventHandler
Remarks
This event indicates successful completion of the connection procedure, while SocketConnected event (occurs before Connected) indicates the connection request from MailBee was accepted by the server, and the IMAP4 connection procedure will now begin.
Examples
This sample uses Connected event to report the successful connection status into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // Connected event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Successfully connected to the server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to Connected event.
        imp.Connected += new ConnectedEventHandler(OnConnected);

        imp.Connect("imap.domain.com");
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' Connected event handler.
    Private Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Successfully connected to the server.")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to Connected event.
        AddHandler imp.Connected, AddressOf OnConnected

        imp.Connect("imap.domain.com")
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSocketConnected


Imap.DataReceived Event

ImapDataReceived Event
Occurs when data is received from the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataReceived
Public Event DataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

Unlike LowLevelDataReceived event, occurrence of this event indicates receiving IMAP4-related data only. For instance, if the transmission channel is SSL-encrypted, LowLevelDataReceived event indicates receiving of encrypted data, while DataReceived will be raised later (after decrypting the data). If the transmission channel is not encrypted or otherwise scrambled, DataReceived and LowLevelDataReceived are equivalent.

Unlike EnvelopeDataChunkReceived event, DataReceived will be raised when any IMAP4-related data is received, while EnvelopeDataChunkReceived event is raised only when FETCH response (containing IMAP4 envelopes, body structures, message data, etc) is downloaded.

Note Note
This event is also raised when zero-length data is received from the server. When the server sends zero-length data portion, it means the server closed the connection. This normally happens after Disconnect method was called.
Examples
This sample prints all the data received from the server during IMAP4 session into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("[" + System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the DataReceived event.
        imp.DataReceived += new DataTransferEventHandler(OnDataReceived);

        // Do something which would produce some network traffic.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe@domain.com", "secret");
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' DataReceived event handler.
    Private Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("[" & System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the DataReceived event.
        AddHandler imp.DataReceived, AddressOf OnDataReceived

        ' Do something which would produce some network traffic.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe@domain.com", "secret")
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapEnvelopeDataChunkReceived
ImapLowLevelDataReceived


Imap.DataSent Event

ImapDataSent Event
Occurs when data is sent to the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataSent
Public Event DataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks
Unlike LowLevelDataSent event, occurrence of this event indicates sending IMAP4-related data only. For instance, if the transmission channel is SSL-encrypted, LowLevelDataSent event indicates sending of any portion of encrypted data, while DataSent will be raised later to indicate the entire request (which was previously sent as one or several encrypted data chunks) has been sent. If the transmission channel is not encrypted or otherwise scrambled, DataSent and LowLevelDataSent are equivalent.
Examples
This sample prints all the data sent to the server during IMAP4 session into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // DataSent event handler.
    private static void OnDataSent(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("[" + System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the DataSent event.
        imp.DataSent += new DataTransferEventHandler(OnDataSent);

        // Do something which would produce some network traffic.
        imp.Connect("imap.host.com");
        imp.Login("jdoe", "secret");
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' DataSent event handler.
    Private Sub OnDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("[" & System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the DataSent event.
        AddHandler imp.DataSent, AddressOf OnDataSent

        ' Do something which would produce some network traffic.
        imp.Connect("imap.host.com")
        imp.Login("jdoe", "secret")
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLowLevelDataSent


Imap.Disconnected Event

ImapDisconnected Event
Occurs when the connection with the server gets closed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DisconnectedEventHandler Disconnected
Public Event Disconnected As DisconnectedEventHandler

Value

Type: MailBeeDisconnectedEventHandler
Remarks
This event is raised in all the cases when the connection gets closed, including normal shutdown and failures.
Note Note
If Abort method is called, the connection is immediately closed, but no events (including Disconnected) are raised any longer.
Examples
This sample demonstrates that Disconnected event raises even on failures (when MailBeeException is thrown). The sample set very small timeout value (500 milliseconds), then attempts to connect to the IMAP4 server, log in the account, select Inbox folder, and download the first message. If the server or network connection is slow, the network operation will time out. Otherwise, it will succeed. But in both cases, Disconnected will still be raised.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // Disconnected event handler.
    private static void OnDisconnected(object sender, DisconnectedEventArgs e)
    {
        if (e.IsNormalShutdown)
        {
            // LOGOUT command was sent to IMAP4 server.
            Console.WriteLine("Normally disconnected from the server.");
        }
        else
        {
            // Rough disconnect (due to failure). This will occur if the server
            // or network connection is quite slow and typical delay exceeds
            // 500 milliseconds timeout value which we set for this sample.
            Console.WriteLine("The connection was terminated.");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Set relatively small timeout value. Under slow connection,
        // it may cause the connection to be closed due to timeout.
        imp.Timeout = 500;

        // Subscribe to Disconnected event.
        imp.Disconnected += new DisconnectedEventHandler(OnDisconnected);

        // Connect to the server, login and select inbox.
        imp.Connect("mail.host.com");
        imp.Login("jdoe@host.com", "secret");
        imp.SelectFolder("INBOX");

        // Download the first message in the inbox completely. If the connection is
        // slow, this may cause MailBee to terminate the connection and raise
        // Disconnected event, and then throw MailBeeException (exceptions are
        // enabled by default).
        MailMessage msg = imp.DownloadEntireMessage(1, false);

        // Close the connection normally.
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    ' Disconnected event handler.
    Private Sub OnDisconnected(ByVal sender As Object, ByVal e As DisconnectedEventArgs)
        If (e.IsNormalShutdown) Then
            ' LOGOUT command was sent to IMAP4 server.
            Console.WriteLine("Normally disconnected from the server.")
        Else
            ' Rough disconnect (due to failure). This will occur if the server
            ' or network connection is quite slow and typical delay exceeds
            ' 500 milliseconds timeout value which we set for this sample.
            Console.WriteLine("The connection was terminated.")
        End If
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Set relatively small timeout value. Under slow connection,
        ' it may cause the connection to be closed due to timeout.
        imp.Timeout = 500

        ' Subscribe to Disconnected event.
        AddHandler imp.Disconnected, AddressOf OnDisconnected

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.host.com")
        imp.Login("jdoe@host.com", "secret")
        imp.SelectFolder("INBOX")

        ' Download the first message in the inbox completely. If the connection is
        ' slow, this may cause MailBee to terminate the connection and raise
        ' Disconnected event, and then throw MailBeeException (exceptions are
        ' enabled by default).
        Dim msg As MailMessage = imp.DownloadEntireMessage(1, False)

        ' Close the connection normally.
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDisconnect


Imap.Disposed Event

ImapDisposed Event
Occurs after the component was disposed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event EventHandler Disposed
Public Event Disposed As EventHandler

Value

Type: SystemEventHandler

Implements

IComponentDisposed
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.EnvelopeDataChunkReceived Event

ImapEnvelopeDataChunkReceived Event
Occurs on progress of downloading FETCH responses (containing message source data, envelopes, and other message-related information) from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ImapEnvelopeDataChunkReceivedEventHandler EnvelopeDataChunkReceived
Public Event EnvelopeDataChunkReceived As ImapEnvelopeDataChunkReceivedEventHandler

Value

Type: MailBee.ImapMailImapEnvelopeDataChunkReceivedEventHandler
Remarks

This event is a special case of DataReceived event. While DataReceived event occurs when any data is received, EnvelopeDataChunkReceived event indicates FETCH response containing envelope or message data is being received (see EnvelopeDownloaded event for more information regarding FETCH responses). In other words, EnvelopeDataChunkReceived event is a filtered version of more general DataReceived event.

When both DataReceived and EnvelopeDataChunkReceived events are used, DataReceived is raised first.

Examples
This sample completely downloads the last message in the inbox. Both DataReceived and EnvelopeDataChunkReceived events are handled, and the corresponding messages are printed into console when each of these events is raised. This sample demonstrates that DataReceived is raised more often than EnvelopeDataChunkReceived.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine(e.Data.Length + " bytes received");
    }

    // EnvelopeDataChunkReceived event handler.
    private static void OnEnvelopeDataChunkReceived(object sender,
        ImapEnvelopeDataChunkReceivedEventArgs e)
    {
        Console.WriteLine(e.BytesJustReceived +
            " bytes of the FETCH response series received");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to events.
        imp.DataReceived += new DataTransferEventHandler(OnDataReceived);
        imp.EnvelopeDataChunkReceived +=
            new ImapEnvelopeDataChunkReceivedEventHandler(OnEnvelopeDataChunkReceived);

        // Connect to the server, login and select inbox.
        imp.Connect("imap.company.com");
        imp.Login("jdoe@company.com", "secret");
        imp.SelectFolder("INBOX");

        // Completely download the last message in the inbox.
        MailMessage msg = imp.DownloadEntireMessage(imp.MessageCount, false);

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' DataReceived event handler.
    Private Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine(e.Data.Length & " bytes received")
    End Sub

    ' EnvelopeDataChunkReceived event handler.
    Private Sub OnEnvelopeDataChunkReceived(ByVal sender As Object, ByVal e As ImapEnvelopeDataChunkReceivedEventArgs)
        Console.WriteLine(e.BytesJustReceived & " bytes of the FETCH response series received")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to events.
        AddHandler imp.DataReceived, AddressOf OnDataReceived
        AddHandler imp.EnvelopeDataChunkReceived, AddressOf OnEnvelopeDataChunkReceived

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Completely download the last message in the inbox.
        Dim msg As MailBee.Mime.MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDataReceived
ImapEnvelopeDownloaded


Imap.EnvelopeDownloaded Event

ImapEnvelopeDownloaded Event
Occurs when a FETCH response is received from the IMAP4 server and the method which receives mail messages or envelopes (such as DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)) is in progress.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ImapEnvelopeDownloadedEventHandler EnvelopeDownloaded
Public Event EnvelopeDownloaded As ImapEnvelopeDownloadedEventHandler

Value

Type: MailBee.ImapMailImapEnvelopeDownloadedEventHandler
Remarks

In the IMAP4 protocol, all message related information is returned as a series of FETCH responses (one response per each message). Each FETCH response may consist of various elements, and the most common of them is ENVELOPE. When processing the server response, MailBee parses every FETCH response into an Envelope object.

MailBee methods which download messages or envelopes raise EnvelopeDownloaded event is raised each time a FETCH response was parsed and corresponding Envelope object created. Currently, the list of methods which raise EnvelopeDownloaded and EnvelopeDataChunkReceived events is as follows:

  • DownloadMessageHeaders(String, Boolean)
  • DownloadEntireMessage(Int64, Boolean)
  • DownloadEntireMessages(String, Boolean)
  • DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)
  • BeginDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String, AsyncCallback, Object)

Other methods never raise these events (even if deal with FETCH responses). For instance, GetFolderSize method gets FETCH responses containing the size of each message for all messages in the folder. Although this method does receive FETCH responses, it does not raise EnvelopeDownloaded and EnvelopeDataChunkReceived events.

The developer can use DownloadedEnvelope property to access the downloaded envelope. MessagePreview contains a reference to the MailMessage object within the envelope.

DownloadedEnvelope property is writable. For instance, the developer can set it to a null reference (Nothing in Visual Basic) to prevent this envelope from being added to the resulting collection. This can be used to filter incoming messages or to process messages directly in the event handler and avoid unnecessary memory overhead when the message is no longer needed.

Note Note
Sometimes, the mail server may send unilateral FETCH responses in addition to the requested ones. For instance, if the IMAP4 session lasts for a long period of time, and another client accesses the same folder simultaneously (for instance, downloads a message so it gets "\Seen" flag set), the server will also send unilateral FETCH response containing the updated flags of the amended message. Starting from MailBee.NET Objects v3.0, MailBee detects such unilateral responses and EnvelopeDownloaded event is NOT raised for them (MessageStatus event is raised instead). Also, MailBee takes unilateral responses into account for calculating the folder statistics (total number of messages, number of unseen messages, etc).
Examples
This console sample displays the total size (via GetFolderSize) and the individual sizes (via DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)) of all messages in the folder. The logging into a file is enabled. The sample demonstrates EnvelopeDownloaded is raised by DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method only (despite the fact that both GetFolderSize and DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) calls make the server to produce the same FETCH responses, the log file shows this).
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // EnvelopeDownloaded event handler.
    private static void OnEnvelopeDownloaded(object sender,
        ImapEnvelopeDownloadedEventArgs e)
    {
        Console.WriteLine("Envelope (size and UID) of message #" +
            e.MessageNumber + " downloaded");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Enable logging to demonstrate GetFolderSize() and
        // DownloadEnvelopes(Imap.AllMessages, EnvelopeParts.Rfc822Size, 0)
        // produce the same requests and responses.
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        // Subscribe to the EnvelopeDownloaded event.
        imp.EnvelopeDownloaded +=
            new ImapEnvelopeDownloadedEventHandler(OnEnvelopeDownloaded);

        // Connect to the server, login and select inbox.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Get the total size of all messages in the folder, and display it.
        Console.WriteLine("The total size of all messages in Inbox is: " +
            imp.GetFolderSize() + " bytes");

        // Get the size of each message in the folder...
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, false,
            EnvelopeParts.Rfc822Size, 0);

        // ... and display it.
        foreach (Envelope env in envs)
        {
            Console.WriteLine("Size of message #" + env.MessageNumber + " is " +
                env.Size + " bytes");
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' EnvelopeDownloaded event handler.
    Private Sub OnEnvelopeDownloaded(ByVal sender As Object, ByVal e As ImapEnvelopeDownloadedEventArgs)
        Console.WriteLine("Envelope (size and UID) of message #" & e.MessageNumber & " downloaded")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Enable logging to demonstrate GetFolderSize() and
        ' DownloadEnvelopes(Imap.AllMessages, EnvelopeParts.Rfc822Size, 0)
        ' produce the same requests and responses.
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Enabled = True
        imp.Log.Clear()

        ' Subscribe to the EnvelopeDownloaded event.
        AddHandler imp.EnvelopeDownloaded, AddressOf OnEnvelopeDownloaded

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Get the total size of all messages in the folder, and display it.
        Console.WriteLine("The total size of all messages in Inbox is: " & _
             imp.GetFolderSize() & " bytes")

        ' Get the size of each message in the folder...
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(Imap.AllMessages, _
            False, EnvelopeParts.Rfc822Size, 0)

        ' ... and display it.
        For Each env As Envelope In envs
            Console.WriteLine("Size of message #" & env.MessageNumber & _
                 " is " & env.Size & " bytes")
        Next

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapEnvelopeDataChunkReceived
ImapDownloadMessageHeaders(String, Boolean)
ImapDownloadEntireMessage(Int64, Boolean)
ImapDownloadEntireMessages(String, Boolean)
ImapDownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String)


Imap.ErrorOccurred Event

ImapErrorOccurred Event
Occurs when the MailBeeException is thrown.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ErrorEventHandler ErrorOccurred
Public Event ErrorOccurred As ErrorEventHandler

Value

Type: MailBeeErrorEventHandler
Remarks

When MailBee encounters any error, it throws the MailBeeException. However, MailBee can trap this exception if the error was not critical. For instance, if the IMAP4 server responds with a FETCH response containing envelope data which could not be completely parsed, the MailBeeException will be thrown and then trapped by MailBee itself, but no exception will be thrown to the application code. Such errors are called warnings.

ErrorOccurred event allows the developer to track both warnings and critical errors because it's raised for a particular exception even if MailBee will trap this exception and do not pass it to the application code.

Examples
This sample logs all the warnings and critical errors issued during the IMAP4 session into the console. If the connection succeeds and all envelopes are received without any errors, no output will be produced. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        // Check whether the error is critical or not.
        if (e.IsFinalError)
        {
            // Display corresponding MailBeeException.Message.
            // After OnErrorOccurred handler finishes, MailBee will
            // throw the same exception to the application code.
            Console.WriteLine("CRITICAL ERROR: " + e.Reason.Message);
        }
        else
        {
            // Display corresponding MailBeeException.Message.
            // After OnErrorOccurred handler finishes, MailBee will
            // try another methods to accomplish the current task.
            Console.WriteLine("WARNING: " + e.Reason.Message);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the ErrorOccurred event.
        imp.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("jdoe@company.com", "secret");
        imp.SelectFolder("INBOX");

        // Download envelopes. If any envelopes could not be completely parsed,
        // this will caused ErrorOccurred event be raised.
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, false);

        // Close the connection
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' ErrorOccurred event handler.
    Private Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        ' Check whether the error is critical or not.
        If (e.IsFinalError) Then
            ' Display corresponding MailBeeException.Message.
            ' After OnErrorOccurred handler finishes, MailBee will
            ' throw the same exception to the application code.
            Console.WriteLine("CRITICAL ERROR: " & e.Reason.Message)
        Else
            ' Display corresponding MailBeeException.Message.
            ' After OnErrorOccurred handler finishes, MailBee will
            ' try another methods to accomplish the current task.
            Console.WriteLine("WARNING: " & e.Reason.Message)
        End If
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the ErrorOccurred event.
        AddHandler imp.ErrorOccurred, AddressOf OnErrorOccurred

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("jdoe@company.com", "secret")
        imp.SelectFolder("INBOX")

        ' Download envelopes. If any envelopes could not be completely parsed,
        ' this will caused ErrorOccurred event be raised.
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(Imap.AllMessages, False)

        ' Close the connection
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.HostResolved Event

ImapHostResolved Event
Occurs when the IMAP4 server name is successfully resolved into IP address(es).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event HostResolvedEventHandler HostResolved
Public Event HostResolved As HostResolvedEventHandler

Value

Type: MailBeeHostResolvedEventHandler
Remarks
If the IMAP4 server name (serverName parameter of Connect(String, Int32, Socket, EndPoint) method) was already specified as an IP address, this event is still raised.
Note Note
No checking if performed on whether the resolved IP address points to the live host.
Examples
This sample connects to the IMAP4 server host and prints all the IP addresses of this host into console. Most hosts, however, have only one IP address assigned.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // HostResolved event handler.
    private static void OnHostResolved(object sender, HostResolvedEventArgs e)
    {
        foreach (System.Net.IPAddress ip in e.RemoteHost.AddressList)
        {
            Console.WriteLine(ip.ToString());
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the HostResolved event.
        imp.HostResolved += new HostResolvedEventHandler(OnHostResolved);

        imp.Connect("imap.company.com");
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' HostResolved event handler.
    Private Sub OnHostResolved(ByVal sender As Object, ByVal e As HostResolvedEventArgs)
        For Each ip As System.Net.IPAddress In e.RemoteHost.AddressList
            Console.WriteLine(ip.ToString())
        Next
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the HostResolved event.
        AddHandler imp.HostResolved, AddressOf OnHostResolved

        imp.Connect("imap.company.com")
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSocketConnected
ImapConnected


Imap.Idling Event

ImapIdling Event
Ticks every 10 milliseconds while in idle state.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ImapIdlingEventHandler Idling
Public Event Idling As ImapIdlingEventHandler

Value

Type: MailBee.ImapMailImapIdlingEventHandler
Remarks
This event is useful for performing background activities (such as UI updates) when the execution of the program is blocked within Idle method call.
Examples
The example is available in Idle topic.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapIdle


Imap.LoggedIn Event

ImapLoggedIn Event
Occurs when the component successfully authenticates the user on the server and logs in the user account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LoggedInEventHandler LoggedIn
Public Event LoggedIn As LoggedInEventHandler

Value

Type: MailBeeLoggedInEventHandler
Remarks
Usually, this event is raised on successful completion of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method call. However, it's also raised when the server authenticates the client automatically (by external means, such as if the client connects from the trusted IP address) and sends PREAUTH response.
Examples
This sample connects to the IMAP4 server and logs in the user account. The sample also checks if the IsLoggedIn status was set to true after calling Connect(String, Int32, Socket, EndPoint). This is required to make sure the client has not already been authenticated via PREAUTH.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    private static string accountName = "Preauthenticated user";

    // LoggedIn event handler.
    private static void OnLoggedIn(object sender, LoggedInEventArgs e)
    {
        Console.WriteLine("Logged in as " + accountName);
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the LoggedIn event.
        imp.LoggedIn += new LoggedInEventHandler(OnLoggedIn);

        // Connect to the server. It's possible the server will automatically
        // authenticate us in some cases. In other samples, we do not check
        // if the auto-login occurred but real-world applications should check this.
        imp.Connect("imap4.somedomain.com");

        if (!imp.IsLoggedIn)
        {
            // Authenticate the user via Login()
            accountName = "jdoe";
            imp.Login(accountName, "secret");
        }

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Dim accountName As String = "Preauthenticated user"

    ' LoggedIn event handler.
    Private Sub OnLoggedIn(ByVal sender As Object, ByVal e As LoggedInEventArgs)
        Console.WriteLine("Logged in as " & accountName)
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the LoggedIn event.
        AddHandler imp.LoggedIn, AddressOf OnLoggedIn

        ' Connect to the server. It's possible the server will automatically
        ' authenticate us in some cases. In other samples, we do not check
        ' if the auto-login occurred but real-world applications should check this.
        imp.Connect("imap4.somedomain.com")

        If Not imp.IsLoggedIn Then
            ' Authenticate the user via Login()
            accountName = "jdoe"
            imp.Login(accountName, "secret")
        End If

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)


Imap.LogNewEntry Event

ImapLogNewEntry Event
Occurs when an entry is written into the log file (or into the memory buffer if Imap.Log.MemoryLog is true).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LogNewEntryEventHandler LogNewEntry
Public Event LogNewEntry As LogNewEntryEventHandler

Value

Type: MailBeeLogNewEntryEventHandler
Remarks

This event is raised only if logging is turned on (Enabled is true).

MailBee raises this event BEFORE adding the entry into the the log. Since many properties of NewEntry object are editable, the developer can change the data MailBee will put into the log or even cancel logging the current entry at all. This may be useful the developer wishes to log only those entires which meet certain criteria.

Note Note
Entries added by the developer (through WriteLine(String) method call) do not cause this event to be raised. Thus, it's safe to add user-defined log entries even in the LogNewEntry event handler itself. This does not cause endless recursion which would otherwise occur if WriteLine(String) method called in LogNewEntry event handler raised this event again.
Examples
This sample enables logging the IMAP4 session into a file, and logs only those entries which indicate any data traffic between the client (MailBee) and the server. Other entries are discarded, and user-defined log entry is added instead. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // LogNewEntry event handler
    private static void OnLogNewEntry(object sender, LogNewEntryEventArgs e)
    {
        if ( !(e.NewEntry.MessageType == LogMessageType.Recv ||
            e.NewEntry.MessageType == LogMessageType.Send) )
        {
            // Do not add this entry if it does not indicate any data transfer,
            // and put our own message instead.
            e.NewEntry.AddThisEntry = false;
            ((Imap)sender).Log.WriteLine("UNWANTED MESSAGE REMOVED");

            // Note: we could produce similar results just by writing new values
            // into MessageText and MessageComment properties of the original entry.
            // The code above uses Log.WriteLine method just to show how to add new
            // entries in the event handler itself. You may comment 2 code lines above
            // and uncomment 2 code lines below to use the alternate approach.
            //
            // e.NewEntry.MessageText = "UNWANTED MESSAGE REMOVED";
            // e.NewEntry.MessageComment = string.Empty;
        }
    }

    // The actual code
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Enable logging the POP3 session into a file
        imp.Log.Enabled = true;
        imp.Log.Filename = @"C:\Temp\log.txt";
        imp.Log.Clear();

        // Subscribe to the LogNewEntry event
        imp.LogNewEntry += new LogNewEntryEventHandler(OnLogNewEntry);

        // Do something which would produce some network traffic
        imp.Connect("mail.domain.com");
        imp.Login("jdoe", "secret");
        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' LogNewEntry event handler
    Private Sub OnLogNewEntry(ByVal sender As Object, ByVal e As LogNewEntryEventArgs)
        If Not e.NewEntry.MessageType = LogMessageType.Recv OrElse _
            e.NewEntry.MessageType = LogMessageType.Send Then

            ' Do not add this entry if it does not indicate any data transfer,
            ' and put our own message instead.
            e.NewEntry.AddThisEntry = False
            CType(sender, Imap).Log.WriteLine("UNWANTED MESSAGE REMOVED")

            ' Note: we could produce similar results just by writing new values
            ' into MessageText and MessageComment properties of the original entry.
            ' The code above uses Log.WriteLine method just to show how to add new
            ' entries in the event handler itself. You may comment 2 code lines above
            ' and uncomment 2 code lines below to use the alternate approach.
            '
            ' e.NewEntry.MessageText = "UNWANTED MESSAGE REMOVED"
            ' e.NewEntry.MessageComment = String.Empty
        End If
    End Sub

    ' The actual code
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Enable logging the POP3 session into a file
        imp.Log.Enabled = True
        imp.Log.Filename = "C:\Temp\log.txt"
        imp.Log.Clear()

        ' Subscribe to the LogNewEntry event
        AddHandler imp.LogNewEntry, AddressOf OnLogNewEntry

        ' Do something which would produce some network traffic
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")
        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace


Imap.LowLevelDataReceived Event

ImapLowLevelDataReceived Event
Occurs when data is received from the connected socket.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler LowLevelDataReceived
Public Event LowLevelDataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

If the transmission channel is encrypted, this event will be raised when any encrypted chunk of data is received. Thus, this event can be used to record the data which is actually received from the network.

The typical use of this property is to calculate the network traffic produced during the IMAP4 session. SSL encryption increases the length of the transmitted data blocks, thus it's more accurate to calculate traffic by counting the length of data actually transmitted over the network.

If the transmission channel is not encrypted or otherwise scrambled, this property is equivalent to DataReceived.

Examples
This sample calculates all incoming traffic from the server during the IMAP4 session, and prints the result into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // Total bytes received counter.
    private static int _totalBytes = 0;

    // LowLevelDataReceived event handler.
    private static void OnLowLevelDataReceived(object sender, DataTransferEventArgs e)
    {
        // Increment the counter.
        _totalBytes += e.Data.Length;
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the LowLevelDataReceived event.
        imp.LowLevelDataReceived += new DataTransferEventHandler(OnLowLevelDataReceived);

        // Do something which would produce some network traffic.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("Inbox");
        MailMessageCollection msgs = imp.DownloadMessageHeaders(Imap.AllMessages, false);
        imp.Disconnect();

        // Print the total number of bytes previously received from the server.
        Console.WriteLine(_totalBytes + " bytes received in all");
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    ' Total bytes received counter.
    Dim _totalBytes As Integer = 0

    ' LowLevelDataReceived event handler.
    Private Sub OnLowLevelDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Increment the counter.
        _totalBytes += e.Data.Length
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the LowLevelDataReceived event.
        AddHandler imp.LowLevelDataReceived, AddressOf OnLowLevelDataReceived

        ' Do something which would produce some network traffic.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("Inbox")
        Dim msgs As MailMessageCollection = imp.DownloadMessageHeaders(Imap.AllMessages, False)
        imp.Disconnect()

        ' Print the total number of bytes previously received from the server.
        Console.WriteLine(_totalBytes & " bytes received in all")
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDataReceived


Imap.LowLevelDataSent Event

ImapLowLevelDataSent Event
Occurs when data is sent to the connected socket.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler LowLevelDataSent
Public Event LowLevelDataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

If the transmission channel is encrypted, this event will be raised each time an encrypted chunk of data is successfully sent. Thus, this event can be used to record the data which is actually sent to the network.

The typical use of this property is to calculate the network traffic produced during the IMAP4 session. SSL encryption increases the length of the transmitted data blocks, thus it's more accurate to calculate traffic by counting the length of data actually transmitted over the network.

If the transmission channel is not encrypted or otherwise scrambled, this property is equivalent to DataSent.

Examples
This sample calculates all outgoing traffic to the server during the IMAP4 session, and prints the result into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    // Total bytes sent counter.
    private static int _totalBytes = 0;

    // LowLevelDataSent event handler.
    private static void OnLowLevelDataSent(object sender, DataTransferEventArgs e)
    {
        // Increment the counter.
        _totalBytes += e.Data.Length;
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the LowLevelDataSent event.
        imp.LowLevelDataSent += new DataTransferEventHandler(OnLowLevelDataSent);

        // Do something which would produce some network traffic.
        imp.Connect("mail.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("Inbox");
        MailMessageCollection msgs =
            imp.DownloadMessageHeaders(Imap.AllMessages, false);
        imp.Disconnect();

        // Print the total number of bytes previously sent to the server.
        Console.WriteLine(_totalBytes + " bytes sent in all");
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Module Sample
    ' Total bytes sent counter.
    Dim _totalBytes As Integer = 0

    ' LowLevelDataSent event handler.
    Private Sub OnLowLevelDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Increment the counter.
        _totalBytes += e.Data.Length
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the LowLevelDataSent event.
        AddHandler imp.LowLevelDataSent, AddressOf OnLowLevelDataSent

        ' Do something which would produce some network traffic.
        imp.Connect("mail.domain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("Inbox")
        Dim msgs As MailMessageCollection = imp.DownloadMessageHeaders(Imap.AllMessages, False)
        imp.Disconnect()

        ' Print the total number of bytes previously sent to the server.
        Console.WriteLine(_totalBytes & " bytes sent in all")
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapDataSent


Imap.MessageStatus Event

ImapMessageStatus Event
Occurs when the IMAP4 server informs the client of any changes to mail messages in the currently selected folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ImapMessageStatusEventHandler MessageStatus
Public Event MessageStatus As ImapMessageStatusEventHandler

Value

Type: MailBee.ImapMailImapMessageStatusEventHandler
Remarks
MailBee raises this event when any of the following is received from the server:
  • Unilateral FETCH response containing flag updates to a message (for instance, certain message was read or marked answered by another mail agent)
  • EXISTS response informing the client of the new number of all messages in the folder
  • RECENT response informing the client of the new number of recent messages in the folder
  • EXPUNGE response containing message number of the mail message which had been permanently deleted from the mailbox
This event is often used in conjunction with ServerStatus event during idling (see Idle) for keeping the application informed of any changes in the monitored folder.
Examples
The example is available in Idle topic.
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapServerStatus
ImapIdle


Imap.ServerStatus Event

ImapServerStatus Event
Occurs when the IMAP4 server reports mailbox or server status information to the client.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ImapServerStatusEventHandler ServerStatus
Public Event ServerStatus As ImapServerStatusEventHandler

Value

Type: MailBee.ImapMailImapServerStatusEventHandler
Remarks

The server sends the status response to the client when a command is completed or there is a state change of the server or the currently folder, etc.

MailBee raises this event when it receives any of the following responses from the server: OK, NO, BAD, PREAUTH, BYE, or FLAGS.

The real-world application should subscribe to this event and at least check IsAlert property value. If it's true, it means the server sent [ALERT] response along with the human-readable message, and the application must present the supplied HumanReadable text to the user. For instance, the server may tell clients it's about to shutdown in a short while.

Examples
This sample connects to the server, logs in the account, selects inbox, and receives envelopes of all messages. If the server sends [ALERT] response during this time, it's displayed to the user.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // ServerStatus event handler.
    private static void OnServerStatus(object sender,
        ImapServerStatusEventArgs e)
    {
        if (e.IsAlert)
        {
            Console.WriteLine("The server warns: " + e.HumanReadable);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to ServerStatus event.
        imp.ServerStatus +=
            new ImapServerStatusEventHandler(OnServerStatus);

        // Connect to the server, login and select inbox.
        imp.Connect("mail.company.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("INBOX");

        // Download envelopes of all message in the inbox.
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, false);

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' ServerStatus event handler.
    Private Sub OnServerStatus(ByVal sender As Object, ByVal e As ImapServerStatusEventArgs)
        If e.IsAlert Then
            Console.WriteLine("The server warns: " & e.HumanReadable)
        End If
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to ServerStatus event.
        AddHandler imp.ServerStatus, AddressOf OnServerStatus

        ' Connect to the server, login and select inbox.
        imp.Connect("mail.company.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("INBOX")

        ' Download envelopes of all message in the inbox.
        Dim envs As EnvelopeCollection = imp.DownloadEnvelopes(Imap.AllMessages, False)

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapMessageStatus


Imap.SocketConnected Event

ImapSocketConnected Event
Occurs when the IMAP4 server accepts the connection attempt and opens the transmission channel between the remote host (IMAP4 server) and the client (MailBee).

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SocketConnectedEventHandler SocketConnected
Public Event SocketConnected As SocketConnectedEventHandler

Value

Type: MailBeeSocketConnectedEventHandler
Remarks
This event is raised immediately after Socket successfully connected to the IMAP4 server host. After the socket itself has been connected and this event raised, the client needs to receive some data from the server in order to complete the procedure of establishing connection with the IMAP4 server. If the connection must be SSL-encrypted, a few additional round-trips to the server required in order to completely establish the connection. Then, once the connection is fully initialized and ready for sending IMAP4 commands to the server, Connected event is raised.
Examples
This sample demonstrates the order in which events are raised during Connect(String, Int32, Socket, EndPoint) method call. The events used in this sample occur in the following order:
  1. HostResolved
  2. SocketCreating
  3. SocketConnected
  4. LowLevelDataReceived
  5. DataReceived
  6. Connected

Once Connect(String, Int32, Socket, EndPoint) method finishes, all event handlers are removed in the code, thus Disconnect method does not generate any events (but it would do if we didn't remove LowLevelDataReceived and DataReceived handlers).

DataSent and LowLevelDataSent events are not used in this sample because Connect(String, Int32, Socket, EndPoint) method does not send any data to the server. However, it would be different if SSL-encrypted connection was used.

C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // HostResolved event handler.
    private static void OnHostResolved(object sender, HostResolvedEventArgs e)
    {
        Console.WriteLine("The host name of the server was resolved into IP address.");
    }

    // SocketConnected event handler.
    private static void OnSocketConnected(object sender, SocketConnectedEventArgs e)
    {
        Console.WriteLine("The server accepted the connection.");
    }

    // LowLevelDataReceived event handler.
    private static void OnLowLevelDataReceived(object sender, DataTransferEventArgs e)
    {
        // Since SSL connection is not used, OnDataReceived and OnLowLevelDataReceived
        // routines will produce the same output. This sample handles both events just
        // to demonstrate that LowLevelDataReceived event is raised before the
        // corresponding DataReceived event.
        // But in SSL case, DataReceived and LowLevelDataReceived event data would be
        // completely different, and some LowLevelDataReceived events (such as ones
        // occurred during the SSL handshake) would not be followed by DataReceived
        // events at all, because the data sent or received during the SSL handshake
        // does not relate to POP3 protocol and cannot be decoded into textual form.
        Console.WriteLine("Low level data received: [" +
            System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("Data received: [" +
            System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // Connected event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Successfully connected to the server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to the events.
        imp.HostResolved += new HostResolvedEventHandler(OnHostResolved);
        imp.SocketConnected += new SocketConnectedEventHandler(OnSocketConnected);
        imp.LowLevelDataReceived += new DataTransferEventHandler(OnLowLevelDataReceived);
        imp.DataReceived += new DataTransferEventHandler(OnDataReceived);
        imp.Connected += new ConnectedEventHandler(OnConnected);

        // Connect to the server and make the events get raised.
        imp.Connect("mail.company.com");

        // Unsubscribe from the events.
        imp.HostResolved -= new HostResolvedEventHandler(OnHostResolved);
        imp.SocketConnected -= new SocketConnectedEventHandler(OnSocketConnected);
        imp.LowLevelDataReceived -= new DataTransferEventHandler(OnLowLevelDataReceived);
        imp.DataReceived -= new DataTransferEventHandler(OnDataReceived);
        imp.Connected -= new ConnectedEventHandler(OnConnected);

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' HostResolved event handler.
    Private Sub OnHostResolved(ByVal sender As Object, ByVal e As HostResolvedEventArgs)
        Console.WriteLine("The host name of the server was resolved into IP address.")
    End Sub

    ' SocketConnected event handler.
    Private Sub OnSocketConnected(ByVal sender As Object, ByVal e As SocketConnectedEventArgs)
        Console.WriteLine("The server accepted the connection.")
    End Sub

    ' LowLevelDataReceived event handler.
    Private Sub OnLowLevelDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Since SSL connection is not used, OnDataReceived and OnLowLevelDataReceived
        ' routines will produce the same output. This sample handles both events just
        ' to demonstrate that LowLevelDataReceived event is raised before the
        ' corresponding DataReceived event.
        ' But in SSL case, DataReceived and LowLevelDataReceived event data would be
        ' completely different, and some LowLevelDataReceived events (such as ones
        ' occurred during the SSL handshake) would not be followed by DataReceived
        ' events at all, because the data sent or received during the SSL handshake
        ' does not relate to POP3 protocol and cannot be decoded into textual form.
        Console.WriteLine("Low level data received: [" & System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' DataReceived event handler.
    Private Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("Data received: [" & System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' Connected event handler.
    Private Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Successfully connected to the server.")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to the events.
        AddHandler imp.HostResolved, AddressOf OnHostResolved
        AddHandler imp.SocketConnected, AddressOf OnSocketConnected
        AddHandler imp.LowLevelDataReceived, AddressOf OnLowLevelDataReceived
        AddHandler imp.DataReceived, AddressOf OnDataReceived
        AddHandler imp.Connected, AddressOf OnConnected

        ' Connect to the server and make the events get raised.
        imp.Connect("mail.company.com")

        ' Unsubscribe from the events.
        RemoveHandler imp.HostResolved, AddressOf OnHostResolved
        RemoveHandler imp.SocketConnected, AddressOf OnSocketConnected
        RemoveHandler imp.LowLevelDataReceived, AddressOf OnLowLevelDataReceived
        RemoveHandler imp.DataReceived, AddressOf OnDataReceived
        RemoveHandler imp.Connected, AddressOf OnConnected

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapConnected


Imap.SocketCreating Event

ImapSocketCreating Event
Occurs when MailBee needs a new socket object for establishing a connection with the IMAP4 server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SocketCreatingEventHandler SocketCreating
Public Event SocketCreating As SocketCreatingEventHandler

Value

Type: MailBeeSocketCreatingEventHandler
Remarks
This event is raised just before MailBee will start making the connection (i.e. before SocketConnected event). This lets you specify your own socket object in case if you need some special socket settings. For instance, configure SSL settings for new sockets in UWP apps. If you need this, set NewSocket property to the socket object needed in your event handler.
Note Note
It's possible that this event will fire multiple times in case if the host has multple endpoints assigned. For instance, if the first endpoint was IPv6, the connection could not be made but second endpoint (IPv4) would succeed. On each call of this event handler, your code must supply a new, fresh socket object (otherwise MailBee will create its own). By default, however, MailBee tries IPv4 addresses first (see PreferIPv4Hosts) so this situation is unlikely to happen.
Examples
This code snippet shows how to ignore some SSL certificate errors when making SSL/TLS connections in a UWP app (useful if you connect to local hosts with self-signed certificates, etc).
C#
VB
Copy
// Event handler
static void Imp_SocketCreating(object sender, SocketCreatingEventArgs e)
{
    e.NewSocket = new StreamSocket();
    e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
    e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
}

// Your async method
...
Imap imp = new Imap();
imp.SocketCreating += new SocketCreatingEventHandler(Imp_SocketCreating);
await imp.ConnectAsync("imap.gmail.com", 993);
...
' Event handler
Sub Imp_SocketCreating(sender As Object, e As SocketCreatingEventArgs)
    e.NewSocket = New StreamSocket()
    e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName)
    e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted)
    e.NewSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired)
End Sub

' Your async method
...
Dim imp As Imap = New Imap()
AddHandler imp.SocketCreating, AddressOf Imp_SocketCreating
Await imp.ConnectAsync("imap.gmail.com", 993)
...
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapConnected


Imap.TlsStarted Event

ImapTlsStarted Event
Occurs when the connection with the server becomes secure.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event TlsStartedEventHandler TlsStarted
Public Event TlsStarted As TlsStartedEventHandler

Value

Type: MailBeeTlsStartedEventHandler
Remarks
This event is raised when TLS/SSL negotiation completes and TLS session successfully starts. Usually, this happens as a result of successful completion of StartTls method or if automatic TLS/SSL negotiation was requested via setting SslMode property to non-Manual value.
Examples
This console sample demonstrates that TlsStarted event is raised during executing Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method when SslMode property is set to UseStartTls value.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Security;

class Sample
{
    // TlsStarted event handler.
    private static void OnTlsStarted(object sender, TlsStartedEventArgs e)
    {
        // This will happen during Login method execution.
        Console.WriteLine("TLS/SSL session started.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Subscribe to TlsStarted event.
        imp.TlsStarted += new TlsStartedEventHandler(OnTlsStarted);

        // Notify MailBee it should start TLS/SSL session when appropriate.
        // The connection is made to the regular port so that STARTTLS command
        // will be used to start TLS/SSL session.
        imp.SslMode = SslStartupMode.UseStartTls;

        imp.Connect("imap.company.com");

        Console.WriteLine("Connected to the server. Will login now...");

        // TLS/SSL negotiation will take place here. Thus, user credentials
        // will be sent to the mail server already under secure TLS/SSL layer.
        imp.Login("jdoe", "secret");

        Console.WriteLine("Logged in successfully.");

        imp.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Security

Module Sample
    ' TlsStarted event handler.
    Private Sub OnTlsStarted(ByVal sender As Object, ByVal e As TlsStartedEventArgs)
        ' This will happen during Login method execution.
        Console.WriteLine("TLS/SSL session started.")
    End Sub

    ' The actual code.
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Subscribe to TlsStarted event.
        AddHandler imp.TlsStarted, AddressOf OnTlsStarted

        ' Notify MailBee it should start TLS/SSL session when appropriate.
        ' The connection is made to the regular port so that STARTTLS command
        ' will be used to start TLS/SSL session.
        imp.SslMode = SslStartupMode.UseStartTls

        imp.Connect("imap.company.com")

        Console.WriteLine("Connected to the server. Will login now...")

        ' TLS/SSL negotiation will take place here. Thus, user credentials
        ' will be sent to the mail server already under secure TLS/SSL layer.
        imp.Login("jdoe", "secret")

        Console.WriteLine("Logged in successfully.")

        imp.Disconnect()
    End Sub
End Module
See Also

Reference

Imap Class
MailBee.ImapMail Namespace
ImapSslMode
ImapStartTls


ImapBodyStructure Class

ImapBodyStructure Class
Represents a structure of a MIME part of a mail message.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailImapBodyStructure

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapBodyStructure
Public Class ImapBodyStructure

The ImapBodyStructure type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAllParts | Returns this MIME part and all its subparts as a flat list.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | BodyParams | Gets the name-value list of body parameters.
Public property | Charset | Gets the charset of the MIME part.
Public property | ContentID | Gets the Content-ID value of the MIME part.
Public property | ContentType | Gets the content-type of the MIME part.
Public property | Description | Gets the description of the MIME part.
Public property | Disposition | Gets the disposition (attachment or inline) of the MIME part.
Public property | DispositionParams | Gets the name-value list of disposition parameters.
Public property | EncapsulatedBodyStructure | Gets the body structure of the attached mail message.
Public property | EncapsulatedEnvelope | Gets the envelope information of the attached mail message.
Public property | Filename | Gets the filename of the MIME part.
Public property | IsMultipart | Indicates if the MIME part is multipart.
Public property | Language | Get the language of the MIME part body.
Public property | Location | Gets the body content URI of the MIME part.
Public property | MailEncodingName | Get the name of content transfer encoding the MIME part body is encoded to.
Public property | PartID | Gets the IMAP4 identifier of this MIME part.
Public property | SafeFilename | Gets the filename of the MIME part, safe for saving to the filesystem under that name.
Public property | Size | Gets the length of encoded body of the MIME part.
Public property | SubParts | Gets the collection of nested parts of the multipart MIME part.
Public property | TextLineCount | Gets the count of text lines of the MIME part of text type.
Top
Remarks

The IMAP4 protocol allows the client to query information about all MIME parts of a mail message without downloading the entire message. The server returns this information as a tree of body structures, where each body structure describes the corresponding MIME part and contains a list of nested body structures if the corresponding MIME part is multipart.

The common use of body structures is to list attachments of a mail message (see the sample code in Envelope topic). Another case is processing envelopes of international messages, because body structures contain charset settings of mail messages. When a body structure of a certain message is available, MailBee is able to decode the message envelope fields containing international characters more correctly.

When an entire message is downloaded, there is no need to download its body structure since all the required information is already available in the message data.

To access body structure information, the developer should request receiving body structures from the server when calling DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method by setting BodyStructure flag in parts parameter value. A reference to the ImapBodyStructure object representing the root MIME part of the mail message can then be obtained via BodyStructure property value.

By default, MailBee represents the body structure tree as a branching linked list. This reflects nested nature of MIME parts. However, it's often more convenient to get this tree as a simple collection. MailBee provides GetAllParts method for this.

See Also

Reference

MailBee.ImapMail Namespace


ImapBodyStructure Methods

ImapBodyStructure Methods

The ImapBodyStructure type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAllParts | Returns this MIME part and all its subparts as a flat list.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.GetAllParts Method

ImapBodyStructureGetAllParts Method
Returns this MIME part and all its subparts as a flat list.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapBodyStructureCollection GetAllParts()
Public Function GetAllParts As ImapBodyStructureCollection

Return Value

Type: ImapBodyStructureCollection
A reference to the ImapBodyStructureCollection object containing body structures of the MIME part and all its sub-parts (including sub-sub-parts, etc).
Remarks
The developer can use this method to get flat representation of the MIME parts tree. This is useful when it's required to quickly iterate through all of the MIME parts (for instance, to count all the attachments of the mail message).
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure Properties

ImapBodyStructure Properties

The ImapBodyStructure type exposes the following members.

Properties
 | Name | Description
Public property | BodyParams | Gets the name-value list of body parameters.
Public property | Charset | Gets the charset of the MIME part.
Public property | ContentID | Gets the Content-ID value of the MIME part.
Public property | ContentType | Gets the content-type of the MIME part.
Public property | Description | Gets the description of the MIME part.
Public property | Disposition | Gets the disposition (attachment or inline) of the MIME part.
Public property | DispositionParams | Gets the name-value list of disposition parameters.
Public property | EncapsulatedBodyStructure | Gets the body structure of the attached mail message.
Public property | EncapsulatedEnvelope | Gets the envelope information of the attached mail message.
Public property | Filename | Gets the filename of the MIME part.
Public property | IsMultipart | Indicates if the MIME part is multipart.
Public property | Language | Get the language of the MIME part body.
Public property | Location | Gets the body content URI of the MIME part.
Public property | MailEncodingName | Get the name of content transfer encoding the MIME part body is encoded to.
Public property | PartID | Gets the IMAP4 identifier of this MIME part.
Public property | SafeFilename | Gets the filename of the MIME part, safe for saving to the filesystem under that name.
Public property | Size | Gets the length of encoded body of the MIME part.
Public property | SubParts | Gets the collection of nested parts of the multipart MIME part.
Public property | TextLineCount | Gets the count of text lines of the MIME part of text type.
Top
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.BodyParams Property

ImapBodyStructureBodyParams Property
Gets the name-value list of body parameters.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary BodyParams { get; }
Public ReadOnly Property BodyParams As StringDictionary
    Get

Property Value

Type: StringDictionary
A reference to the StringDictionary object containing name-value pairs representing all parameters of "Content-Type" header, or a null reference (Nothing in Visual Basic) if the body parameter's information is available.
Remarks
All parameter names are lowercased, while parameter values remain unchanged. This is the specifics of StringDictionary object.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.Charset Property

ImapBodyStructureCharset Property
Gets the charset of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Charset { get; }
Public ReadOnly Property Charset As String
    Get

Property Value

Type: String
The string containing the charset of the MIME part contents, or a null reference (Nothing in Visual Basic) if no charset information is available.
Remarks

Examples: "us-ascii", "ISO-8859-1", "gb2312", "shift-jis", "Windows-1252".

MailBee obtains the charset from the value of "charset" parameter of BodyParams.

See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.ContentID Property

ImapBodyStructureContentID Property
Gets the Content-ID value of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentID { get; }
Public ReadOnly Property ContentID As String
    Get

Property Value

Type: String
The string containing "Content-ID" header value, or a null reference (Nothing in Visual Basic) if the part does not have Content-ID.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.ContentType Property

ImapBodyStructureContentType Property
Gets the content-type of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentType { get; }
Public ReadOnly Property ContentType As String
    Get

Property Value

Type: String
The string value in the "media type/media sub type" format.
Remarks

Examples: "text/plain", "TEXT/HTML", "multipart/mixed", "Multipart/Related", "message/rfc822", "application/octet-stream".

Note Note
If the entire "Content-Type" message header contains some additional parameters (such as "charset", "name", etc), the developer can examine BodyParams list to obtain the parameter names and values.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.Description Property

ImapBodyStructureDescription Property
Gets the description of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Description { get; }
Public ReadOnly Property Description As String
    Get

Property Value

Type: String
The string containing "Content-Description" header value, or a null reference (Nothing in Visual Basic) if the part does not have "Content-Description" header set.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.Disposition Property

ImapBodyStructureDisposition Property
Gets the disposition (attachment or inline) of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Disposition { get; }
Public ReadOnly Property Disposition As String
    Get

Property Value

Type: String
The string containing "Content-Disposition" header value, or a null reference (Nothing in Visual Basic) if the part does not have "Content-Disposition" header set.
Remarks

Examples: "attachment", "INLINE".

If this header is missing, the application should assume "inline" by default.

Note Note
If the entire "Content-Disposition" message header contains some additional parameters (such as "filename"), the developer can examine DispositionParams list to obtain the parameter names and values.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.DispositionParams Property

ImapBodyStructureDispositionParams Property
Gets the name-value list of disposition parameters.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary DispositionParams { get; }
Public ReadOnly Property DispositionParams As StringDictionary
    Get

Property Value

Type: StringDictionary
A reference to the StringDictionary object containing name-value pairs representing all parameters of "Content-Disposition" header.
Remarks
All parameter names are lowercased, while parameter values remain unchanged. This is the specifics of StringDictionary object.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.EncapsulatedBodyStructure Property

ImapBodyStructureEncapsulatedBodyStructure Property
Gets the body structure of the attached mail message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapBodyStructure EncapsulatedBodyStructure { get; }
Public ReadOnly Property EncapsulatedBodyStructure As ImapBodyStructure
    Get

Property Value

Type: ImapBodyStructure
A reference to the ImapBodyStructure object containing the body structure of the MIME part which is an attached mail message, or a null reference (Nothing in Visual Basic) if the part is not a mail message.
Remarks
The developer can use this property to access the body structure information of forwarded or attached mail messages.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.EncapsulatedEnvelope Property

ImapBodyStructureEncapsulatedEnvelope Property
Gets the envelope information of the attached mail message.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Envelope EncapsulatedEnvelope { get; }
Public ReadOnly Property EncapsulatedEnvelope As Envelope
    Get

Property Value

Type: Envelope
A reference to the Envelope object containing the envelope information of the MIME part which is an attached mail message, or a null reference (Nothing in Visual Basic) if the part is not a mail message.
Remarks
The developer can use this property to access the envelope information of forwarded or attached mail messages.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.Filename Property

ImapBodyStructureFilename Property
Gets the filename of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; }
Public ReadOnly Property Filename As String
    Get

Property Value

Type: String
The string containing the filename of the MIME part, or a null reference (Nothing in Visual Basic) if no filename is available.
Remarks

MailBee obtains the filename from the value of "filename" parameter of DispositionParams.

As this can be empty or missing, you may use SafeFilename which is never empty and never contains symbols not allowed for filenames on the filesystem.

See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace
ImapBodyStructureSafeFilename


ImapBodyStructure.IsMultipart Property

ImapBodyStructureIsMultipart Property
Indicates if the MIME part is multipart.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsMultipart { get; }
Public ReadOnly Property IsMultipart As Boolean
    Get

Property Value

Type: Boolean
true if the MIME part is multipart; otherwise, false.
Remarks
If the part is multipart, the developer can use SubParts property to access nested parts of this part.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.Language Property

ImapBodyStructureLanguage Property
Get the language of the MIME part body.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Language { get; }
Public ReadOnly Property Language As String
    Get

Property Value

Type: String
The string containing the language of the MIME part body, or a null reference (Nothing in Visual Basic) if this information is available.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.Location Property

ImapBodyStructureLocation Property
Gets the body content URI of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Location { get; }
Public ReadOnly Property Location As String
    Get

Property Value

Type: String
The string containing "Content-Location" header value, or a null reference (Nothing in Visual Basic) if the part does not have "Content-Location" header set.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.MailEncodingName Property

ImapBodyStructureMailEncodingName Property
Get the name of content transfer encoding the MIME part body is encoded to.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MailEncodingName { get; }
Public ReadOnly Property MailEncodingName As String
    Get

Property Value

Type: String
The string containing "Content-Transfer-Encoding" header value, or a null reference (Nothing in Visual Basic) if the part does not have "Content-Transfer-Encoding" header set.
Remarks

Examples: "base64", "Quoted-Printable", "X-UUE", "7bit", "binary".

If this value is missing, the MIME part body is not encoded. This is the same as "7bit", "8bit", or "binary".

See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.PartID Property

ImapBodyStructurePartID Property
Gets the IMAP4 identifier of this MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string PartID { get; }
Public ReadOnly Property PartID As String
    Get

Property Value

Type: String
The string containing the identifier which can be used to request the body or header sections of this MIME part from the server.
Remarks

The developer can use this property to obtain the identifier of the part which can then be passed as one of elements of extraItems parameter of DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method. Once DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) method succeeds, the developer can then obtain the requested data using GetEnvelopeItem(String, Boolean) method.

The exact syntax of the value to be passed as element of extraItems array depends on which portion of the MIME part the developer needs to obtain. Also, the name of the requested item to be passed to GetEnvelopeItem(String, Boolean) method may differ from the name passed as extraItems element. See GetEnvelopeItem(String, Boolean) method topic for more information.

See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.SafeFilename Property

ImapBodyStructureSafeFilename Property
Gets the filename of the MIME part, safe for saving to the filesystem under that name.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SafeFilename { get; }
Public ReadOnly Property SafeFilename As String
    Get

Property Value

Type: String
The string containing the filename of the MIME part, without symbols not valid on the filesystem, or an auto-generated name if the MIME part has no filename.
Remarks
If Filename is set, it's used. Otherwise, name parameter of Content-Type is tried. The resulting name is made safe for the filesystem by replacing invalid characters with "_". If both Filename and name are empty, the filename is auto-generated based on the ContentType (e.g. for image/gif MailBee generates a filename like some-unique-string.gif).
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace
ImapBodyStructureFilename


ImapBodyStructure.Size Property

ImapBodyStructureSize Property
Gets the length of encoded body of the MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Size { get; }
Public ReadOnly Property Size As Integer
    Get

Property Value

Type: Int32
The integer value containing the length of encoded body of the MIME part, or 0 if the MIME part is multipart and thus does not have its own body, or -1 if the body size parameter value in the IMAP4 response could not be parsed.
Remarks
This is the size of the MIME part body in its encoded state. For instance, if the body is base64 encoded, the encoded data length is approximately 33% larger than the actual data length.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.SubParts Property

ImapBodyStructureSubParts Property
Gets the collection of nested parts of the multipart MIME part.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapBodyStructureCollection SubParts { get; }
Public ReadOnly Property SubParts As ImapBodyStructureCollection
    Get

Property Value

Type: ImapBodyStructureCollection
A reference to the ImapBodyStructureCollection object containing the immediate sub-parts of the given multipart MIME part, or a null reference (Nothing in Visual Basic) if the part is not multipart.
Remarks
Certain sub-parts can also be multipart. The maximum number of nesting levels is not limited (although it's usually is not larger than 5).
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructure.TextLineCount Property

ImapBodyStructureTextLineCount Property
Gets the count of text lines of the MIME part of text type.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TextLineCount { get; }
Public ReadOnly Property TextLineCount As Integer
    Get

Property Value

Type: Int32
The integer value containing the number of text lines of the MIME part of text type, or 0 if the MIME part is not of text type, or -1 if this parameter value in the IMAP4 response could not be parsed.
See Also

Reference

ImapBodyStructure Class
MailBee.ImapMail Namespace


ImapBodyStructureCollection Class

ImapBodyStructureCollection Class
Provides properties and methods for examining the collection of the ImapBodyStructure objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailImapBodyStructureCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapBodyStructureCollection : CollectionBase
Public Class ImapBodyStructureCollection
    Inherits CollectionBase

The ImapBodyStructureCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the ImapBodyStructure object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailImapBodyStructure


ImapBodyStructureCollection Methods

ImapBodyStructureCollection Methods

The ImapBodyStructureCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapBodyStructureCollection Class
MailBee.ImapMail Namespace


ImapBodyStructureCollection Properties

ImapBodyStructureCollection Properties

The ImapBodyStructureCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the ImapBodyStructure object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

ImapBodyStructureCollection Class
MailBee.ImapMail Namespace


ImapBodyStructureCollection.Item Property

ImapBodyStructureCollectionItem Property
Gets the ImapBodyStructure object at the specified zero-based index in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapBodyStructure this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As ImapBodyStructure
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the ImapBodyStructure object in the collection.

Property Value

Type: ImapBodyStructure
A ImapBodyStructure object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

ImapBodyStructureCollection Class
MailBee.ImapMail Namespace
MailBee.ImapMailImapBodyStructure


ImapNamespace Class

ImapNamespace Class
Represents the description of a single IMAP namespace.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailImapNamespace

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapNamespace
Public Class ImapNamespace

The ImapNamespace type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AllValues | Gets the string list of all items returned by the mail server for the given namespace.
Public property | Delimiter | Gets the character which is used as a hierarchy delimiter of separate levels of folder names.
Public property | IsValid | Returns true if the response with the namespace data received from the mail server was correctly parsed.
Public property | Prefix | The prefix which needs to be used in the beginning of a folder name to select it within the given namespace.
Top
Remarks
Provides the properties to get the namespace name (prefix to be inserted before the folder name) and other information about a single namespace. To get all the namespaces defined for the current e-mail account, use GetNamespaces method.
See Also

Reference

MailBee.ImapMail Namespace
ImapGetNamespaces


ImapNamespace Methods

ImapNamespace Methods

The ImapNamespace type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapNamespace Class
MailBee.ImapMail Namespace


ImapNamespace Properties

ImapNamespace Properties

The ImapNamespace type exposes the following members.

Properties
 | Name | Description
Public property | AllValues | Gets the string list of all items returned by the mail server for the given namespace.
Public property | Delimiter | Gets the character which is used as a hierarchy delimiter of separate levels of folder names.
Public property | IsValid | Returns true if the response with the namespace data received from the mail server was correctly parsed.
Public property | Prefix | The prefix which needs to be used in the beginning of a folder name to select it within the given namespace.
Top
See Also

Reference

ImapNamespace Class
MailBee.ImapMail Namespace


ImapNamespace.AllValues Property

ImapNamespaceAllValues Property
Gets the string list of all items returned by the mail server for the given namespace.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ArrayList AllValues { get; }
Public ReadOnly Property AllValues As ArrayList
    Get

Property Value

Type: ArrayList
The array of strings where each string represents a single value of the list of items returned by the mail server to describe this namespace.
Remarks
The mail server can return arbitrary information about the namespace in addition to its prefix. MailBee itself recognizes only Prefix and Delimiter. You can use this property to examine other namespace properties specific for your mail server.
See Also

Reference

ImapNamespace Class
MailBee.ImapMail Namespace


ImapNamespace.Delimiter Property

ImapNamespaceDelimiter Property
Gets the character which is used as a hierarchy delimiter of separate levels of folder names.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Delimiter { get; }
Public ReadOnly Property Delimiter As String
    Get

Property Value

Type: String
The string containing a single character used to separate levels of hierarchy of folder names, or a null reference (Nothing in Visual Basic) if folder names are flat and nested folders are not supported.
Remarks
The typical values returned by this property are: "/", ".", "\".
See Also

Reference

ImapNamespace Class
MailBee.ImapMail Namespace


ImapNamespace.IsValid Property

ImapNamespaceIsValid Property
Returns true if the response with the namespace data received from the mail server was correctly parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if the response with the namespace data received from the mail server was correctly parsed. Otherwise, false.
Remarks
Other properties of this object may return a null reference (Nothing in Visual Basic) if this value is false. This may happen if the mail server incorrectly returns some parts of the namespace information.
See Also

Reference

ImapNamespace Class
MailBee.ImapMail Namespace


ImapNamespace.Prefix Property

ImapNamespacePrefix Property
The prefix which needs to be used in the beginning of a folder name to select it within the given namespace.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Prefix { get; }
Public ReadOnly Property Prefix As String
    Get

Property Value

Type: String
Empty string for Personal namespace, or mail-server dependent value for other namespaces (such as "~" for Other Users', "~public/" or "#" for Shared folders).
Remarks
To select a folder within the given namespace, prepend its name with this prefix: fullFolderName = namespace.Prefix + shortFolderName in C# syntax where shortFolderName is the folder name within the given namespace. Do NOT insert Delimiter value between the prefix and the folder name! Delimiter is only to be used levels in folder names (if folders are nested).
See Also

Reference

ImapNamespace Class
MailBee.ImapMail Namespace


ImapNamespaceCollection Class

ImapNamespaceCollection Class
Provides properties and methods for examining the collection of ImapNamespace objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailImapNamespaceCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapNamespaceCollection : CollectionBase
Public Class ImapNamespaceCollection
    Inherits CollectionBase

The ImapNamespaceCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | IsValid | Returns true if all the responses with the namespace data received from the mail server were correctly parsed.
Public property | Item | Gets the ImapNamespace object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks
A single ImapNamespaceCollection object lists all the namespaces which are defined for the current account and belong to a certain category. There are 3 categories (Personal, Other Users, Shared) and thus GetNamespaces method may return up to 3 ImapNamespaceCollection objects within ImapNamespaceCollectionSet object (which represents ALL the namespaces for the current e-mail account).
See Also

Reference

MailBee.ImapMail Namespace
ImapGetNamespaces


ImapNamespaceCollection Methods

ImapNamespaceCollection Methods

The ImapNamespaceCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapNamespaceCollection Class
MailBee.ImapMail Namespace


ImapNamespaceCollection Properties

ImapNamespaceCollection Properties

The ImapNamespaceCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | IsValid | Returns true if all the responses with the namespace data received from the mail server were correctly parsed.
Public property | Item | Gets the ImapNamespace object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

ImapNamespaceCollection Class
MailBee.ImapMail Namespace


ImapNamespaceCollection.IsValid Property

ImapNamespaceCollectionIsValid Property
Returns true if all the responses with the namespace data received from the mail server were correctly parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if all the responses with the namespace data received from the mail server were correctly parsed. Otherwise, false.
Remarks
Other items in this collection may return a null reference (Nothing in Visual Basic) if this value is false. This may happen if the mail server incorrectly returns some parts of the namespace information.
See Also

Reference

ImapNamespaceCollection Class
MailBee.ImapMail Namespace


ImapNamespaceCollection.Item Property

ImapNamespaceCollectionItem Property
Gets the ImapNamespace object at the specified zero-based index in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapNamespace this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As ImapNamespace
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the ImapNamespace object in the collection.

Property Value

Type: ImapNamespace
A ImapNamespace object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

ImapNamespaceCollection Class
MailBee.ImapMail Namespace
MailBee.ImapMailImapNamespace


ImapNamespaceCollectionSet Class

ImapNamespaceCollectionSet Class
Provides access to the lists of namespaces defined for the current e-mail account.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailImapNamespaceCollectionSet

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapNamespaceCollectionSet
Public Class ImapNamespaceCollectionSet

The ImapNamespaceCollectionSet type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | IsValid | Returns true if all the responses with the namespace data received from the mail server were correctly parsed.
Public property | OtherUser | Gets the reference to the list of Other Users' namespaces defined for the current e-mail account.
Public property | Personal | Gets the reference to the list of Personal namespaces defined for the current e-mail account.
Public property | Shared | Gets the reference to the list of Shared (Public) namespaces defined for the current e-mail account.
Top
Remarks
This is the top object in the hierarchy of namespaces. It provides 3 collections which list all the defined namespaces in Personal, Other Users and Shared categories.
See Also

Reference

MailBee.ImapMail Namespace
ImapGetNamespaces


ImapNamespaceCollectionSet Methods

ImapNamespaceCollectionSet Methods

The ImapNamespaceCollectionSet type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ImapNamespaceCollectionSet Class
MailBee.ImapMail Namespace


ImapNamespaceCollectionSet Properties

ImapNamespaceCollectionSet Properties

The ImapNamespaceCollectionSet type exposes the following members.

Properties
 | Name | Description
Public property | IsValid | Returns true if all the responses with the namespace data received from the mail server were correctly parsed.
Public property | OtherUser | Gets the reference to the list of Other Users' namespaces defined for the current e-mail account.
Public property | Personal | Gets the reference to the list of Personal namespaces defined for the current e-mail account.
Public property | Shared | Gets the reference to the list of Shared (Public) namespaces defined for the current e-mail account.
Top
See Also

Reference

ImapNamespaceCollectionSet Class
MailBee.ImapMail Namespace


ImapNamespaceCollectionSet.IsValid Property

ImapNamespaceCollectionSetIsValid Property
Returns true if all the responses with the namespace data received from the mail server were correctly parsed.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if all the responses with the namespace data received from the mail server were correctly parsed. Otherwise, false.
Remarks
Any properties of this object may return a null reference (Nothing in Visual Basic) if this value is false. This may happen if the mail server incorrectly returns some parts of the namespace information. However, Shared and OtherUser are optional and can return null even if IsValid is true.
See Also

Reference

ImapNamespaceCollectionSet Class
MailBee.ImapMail Namespace


ImapNamespaceCollectionSet.OtherUser Property

ImapNamespaceCollectionSetOtherUser Property
Gets the reference to the list of Other Users' namespaces defined for the current e-mail account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapNamespaceCollection OtherUser { get; }
Public ReadOnly Property OtherUser As ImapNamespaceCollection
    Get

Property Value

Type: ImapNamespaceCollection
The reference to the collection of all other users' namespaces defined for the current e-mail account, or a null reference (Nothing in Visual Basic) if no Other Users' namespaces are defined.
See Also

Reference

ImapNamespaceCollectionSet Class
MailBee.ImapMail Namespace


ImapNamespaceCollectionSet.Personal Property

ImapNamespaceCollectionSetPersonal Property
Gets the reference to the list of Personal namespaces defined for the current e-mail account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapNamespaceCollection Personal { get; }
Public ReadOnly Property Personal As ImapNamespaceCollection
    Get

Property Value

Type: ImapNamespaceCollection
The reference to the collection of all personal namespaces defined for the current e-mail account.
Remarks
Usually, the returned collection contains only a single element. If the returned value is a null reference (Nothing in Visual Basic), IsValid is true because it's an error that the e-mail account has no personal namespace. Usually, this means the data returned by the mail server could not be correctly parsed. This behaviour is different for OtherUser and Shared namespaces because they are optional and there is no error if any of them is missing.
See Also

Reference

ImapNamespaceCollectionSet Class
MailBee.ImapMail Namespace


ImapNamespaceCollectionSet.Shared Property

ImapNamespaceCollectionSetShared Property
Gets the reference to the list of Shared (Public) namespaces defined for the current e-mail account.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ImapNamespaceCollection Shared { get; }
Public ReadOnly Property Shared As ImapNamespaceCollection
    Get

Property Value

Type: ImapNamespaceCollection
The reference to the collection of all Shared namespaces defined for the current e-mail account, or a null reference (Nothing in Visual Basic) if no Shared namespaces are defined.
See Also

Reference

ImapNamespaceCollectionSet Class
MailBee.ImapMail Namespace


ImapUtils Class

ImapUtils Class
Provides static methods useful for processing IMAP4 strings, dates, folder names, etc.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailImapUtils

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ImapUtils
Public Class ImapUtils

The ImapUtils type exposes the following members.

Methods
 | Name | Description
 | AllOf | Creates IMAP search query of AND type.
 | AnyOf | Creates IMAP search query of OR type.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | FromUtf7String | Converts the specified string from the IMAP4 UTF-7 Modified encoding into human-readable form.
 | GetDateTimeFromImapDate | Converts the datetime string in IMAP4 format into DateTime value.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetImapDateString | Returns the string containing the current date of the local computer in the IMAP4 format.
 | GetImapDateString(DateTime) | Returns the string containing the specified date value in the IMAP4 format.
 | GetImapDateTimeString | Returns the string containing the current date and time of the local computer in the IMAP4 format.
 | GetImapDateTimeString(DateTime) | Returns the string containing the specified local date and time value in the IMAP4 format.
 | GetImapDateTimeString(DateTime, Boolean, Boolean) | Returns the string containing the specified date and time value in the IMAP4 format.
 | GetImapDateTimeString(DateTime, Boolean, String) | Returns the string containing the specified date and time value in the IMAP4 format.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | GmailSearch | Creates IMAP search query of Gmail type.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Not | Creates IMAP search query of NOT type.
 | ToLiteral(String) | Converts a text string into UTF-8 encoded IMAP LITERAL+ string.
 | ToLiteral(String, Encoding, Encoding) | Converts a text string into IMAP LITERAL+ string.
 | ToQuotedString | Converts the specified string into the IMAP4 quoted string.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | ToUtf7QuotedString | Converts the specified string into the IMAP4 UTF-7 Modified quoted string.
 | ToUtf7String | Converts the specified string into the IMAP4 UTF-7 Modified string.
 | ToUtf8QuotedString | Converts the specified string into the IMAP4 quoted and UTF-8 encoded string.
Top
See Also

Reference

MailBee.ImapMail Namespace


ImapUtils Methods

ImapUtils Methods

The ImapUtils type exposes the following members.

Methods
 | Name | Description
 | AllOf | Creates IMAP search query of AND type.
 | AnyOf | Creates IMAP search query of OR type.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | FromUtf7String | Converts the specified string from the IMAP4 UTF-7 Modified encoding into human-readable form.
 | GetDateTimeFromImapDate | Converts the datetime string in IMAP4 format into DateTime value.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetImapDateString | Returns the string containing the current date of the local computer in the IMAP4 format.
 | GetImapDateString(DateTime) | Returns the string containing the specified date value in the IMAP4 format.
 | GetImapDateTimeString | Returns the string containing the current date and time of the local computer in the IMAP4 format.
 | GetImapDateTimeString(DateTime) | Returns the string containing the specified local date and time value in the IMAP4 format.
 | GetImapDateTimeString(DateTime, Boolean, Boolean) | Returns the string containing the specified date and time value in the IMAP4 format.
 | GetImapDateTimeString(DateTime, Boolean, String) | Returns the string containing the specified date and time value in the IMAP4 format.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | GmailSearch | Creates IMAP search query of Gmail type.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Not | Creates IMAP search query of NOT type.
 | ToLiteral(String) | Converts a text string into UTF-8 encoded IMAP LITERAL+ string.
 | ToLiteral(String, Encoding, Encoding) | Converts a text string into IMAP LITERAL+ string.
 | ToQuotedString | Converts the specified string into the IMAP4 quoted string.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | ToUtf7QuotedString | Converts the specified string into the IMAP4 UTF-7 Modified quoted string.
 | ToUtf7String | Converts the specified string into the IMAP4 UTF-7 Modified string.
 | ToUtf8QuotedString | Converts the specified string into the IMAP4 quoted and UTF-8 encoded string.
Top
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


ImapUtils.AllOf Method

ImapUtilsAllOf Method
Creates IMAP search query of AND type.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string AllOf(
    params string[] list
)
Public Shared Function AllOf (
    ParamArray list As String()
) As String

Parameters

list
Type: SystemString
Search conditions to be ANDed.

Return Value

Type: String
The string containing ANDed search conditions.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | Any of the specified search conditions is a null reference (Nothing in Visual Basic) or an empty string, or if the specified list of search conditions is empty.
Remarks

This method allows you to produce ANDed query you can then pass to Search(Boolean, String, String) method. You can combine this method with other methods like AnyOf(String) to build complex and nested queries.

For instance, ImapUtils.AllOf("SINCE 1-Feb-1994", "FLAGGED", "OLD") returns (SINCE 1-Feb-1994 FLAGGED OLD).

See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)


ImapUtils.AnyOf Method

ImapUtilsAnyOf Method
Creates IMAP search query of OR type.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string AnyOf(
    params string[] list
)
Public Shared Function AnyOf (
    ParamArray list As String()
) As String

Parameters

list
Type: SystemString
Search conditions to be ORed.

Return Value

Type: String
The string containing ORed search conditions.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | Any of the specified search conditions is a null reference (Nothing in Visual Basic) or an empty string, or if the specified list of search conditions is empty.
Remarks

This method allows you to produce ORed query you can then pass to Search(Boolean, String, String) method. You can combine this method with other methods like AllOf(String) to build complex queries.

For instance, ImapUtils.AnyOf("SINCE 1-Feb-1994", "FLAGGED", "OLD") returns (OR (OR 1-Feb-1994 FLAGGED) OLD).

See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)


ImapUtils.FromUtf7String Method

ImapUtilsFromUtf7String Method
Converts the specified string from the IMAP4 UTF-7 Modified encoding into human-readable form.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string FromUtf7String(
    string s
)
Public Shared Function FromUtf7String (
    s As String
) As String

Parameters

s
Type: SystemString
The string (usually, a folder name) to be converted from the IMAP4 UTF-7 Modified string.

Return Value

Type: String
The decoded human-readable string, or a null reference (Nothing in Visual Basic) if s is a null reference.
Remarks
This method can be used to decode UTF-7 Mofified folder names into real values.
Note Note
All Imap methods which deal with folder names apply UTF-7M automatically and produce Folder objects which already have their Name and ShortName values properly decoded (although RawName is also available). There is no need to use FromUtf7String(String) method in this case. The same is true for folder names in other objects (such as FolderStatus).
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapUtilsToUtf7String(String)


ImapUtils.GetDateTimeFromImapDate Method

ImapUtilsGetDateTimeFromImapDate Method
Converts the datetime string in IMAP4 format into DateTime value.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static DateTime GetDateTimeFromImapDate(
    string dateTimeString
)
Public Shared Function GetDateTimeFromImapDate (
    dateTimeString As String
) As DateTime

Parameters

dateTimeString
Type: SystemString
The datetime string in IMAP4 format (can contain: date; date and time; date, time, and timezone).

Return Value

Type: DateTime
The DateTime value representing the parsed IMA4 datetime string, or MinValue if the specified datetime string could not be parsed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | dateTimeString is a null reference (Nothing in Visual Basic).
Remarks
The returned date is in UTC (GMT) time. To convert it into local time, the developer can use ToLocalTime method.
Examples
This sample parses a few IMAP4 datetime strings into DateTime structures and prints the results as UTC time and local time.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        DateTime dt;
        string dtString;

        dtString = "08-Sep-2004 13:47:32 -0400";

        Console.WriteLine(dtString);
        dt = ImapUtils.GetDateTimeFromImapDate(dtString);
        Console.WriteLine("UTC time: " + dt);
        Console.WriteLine("Local time: " + dt.ToLocalTime());
        Console.WriteLine();

        dtString = "20-May-2005 00:47:32";

        Console.WriteLine(dtString);
        dt = ImapUtils.GetDateTimeFromImapDate(dtString);
        Console.WriteLine("UTC time: " + dt);
        Console.WriteLine("Local time: " + dt.ToLocalTime());
        Console.WriteLine();

        dtString = "31-Jan-2005";

        Console.WriteLine(dtString);
        dt = ImapUtils.GetDateTimeFromImapDate(dtString);
        Console.WriteLine("UTC time: " + dt);
        Console.WriteLine("Local time: " + dt.ToLocalTime());
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        Dim dt As DateTime
        Dim dtString As String

        dtString = "08-Sep-2004 13:47:32 -0400"

        Console.WriteLine(dtString)
        dt = ImapUtils.GetDateTimeFromImapDate(dtString)
        Console.WriteLine("UTC time: " & dt)
        Console.WriteLine("Local time: " & dt.ToLocalTime())
        Console.WriteLine()

        dtString = "20-May-2005 00:47:32"

        Console.WriteLine(dtString)
        dt = ImapUtils.GetDateTimeFromImapDate(dtString)
        Console.WriteLine("UTC time: " & dt)
        Console.WriteLine("Local time: " & dt.ToLocalTime())
        Console.WriteLine()

        dtString = "31-Jan-2005"

        Console.WriteLine(dtString)
        dt = ImapUtils.GetDateTimeFromImapDate(dtString)
        Console.WriteLine("UTC time: " & dt)
        Console.WriteLine("Local time: " & dt.ToLocalTime())
    End Sub
End Module
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


ImapUtils.GetImapDateString Method

ImapUtilsGetImapDateString Method
Overload List
Name | Description
GetImapDateString | Returns the string containing the current date of the local computer in the IMAP4 format.
GetImapDateString(DateTime) | Returns the string containing the specified date value in the IMAP4 format.
Top
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


ImapUtils.GetImapDateString Method

ImapUtilsGetImapDateString Method
Returns the string containing the current date of the local computer in the IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetImapDateString()
Public Shared Function GetImapDateString As String

Return Value

Type: String
The string containing the current date of the local computer in the IMAP4 format.
Remarks
This method can be used to build "search by today's date" expressions when using Search(Boolean, String, String) or BeginSearch(Boolean, String, String, AsyncCallback, Object) methods. The IMAP4 protocol allows the client to search messages only by dates, not by exact datetime values.
Examples
This sample prints the current date of the local computer as IMAP4-formatted string.
C#
VB
Copy
using System;

class Sample
{
    static void Main(string[] args)
    {
        Console.WriteLine(MailBee.ImapMail.ImapUtils.GetImapDateString());
    }
}
Imports System

Module Sample
    Sub Main(ByVal args As String())
        Console.WriteLine(MailBee.ImapMail.ImapUtils.GetImapDateString())
    End Sub
End Module
See Also

Reference

ImapUtils Class
GetImapDateString Overload
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)
ImapBeginSearch(Boolean, String, String, AsyncCallback, Object)


ImapUtils.GetImapDateString Method (DateTime)

ImapUtilsGetImapDateString Method (DateTime)
Returns the string containing the specified date value in the IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetImapDateString(
    DateTime dt
)
Public Shared Function GetImapDateString (
    dt As DateTime
) As String

Parameters

dt
Type: SystemDateTime
The date and time value to return the date for.

Return Value

Type: String
The IMAP4 date string in "dd-MMM-yyyy" format.
Remarks
This method can be used to build "search by date" expressions when using Search(Boolean, String, String) or BeginSearch(Boolean, String, String, AsyncCallback, Object) methods. The IMAP4 protocol allows the client to search messages only by dates, not by exact datetime values.
Examples
This sample prints the current date of the local computer as IMAP4-formatted string.
C#
VB
Copy
using System;

class Sample
{
    static void Main(string[] args)
    {
        Console.WriteLine(
            MailBee.ImapMail.ImapUtils.GetImapDateString(DateTime.Now));
    }
}
Imports System

Module Sample
    Sub Main(ByVal args As String())
        Console.WriteLine( _
            MailBee.ImapMail.ImapUtils.GetImapDateString(DateTime.Now))
    End Sub
End Module
See Also

Reference

ImapUtils Class
GetImapDateString Overload
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)
ImapBeginSearch(Boolean, String, String, AsyncCallback, Object)


ImapUtils.GetImapDateTimeString Method

ImapUtilsGetImapDateTimeString Method
Overload List
Name | Description
GetImapDateTimeString | Returns the string containing the current date and time of the local computer in the IMAP4 format.
GetImapDateTimeString(DateTime) | Returns the string containing the specified local date and time value in the IMAP4 format.
GetImapDateTimeString(DateTime, Boolean, Boolean) | Returns the string containing the specified date and time value in the IMAP4 format.
GetImapDateTimeString(DateTime, Boolean, String) | Returns the string containing the specified date and time value in the IMAP4 format.
Top
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


ImapUtils.GetImapDateTimeString Method

ImapUtilsGetImapDateTimeString Method
Returns the string containing the current date and time of the local computer in the IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetImapDateTimeString()
Public Shared Function GetImapDateTimeString As String

Return Value

Type: String
The current date and time of the local computer as string in "dd-MMM-yyyy HH:mm:ss +/-HHmm" format.
Examples
This sample prints the current datetime of the local computer as IMAP4-formatted string.
C#
VB
Copy
using System;

class Sample
{
    static void Main(string[] args)
    {
        Console.WriteLine(MailBee.ImapMail.ImapUtils.GetImapDateTimeString());
    }
}
Imports System

Module Sample
    Sub Main(ByVal args As String())
        Console.WriteLine(MailBee.ImapMail.ImapUtils.GetImapDateTimeString())
    End Sub
End Module
See Also

Reference

ImapUtils Class
GetImapDateTimeString Overload
MailBee.ImapMail Namespace


ImapUtils.GetImapDateTimeString Method (DateTime)

ImapUtilsGetImapDateTimeString Method (DateTime)
Returns the string containing the specified local date and time value in the IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetImapDateTimeString(
    DateTime dt
)
Public Shared Function GetImapDateTimeString (
    dt As DateTime
) As String

Parameters

dt
Type: SystemDateTime
The date and time in the timezone of the local computer.

Return Value

Type: String
The IMAP4 datetime string in "dd-MMM-yyyy HH:mm:ss +/-HHmm" format.
Examples
This sample prints the current datetime of the local computer as IMAP4-formatted string.
C#
VB
Copy
using System;

class Sample
{
    static void Main(string[] args)
    {
        Console.WriteLine(
            MailBee.ImapMail.ImapUtils.GetImapDateTimeString(DateTime.Now));
    }
}
Imports System

Module Sample
    Sub Main(ByVal args As String())
        Console.WriteLine( _
            MailBee.ImapMail.ImapUtils.GetImapDateTimeString(DateTime.Now))
    End Sub
End Module
See Also

Reference

ImapUtils Class
GetImapDateTimeString Overload
MailBee.ImapMail Namespace


ImapUtils.GetImapDateTimeString Method (DateTime, Boolean, Boolean)

ImapUtilsGetImapDateTimeString Method (DateTime, Boolean, Boolean)
Returns the string containing the specified date and time value in the IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetImapDateTimeString(
    DateTime dt,
    bool includeTime,
    bool isUtc
)
Public Shared Function GetImapDateTimeString (
    dt As DateTime,
    includeTime As Boolean,
    isUtc As Boolean
) As String

Parameters

dt
Type: SystemDateTime
The date and time in UTC or local timezone.
includeTime
Type: SystemBoolean
If true, the date, time, and timezone will be included into the resulting string; otherwise, only the date will be included.
isUtc
Type: SystemBoolean
Indicates if dt is UTC time or local time. Ignored if includeTime is false.

Return Value

Type: String
The IMAP4 datetime string in "dd-MMM-yyyy HH:mm:ss +/-HHmm", "dd-MMM-yyyy HH:mm:ss", or "dd-MMM-yyyy" format.
Remarks

When is true, the timezone part of the returned string will be "+0000"; otherwise, the local timezone in "+/-HHmm" format (such as "-0500" for EST). However, if includeTime is false, the time and timezone information will not be appended to the resulting string. "

When uploading messages with UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method, the datetime value can contain all 3 fields (date, time, and timezone). When searching messages with Search(Boolean, String, String) method, datetime values can contain only date field.

Examples
This sample prints UTC and local time versions of certain DateTime value as IMAP4-formatted strings.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        // Assume it's 31-Dec-2005 20:00:00 (24 hrs clock) now,
        // and the local timezone is EST (UTC minus 5 hrs 0 mins).
        DateTime dtLocal = DateTime.Now;
        DateTime dtUtc = dtLocal.ToUniversalTime();

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtLocal, true, false));
        // The output: 31-Dec-2005 20:00:00 -0500

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtUtc, true, true));
        // The output: 01-Jan-2006 01:00:00 +0000

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtLocal, false, false));
        // The output: 31-Dec-2005

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtUtc, false, true));
        // The output: 01-Jan-2006
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        ' Assume it's 31-Dec-2005 20:00:00 (24 hrs clock) now,
        ' and the local timezone is EST (UTC minus 5 hrs 0 mins).
        Dim dtLocal, dtUtc As DateTime

        dtLocal = DateTime.Now()
        dtUtc = dtLocal.ToUniversalTime()

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtLocal, True, False))
        ' The output: 31-Dec-2005 20:00:00 -0500

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtUtc, True, True))
        ' The output: 01-Jan-2006 01:00:00 +0000

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtLocal, False, False))
        ' The output: 31-Dec-2005

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dtUtc, False, True))
        ' The output: 01-Jan-2006
    End Sub
End Module
See Also

Reference

ImapUtils Class
GetImapDateTimeString Overload
MailBee.ImapMail Namespace


ImapUtils.GetImapDateTimeString Method (DateTime, Boolean, String)

ImapUtilsGetImapDateTimeString Method (DateTime, Boolean, String)
Returns the string containing the specified date and time value in the IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetImapDateTimeString(
    DateTime dt,
    bool includeTime,
    string timeZoneOffset
)
Public Shared Function GetImapDateTimeString (
    dt As DateTime,
    includeTime As Boolean,
    timeZoneOffset As String
) As String

Parameters

dt
Type: SystemDateTime
The date and time.
includeTime
Type: SystemBoolean
If true, the date, time, and timezone will be included into the resulting string; otherwise, only the date will be included.
timeZoneOffset
Type: SystemString
The timezone string in "+/-HHmm" format, or a null reference (Nothing in Visual Basic) if no timezone should be specified. Ignored if includeTime is false.

Return Value

Type: String
The IMAP4 datetime string in "dd-MMM-yyyy HH:mm:ss +/-HHmm", "dd-MMM-yyyy HH:mm:ss", or "dd-MMM-yyyy" format.
Remarks

When uploading messages with UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method, the datetime value can contain all 3 fields (date, time, and timezone). When searching messages with Search(Boolean, String, String) method, datetime values can contain only date field.

Examples
This sample prints certain DateTime value as IMAP4-formatted string.
C#
VB
Copy
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    static void Main(string[] args)
    {
        // Assume it's 8 Apr 2006 14:45:50 (24 hrs clock) now,
        // and the local timezone is EDT (UTC minus 4 hrs 0 mins).
        DateTime dt = DateTime.Now;

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dt, true, "-0400"));
        // The output: 08-Apr-2006 14:45:50 -0400

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dt, false, "-0400"));
        // The output: 08-Apr-2006

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dt, true, null));
        // The output: 08-Apr-2006 14:45:50
    }
}
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    Sub Main(ByVal args As String())
        ' Assume it's 8 Apr 2006 14:45:50 (24 hrs clock) now,
        ' and the local timezone is EDT (UTC minus 4 hrs 0 mins).

        Dim dt As DateTime = DateTime.Now

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dt, True, "-0400"))
        ' The output: 08-Apr-2006 14:45:50 -0400

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dt, False, "-0400"))
        ' The output: 08-Apr-2006

        Console.WriteLine(ImapUtils.GetImapDateTimeString(dt, True, CType(Nothing, String)))
        ' The output: 08-Apr-2006 14:45:50
    End Sub
End Module
See Also

Reference

ImapUtils Class
GetImapDateTimeString Overload
MailBee.ImapMail Namespace


ImapUtils.GmailSearch Method

ImapUtilsGmailSearch Method
Creates IMAP search query of Gmail type.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GmailSearch(
    string s
)
Public Shared Function GmailSearch (
    s As String
) As String

Parameters

s
Type: SystemString
Search condition.

Return Value

Type: String
The string containing Gmail search condition wrapped with X-GM-RAW verb.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | The specified string is a null reference (Nothing in Visual Basic).
Remarks

This method lets you use search conditions in Gmail syntax when you work with Gmail-compatible server. For instance, s can be has:attachment in:unread or SomeWord or "Any text" in:read. MailBee wraps it with a special IMAP search verb (X-GM-RAW) recognized by Gmail so that you can supply it to Search(Boolean, String, String) method to find items with a familiar and flexible Gmail syntax. For instance, it allows for finding attachments while the standard IMAP syntax doesn't.

Non-ASCII text is encoded in UTF-8 with this method. Thus, if you search non-ASCII, you must pass "utf-8" as charset value when calling Search(Boolean, String, String) method.

Note Note
The mail server must support Gmail search syntax ("x-gm-ext-1" capability must be listed in GetExtensions results). See Google IMAP Extensions for details.
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


ImapUtils.Not Method

ImapUtilsNot Method
Creates IMAP search query of NOT type.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string Not(
    string s
)
Public Shared Function Not (
    s As String
) As String

Parameters

s
Type: SystemString
Search condition to be inverted.

Return Value

Type: String
The string containing the inverted search condition.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | The specified string is a null reference (Nothing in Visual Basic) or an empty string.
Remarks

This method allows you to produce the inverted query you can then pass to Search(Boolean, String, String) method. You can combine this method with other methods like AnyOf(String) to build complex queries.

For instance, if s is SINCE 1-Feb-1994, the return value is NOT SINCE 1-Feb-1994.

Note Note
Many IMAP search conditions already have native inverse versions. For instance, KEYWORD has UNKEYWORD counterpart. However, there is no harm to use NOT with such conditions (i.e. NOT KEYWORD has exacty the same effect as UNKEYWORD).
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)


ImapUtils.ToLiteral Method

ImapUtilsToLiteral Method
Converts a text string into IMAP LITERAL+ string.
Overload List
Name | Description
ToLiteral(String) | Converts a text string into UTF-8 encoded IMAP LITERAL+ string.
ToLiteral(String, Encoding, Encoding) | Converts a text string into IMAP LITERAL+ string.
Top
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


ImapUtils.ToLiteral Method (String)

ImapUtilsToLiteral Method (String)
Converts a text string into UTF-8 encoded IMAP LITERAL+ string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string ToLiteral(
    string s
)
Public Shared Function ToLiteral (
    s As String
) As String

Parameters

s
Type: SystemString
The text string to convert.

Return Value

Type: String
The UTF-8 encoded LITERAL+ string, or an empty quoted string ("") if the source string is an empty string or a null reference (Nothing in Visual Basic).
Remarks

You'll typically use this method to build search string in UTF-8 charset when the IMAP server is Gmail.

Note Note
This method produces literals in very efficient LITERAL+ syntax. Gmail does not advertize the support of LITERAL+ extension but it's actually supported.
See Also

Reference

ImapUtils Class
ToLiteral Overload
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)


ImapUtils.ToLiteral Method (String, Encoding, Encoding)

ImapUtilsToLiteral Method (String, Encoding, Encoding)
Converts a text string into IMAP LITERAL+ string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string ToLiteral(
    string s,
    Encoding charsetEncoding,
    Encoding requestEncoding
)
Public Shared Function ToLiteral (
    s As String,
    charsetEncoding As Encoding,
    requestEncoding As Encoding
) As String

Parameters

s
Type: SystemString
The text string to convert.
charsetEncoding
Type: System.TextEncoding
Denotes the charset of the resulting string. If a null reference (Nothing in Visual Basic), UTF8 is used. Must match the charset specified in Search(Boolean, String, String) method call.
requestEncoding
Type: System.TextEncoding
Must match RequestEncoding value. If a null reference, DefaultEncoding is used (RequestEncoding uses the same default value).

Return Value

Type: String
The encoded LITERAL+ string, or an empty quoted string ("") if the source string is an empty string or a null reference.
Remarks

You'll typically use this method to build search string in non-ASCII charset when the IMAP server is Gmail.

If you're using UTF-8 charset for search strings and you never changed RequestEncoding from its default value, use ToLiteral(String) overload instead.

Note Note
This method produces literals in very efficient LITERAL+ syntax. Gmail does not advertize the support of LITERAL+ extension but it's actually supported.
See Also

Reference

ImapUtils Class
ToLiteral Overload
MailBee.ImapMail Namespace
ImapSearch(Boolean, String, String)


ImapUtils.ToQuotedString Method

ImapUtilsToQuotedString Method
Converts the specified string into the IMAP4 quoted string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string ToQuotedString(
    string s
)
Public Shared Function ToQuotedString (
    s As String
) As String

Parameters

s
Type: SystemString
The string to be converted into the IMAP4 quoted string.

Return Value

Type: String
The IMAP4 quoted string.
Remarks

This method escapes all quote and backslash characters and encloses the result in quotes. If s is a null reference (Nothing) in Visual Basic), empty quoted string ("") is returned.

The method can be used to build "search by text" expressions when using Search(Boolean, String, String) or BeginSearch(Boolean, String, String, AsyncCallback, Object) methods.

Note Note
If you need to search non-ASCII strings (non-English), use ToUtf8QuotedString(String) method instead. Also, charset parameter in Search(Boolean, String, String) method call must be "UTF-8".
Note Note
With Gmail, use ToLiteral(String) method instead.
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapUtilsToUtf8QuotedString(String)
ImapSearch(Boolean, String, String)
ImapBeginSearch(Boolean, String, String, AsyncCallback, Object)


ImapUtils.ToUtf7QuotedString Method

ImapUtilsToUtf7QuotedString Method
Converts the specified string into the IMAP4 UTF-7 Modified quoted string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string ToUtf7QuotedString(
    string s
)
Public Shared Function ToUtf7QuotedString (
    s As String
) As String

Parameters

s
Type: SystemString
The string (usually, a folder name) to be converted into the IMAP4 UTF-7 Modified quoted string.

Return Value

Type: String
The IMAP4 UTF-7 Modified quoted string.
Remarks

This method converts the source string contents into UTF-7 Modified string and escapes all quote and backslash characters and encloses the result in quotes. If s is a null reference (Nothing) in Visual Basic), empty quoted string ("") is returned.

The method can be used to refer international folder names when building an IMAP4 request to create/delete/rename or otherwise manage folder manually (i.e. using ExecuteCustomCommand(String, String) method).

Note Note
SelectFolder(String), CreateFolder(String), etc apply character escaping and UTF-7 Modified transformations automatically (unless Utf7EncodeFolderNames is false). The developer should not attempt to use ToUtf7QuotedString(String) method in this case. Even if Utf7EncodeFolderNames is false, quote and backslash characters in folder names are still automatically escaped, and the developer should use ToUtf7String(String) rather than ToUtf7QuotedString(String) to apply UTF-7 Modified.
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapExecuteCustomCommand(String, String)


ImapUtils.ToUtf7String Method

ImapUtilsToUtf7String Method
Converts the specified string into the IMAP4 UTF-7 Modified string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string ToUtf7String(
    string s
)
Public Shared Function ToUtf7String (
    s As String
) As String

Parameters

s
Type: SystemString
The string (usually, a folder name) to be converted into the IMAP4 UTF-7 Modified string.

Return Value

Type: String
The IMAP4 UTF-7 Modified string, or a null reference (Nothing in Visual Basic) if s is a null reference.
Remarks

ToUtf7QuotedString(String) method should be used in the case if the developer constructs the entire request manually (for instance, for further sending it to the server using ExecuteCustomCommand(String, String) method) and wants the target string being enclosed in quotes (including proper escaping of any quotes inside the string) as well as being UTF-7M transformed.

ToUtf7String(String) method should be used for strings which will be quote/slash-escaped later (for instance, if the result of ToUtf7String(String) is passed to a method such as SelectFolder(String) which automatically escapes folder names).

Note Note
By default (Utf7EncodeFolderNames is true), all Imap methods which deal with folder names apply UTF-7M automatically (and there is no need to use ToUtf7String(String) method). Even if Utf7EncodeFolderNames is false and there is a need to process (e.g. select) a folder which name was received from the server, it's usually easier to directly use raw names of folders (e.g. RawName) than to manually convert decoded names (such as Name) back to UTF-7M.
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace
ImapUtilsToUtf7QuotedString(String)


ImapUtils.ToUtf8QuotedString Method

ImapUtilsToUtf8QuotedString Method
Converts the specified string into the IMAP4 quoted and UTF-8 encoded string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string ToUtf8QuotedString(
    string s
)
Public Shared Function ToUtf8QuotedString (
    s As String
) As String

Parameters

s
Type: SystemString
The string to be converted into the IMAP4 quoted and UTF-8 encoded string.

Return Value

Type: String
The IMAP4 quoted and UTF-8 encoded string.
Remarks
The method can be used to build "search by non-English text" expressions when using Search(Boolean, String, String) or BeginSearch(Boolean, String, String, AsyncCallback, Object) methods.
Note Note
With Gmail, use ToLiteral(String) method instead.
See Also

Reference

ImapUtils Class
MailBee.ImapMail Namespace


MessageFlagAction Enumeration

MessageFlagAction Enumeration
Defines actions to be performed with the message flags.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MessageFlagAction
Public Enumeration MessageFlagAction
Members
Member name | Value | Description
Replace | 0 | The specified flags will replace the existing flags of the message.
Add | 1 | The specified flags will be added to the list of existing flags of the message.
Remove | 2 | The specified flags will be removed from the list existing flags of the message.
ReplaceGmailLabel | 3 | The specified Gmail labels will replace the existing Gmail labels of the message.
AddGmailLabel | 4 | The specified Gmail labels will be added to the list of existing Gmail labels of the message.
RemoveGmailLabel | 5 | The specified Gmail labels will be removed from the list existing Gmail labels of the message.
Remarks

It's not error to attempt to remove flags which are not set or add flags which are already set. The server will simply do nothing in this case. For instance, if the application sets "\Deleted" flag for two messages and the first message already has this flag set, the first message flags will remain intact while the second message will acquire the "\Deleted" flag.

To remove all flags from the message (including both system and server-specific flags), the developer should call SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) method passing empty flags and specifying Replace as action parameter value.

Values with GmailLabel suffix allow for setting Gmail-specific labels instead of ordinary IMAP flags. To use this functionality, make sure your mail server is Gmail-compatible ("x-gm-ext-1" capability must be listed in GetExtensions results). Gmail labels can only be used as strings (not as SystemMessageFlags values) so that you must use SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) overload to set them.

See Also

Reference

MailBee.ImapMail Namespace
ImapSetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean)


MessageFlagSet Class

MessageFlagSet Class
Represents a set of flags of a mail message.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailMessageFlagSet

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MessageFlagSet
Public Class MessageFlagSet

The MessageFlagSet type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | SystemFlagsToString | Converts the specified set of system message flags into IMAP4 flag list.
Public method | ToString | Returns the entire list of flags as a string. (Overrides ObjectToString.)
Top
Properties
 | Name | Description
Public property | AllFlags | Gets the entire list of flags as array of strings.
Public property | SystemFlags | Gets the system (standard) flags subset of the entire list of flags.
Top
Remarks

Message flags can be of two types: system (standard) and non-standard. System flags can be examined using SystemFlags property. AllFlags property returns all the flags as an array of strings. ToString method returns all the the flags as a string.

To learn flags of particular messages, the developer can use DownloadEnvelopes(String, Boolean) method (or its overloads), and then examine Flags property of Envelope objects contained within the returned EnvelopeCollection.

To learn which message flags are defined in the currently selected folder, the developer can use Flags property of the Imap object.

To learn which message flags can be applied to messages permanently of whether it's allowed to define new flags by applying them to messages, the developer can use PermanentFlags property of the Imap object.

To apply flags to messages, the developer can use SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) method. DeleteMessages(String, Boolean) method is a particular case of SetMessageFlags(String, Boolean, String, MessageFlagAction, Boolean) method which adds "\Deleted" flag to messages.

To search messages having specified flags set, the developer can use Search(Boolean, String, String) method.

Note Note
Message flags is not the same as folder flags (FolderFlags). Each folder has 3 groups of flags set: folder flags (which can be examined via Flags property of Folder object), permanent message flags (PermanentFlags property of the Imap object), and available message flags (Flags property of the Imap object).
See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailSystemMessageFlags


MessageFlagSet Methods

MessageFlagSet Methods

The MessageFlagSet type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | SystemFlagsToString | Converts the specified set of system message flags into IMAP4 flag list.
Public method | ToString | Returns the entire list of flags as a string. (Overrides ObjectToString.)
Top
See Also

Reference

MessageFlagSet Class
MailBee.ImapMail Namespace


MessageFlagSet.SystemFlagsToString Method

MessageFlagSetSystemFlagsToString Method
Converts the specified set of system message flags into IMAP4 flag list.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string SystemFlagsToString(
    SystemMessageFlags systemFlags
)
Public Shared Function SystemFlagsToString (
    systemFlags As SystemMessageFlags
) As String

Parameters

systemFlags
Type: MailBee.ImapMailSystemMessageFlags
A set of system flags.

Return Value

Type: String
The space-delimited flag list string in IMAP4 format containing the specified system flags.
Remarks
Example of the returned value: "\Seen \Answered".
See Also

Reference

MessageFlagSet Class
MailBee.ImapMail Namespace


MessageFlagSet.ToString Method

MessageFlagSetToString Method
Returns the entire list of flags as a string.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
The string containing all the message flags associated with the given message or folder as a space-delimited list.
Remarks
The returned string is in IMAP4 format of flag list. For instance, "\Seen \Answered $Personal".
See Also

Reference

MessageFlagSet Class
MailBee.ImapMail Namespace


MessageFlagSet Properties

MessageFlagSet Properties

The MessageFlagSet type exposes the following members.

Properties
 | Name | Description
Public property | AllFlags | Gets the entire list of flags as array of strings.
Public property | SystemFlags | Gets the system (standard) flags subset of the entire list of flags.
Top
See Also

Reference

MessageFlagSet Class
MailBee.ImapMail Namespace


MessageFlagSet.AllFlags Property

MessageFlagSetAllFlags Property
Gets the entire list of flags as array of strings.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] AllFlags { get; }
Public ReadOnly Property AllFlags As String()
    Get

Property Value

Type: String
The array of strings containing all the message flags associated with the given message or folder.
Remarks
In the returned array, system flags are prefixed with "\" character. For instance, the following list can be returned: "\Seen", "\Answered", "$Personal".
Note Note
In C#, "\" character has special meaning. To insert it into string, either duplicate it or prefix the entire string with "@" character.
See Also

Reference

MessageFlagSet Class
MailBee.ImapMail Namespace


MessageFlagSet.SystemFlags Property

MessageFlagSetSystemFlags Property
Gets the system (standard) flags subset of the entire list of flags.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SystemMessageFlags SystemFlags { get; }
Public ReadOnly Property SystemFlags As SystemMessageFlags
    Get

Property Value

Type: SystemMessageFlags
The SystemMessageFlags enumeration containing the system message flags associated with the given message or folder.
See Also

Reference

MessageFlagSet Class
MailBee.ImapMail Namespace


MessageIndexCollection Class

MessageIndexCollection Class
Represents an abstract list of indices (such as ordinal message numbers or UIDs) of mail messages.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailMessageIndexCollection
MailBee.ImapMailMessageNumberCollection
MailBee.ImapMailUidCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MessageIndexCollection : CollectionBase
Public MustInherit Class MessageIndexCollection
    Inherits CollectionBase

The MessageIndexCollection type exposes the following members.

Constructors
 | Name | Description
Protected method | MessageIndexCollection | Initializes a new instance of the MessageIndexCollection class
Top
Methods
 | Name | Description
Public method | AddIndex | When overridden in a derived class, should add the message index (ordinal message number or UID) specified as string, to the collection.
Public method | AddRange | When overridden in a derived class, should add the specified range of message numbers or UIDs to the collection.
Public method | AddSet | Adds the specified sequence of message numbers or UIDs to the collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | IsPartOfRange | This member is not intended to be used directly from your code.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns the message sequence as a string in IMAP4 format. (Overrides ObjectToString.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

This class is an abstract parent of MessageNumberCollection and UidCollection classes.

Some methods of the Imap object (such as Search(Boolean, String, String)) can return both a collection of ordinal message numbers (MessageNumberCollection) and a collection of UIDs (UidCollection). The type of the returned collection is contolled via indexIsUid parameter value of these methods. Also, the developer should typecast the returned value to the appropriate type (MessageNumberCollection or UidCollection). See the sample code in Search(Boolean, String, String) topic for more information.

MessageNumberCollection and UidCollection classes can also be used to build and parse sequences of UIDs or message numbers in IMAP4 format (e.g. "5,8,14:22,24:26,35").

See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailMessageNumberCollection
MailBee.ImapMailUidCollection
ImapSearch(Boolean, String, String)


MessageIndexCollection Constructor

MessageIndexCollection Constructor
Initializes a new instance of the MessageIndexCollection class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MessageIndexCollection()
Protected Sub New
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace


MessageIndexCollection Methods

MessageIndexCollection Methods

The MessageIndexCollection type exposes the following members.

Methods
 | Name | Description
Public method | AddIndex | When overridden in a derived class, should add the message index (ordinal message number or UID) specified as string, to the collection.
Public method | AddRange | When overridden in a derived class, should add the specified range of message numbers or UIDs to the collection.
Public method | AddSet | Adds the specified sequence of message numbers or UIDs to the collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | IsPartOfRange | This member is not intended to be used directly from your code.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns the message sequence as a string in IMAP4 format. (Overrides ObjectToString.)
Top
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace


MessageIndexCollection.AddIndex Method

MessageIndexCollectionAddIndex Method
When overridden in a derived class, should add the message index (ordinal message number or UID) specified as string, to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract void AddIndex(
    string index
)
Public MustOverride Sub AddIndex (
    index As String
)

Parameters

index
Type: SystemString
The message index.
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace
MailBee.ImapMailMessageNumberCollection
MailBee.ImapMailUidCollection


MessageIndexCollection.AddRange Method

MessageIndexCollectionAddRange Method
When overridden in a derived class, should add the specified range of message numbers or UIDs to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract void AddRange(
    string startIndex,
    string endIndex
)
Public MustOverride Sub AddRange (
    startIndex As String,
    endIndex As String
)

Parameters

startIndex
Type: SystemString
The lower index of the range.
endIndex
Type: SystemString
The higher index of the range.
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace
MailBee.ImapMailMessageNumberCollection
MailBee.ImapMailUidCollection


MessageIndexCollection.AddSet Method

MessageIndexCollectionAddSet Method
Adds the specified sequence of message numbers or UIDs to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddSet(
    string messageIndexSet
)
Public Sub AddSet (
    messageIndexSet As String
)

Parameters

messageIndexSet
Type: SystemString
The message sequence in IMAP4 format.
Exceptions
Exception | Condition
Exception | The message sequence parsing failed.
Remarks
The sequence to be parsed can contain the following characters only: digits (0-9), commas (,), and colon (:). Also, the sequence must be monotonically increasing. Examples of valid sequences: "1", "4:5,7,9", "1:135", "15,29".
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace


MessageIndexCollection.IsPartOfRange Method

MessageIndexCollectionIsPartOfRange Method
This member is not intended to be used directly from your code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected abstract bool IsPartOfRange(
    int index
)
Protected MustOverride Function IsPartOfRange (
    index As Integer
) As Boolean

Parameters

index
Type: SystemInt32
Index.

Return Value

Type: Boolean
Boolean value.
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace


MessageIndexCollection.ToString Method

MessageIndexCollectionToString Method
Returns the message sequence as a string in IMAP4 format.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
The string containing the message sequence in IMAP4 format.
Remarks
For instance, if the collection contains message indices 5, 8, 11, 12, 13, 67, 68, this method returns "5,8,11:13,67:68".
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace


MessageIndexCollection Properties

MessageIndexCollection Properties

The MessageIndexCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MessageIndexCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection Class

MessageNumberCollection Class
Represents a list of ordinal message numbers of mail messages.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailMessageIndexCollection
MailBee.ImapMailMessageNumberCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MessageNumberCollection : MessageIndexCollection
Public Class MessageNumberCollection
    Inherits MessageIndexCollection

The MessageNumberCollection type exposes the following members.

Constructors
 | Name | Description
Public method | MessageNumberCollection | Initializes a new instance of the MessageNumberCollection class
Top
Methods
 | Name | Description
Public method | Add | Adds the specified ordinal message number to the collection.
Public method | AddIndex | Adds the ordinal message number specified as string, to the collection. (Overrides MessageIndexCollectionAddIndex(String).)
Public method | AddRange | Adds the specified range of message numbers to the collection. (Overrides MessageIndexCollectionAddRange(String, String).)
Public method | AddSet | Adds the specified sequence of message numbers or UIDs to the collection. (Inherited from MessageIndexCollection.)
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IndexOf | Returns the zero-based index of the first occurrence of the specified ordinal message number in the collection.
Protected method | IsPartOfRange | This member is not intended to be used directly from your code. (Overrides MessageIndexCollectionIsPartOfRange(Int32).)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Parse | Creates a new MessageNumberCollection from the specified message number sequence.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToArray | Gets all the items in the collection as an array.
Public method | ToString | Returns the message sequence as a string in IMAP4 format. (Inherited from MessageIndexCollection.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the ordinal message number at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

This class implements MessageIndexCollection as a collection of Int32 values.

Note Note
Although .NET collections are zero-based, message indices (ordinal message numbers and UIDs) are one-based. E.g. if this collection contains a single item referencing the first message in the folder, the index of this item in the collection will be 0, while its value (message number) will be 1.
See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailMessageIndexCollection
MailBee.ImapMailUidCollection
ImapSearch(Boolean, String, String)


MessageNumberCollection Constructor

MessageNumberCollection Constructor
Initializes a new instance of the MessageNumberCollection class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageNumberCollection()
Public Sub New
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection Methods

MessageNumberCollection Methods

The MessageNumberCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds the specified ordinal message number to the collection.
Public method | AddIndex | Adds the ordinal message number specified as string, to the collection. (Overrides MessageIndexCollectionAddIndex(String).)
Public method | AddRange | Adds the specified range of message numbers to the collection. (Overrides MessageIndexCollectionAddRange(String, String).)
Public method | AddSet | Adds the specified sequence of message numbers or UIDs to the collection. (Inherited from MessageIndexCollection.)
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IndexOf | Returns the zero-based index of the first occurrence of the specified ordinal message number in the collection.
Protected method | IsPartOfRange | This member is not intended to be used directly from your code. (Overrides MessageIndexCollectionIsPartOfRange(Int32).)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Parse | Creates a new MessageNumberCollection from the specified message number sequence.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToArray | Gets all the items in the collection as an array.
Public method | ToString | Returns the message sequence as a string in IMAP4 format. (Inherited from MessageIndexCollection.)
Top
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.Add Method

MessageNumberCollectionAdd Method
Adds the specified ordinal message number to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    int messageNumber
)
Public Sub Add (
    messageNumber As Integer
)

Parameters

messageNumber
Type: SystemInt32
The ordinal message number.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.AddIndex Method

MessageNumberCollectionAddIndex Method
Adds the ordinal message number specified as string, to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override void AddIndex(
    string index
)
Public Overrides Sub AddIndex (
    index As String
)

Parameters

index
Type: SystemString
The string containing the ordinal message number to be added.
Exceptions
Exception | Condition
Exception | Parsing the supplied string into an ordinal message number failed.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.AddRange Method

MessageNumberCollectionAddRange Method
Adds the specified range of message numbers to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override void AddRange(
    string startIndex,
    string endIndex
)
Public Overrides Sub AddRange (
    startIndex As String,
    endIndex As String
)

Parameters

startIndex
Type: SystemString
The string containing the lower message number in the range.
endIndex
Type: SystemString
The string containing the higher message number in the range.
Exceptions
Exception | Condition
Exception | Parsing the supplied strings into message numbers failed.
Remarks
endIndex must be not less than startIndex.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.IndexOf Method

MessageNumberCollectionIndexOf Method
Returns the zero-based index of the first occurrence of the specified ordinal message number in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int IndexOf(
    int messageNumber
)
Public Function IndexOf (
    messageNumber As Integer
) As Integer

Parameters

messageNumber
Type: SystemInt32
The ordinal message number to be searched for.

Return Value

Type: Int32
A zero-based index of the first occurrence of the specified ordinal message number in the collection, or -1 if not found.
Remarks
The collection is zero-based (the first item has the position of 0) but the item values are 1-based (because message numbers in IMAP start from 1).
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.IsPartOfRange Method

MessageNumberCollectionIsPartOfRange Method
This member is not intended to be used directly from your code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected override bool IsPartOfRange(
    int index
)
Protected Overrides Function IsPartOfRange (
    index As Integer
) As Boolean

Parameters

index
Type: SystemInt32
Index.

Return Value

Type: Boolean
Boolean value.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.Parse Method

MessageNumberCollectionParse Method
Creates a new MessageNumberCollection from the specified message number sequence.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MessageNumberCollection Parse(
    string messageNumberString
)
Public Shared Function Parse (
    messageNumberString As String
) As MessageNumberCollection

Parameters

messageNumberString
Type: SystemString
The string containing the sequence of ordinal message numbers in IMAP4 format.

Return Value

Type: MessageNumberCollection
A reference to the MessageNumberCollection object representing the specified message number sequence, or a null reference (Nothing in Visual Basic) if the message number sequence could not be parsed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | messageNumberString is a null reference (Nothing in Visual Basic).
Remarks
The messageNumberString must conform to the rules described in AddSet(String) method remarks.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.ToArray Method

MessageNumberCollectionToArray Method
Gets all the items in the collection as an array.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int[] ToArray()
Public Function ToArray As Integer()

Return Value

Type: Int32
The array containing all the ordinal message numbers in the collection.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection Properties

MessageNumberCollection Properties

The MessageNumberCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the ordinal message number at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


MessageNumberCollection.Item Property

MessageNumberCollectionItem Property
Gets the ordinal message number at the specified zero-based index in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Integer
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the ordinal message number in the collection.

Property Value

Type: Int32
An Int32 value having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

MessageNumberCollection Class
MailBee.ImapMail Namespace


SystemMessageFlags Enumeration

SystemMessageFlags Enumeration
Defines the standard (system) flags which can be set or examined for mail messages in the folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum SystemMessageFlags
<FlagsAttribute>
Public Enumeration SystemMessageFlags
Members
Member name | Value | Description
None | 0 | No flags set.
Seen | 1 | Message has been read.
Answered | 2 | Message has been answered.
Flagged | 4 | Message is "flagged" for urgent/special attention.
Deleted | 8 | Message is "deleted" for removal by later Expunge or Close.
Draft | 16 | Message has not completed composition (marked as a draft).
Recent | 32 | Message is "recently" arrived in this folder. This session is the first session to have been notified about this message; if the session is read-write (the folder was selected with SelectFolder(String) method), subsequent sessions will not see "\Recent" set for this message. If the folder was selected in read-only mode (using ExamineFolder(String) method), "\Recent" flag will not be removed from the message. This flag can not be altered by the client.
CanCreate | 64 | "\*" flag. This special flag may appear only in Imap.PermanentFlags.SystemFlags value. If it's present, it indicates it's possible to create new flags in this folder by attempting to set those flags for messages.
Other | 128 | There are some other (non-system) flags set. The developer may examine AllFlags property of MessageFlagSet object to get the list of all flags set.
Remarks

To examine flags of an existing message (or messages), the developer can use DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32) method setting Flags bit in parts parameter value. Then, the developer should iterate through the returned EnvelopeCollection and examine Envelope.Flags property value. This property returns MessageFlagSet object which represents all flags of the message including both system flags and non-standard flags.

System flags can be examined via SystemFlags property of MessageFlagSet object.

To set specific system flags for messages, the developer can use SetMessageFlags(String, Boolean, SystemMessageFlags, MessageFlagAction) method.

See MessageFlagSet topic on more information regarding message flags.

See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailMessageFlagSet


UidCollection Class

UidCollection Class
Represents a list of UIDs of mail messages.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.ImapMailMessageIndexCollection
MailBee.ImapMailUidCollection

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class UidCollection : MessageIndexCollection
Public Class UidCollection
    Inherits MessageIndexCollection

The UidCollection type exposes the following members.

Constructors
 | Name | Description
Public method | UidCollection | Initializes a new instance of the UidCollection class
Top
Methods
 | Name | Description
Public method | Add | Adds the specified UID to the collection.
Public method | AddIndex | Adds the UID specified as string, to the collection. (Overrides MessageIndexCollectionAddIndex(String).)
Public method | AddRange | Adds the specified range of UIDs to the collection. (Overrides MessageIndexCollectionAddRange(String, String).)
Public method | AddSet | Adds the specified sequence of message numbers or UIDs to the collection. (Inherited from MessageIndexCollection.)
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IndexOf | Returns the zero-based index of the first occurrence of the specified UID in the collection.
Protected method | IsPartOfRange | This member is not intended to be used directly from your code. (Overrides MessageIndexCollectionIsPartOfRange(Int32).)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Parse | Creates a new UidCollection from the specified UID sequence.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToArray | Gets all the items in the collection as an array.
Public method | ToString | Returns the message sequence as a string in IMAP4 format. (Inherited from MessageIndexCollection.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the UID at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

This class implements MessageIndexCollection as a collection of Int64 values.

Note Note
In MailBee, UID is represented as a Int64 value. Actually, UID is a 32-bit unsigned value. Due to this, it's possible to get UID value which won't fit in the range of values allowed for Int32 type (which is 32-bit signed). Although .NET framework supports UInt32 type (32-bit unsigned), not all .NET languages support this type (i.e. it's not CLS-compliant). Also, with UInt32 it's not possible to represent negative values which are used by MailBee to represent invalid data (such as when certain value cannot be parsed).
See Also

Reference

MailBee.ImapMail Namespace
MailBee.ImapMailMessageIndexCollection
MailBee.ImapMailMessageNumberCollection
ImapSearch(Boolean, String, String)


UidCollection Constructor

UidCollection Constructor
Initializes a new instance of the UidCollection class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public UidCollection()
Public Sub New
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection Methods

UidCollection Methods

The UidCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds the specified UID to the collection.
Public method | AddIndex | Adds the UID specified as string, to the collection. (Overrides MessageIndexCollectionAddIndex(String).)
Public method | AddRange | Adds the specified range of UIDs to the collection. (Overrides MessageIndexCollectionAddRange(String, String).)
Public method | AddSet | Adds the specified sequence of message numbers or UIDs to the collection. (Inherited from MessageIndexCollection.)
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | IndexOf | Returns the zero-based index of the first occurrence of the specified UID in the collection.
Protected method | IsPartOfRange | This member is not intended to be used directly from your code. (Overrides MessageIndexCollectionIsPartOfRange(Int32).)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Parse | Creates a new UidCollection from the specified UID sequence.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToArray | Gets all the items in the collection as an array.
Public method | ToString | Returns the message sequence as a string in IMAP4 format. (Inherited from MessageIndexCollection.)
Top
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.Add Method

UidCollectionAdd Method
Adds the specified UID to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    long uid
)
Public Sub Add (
    uid As Long
)

Parameters

uid
Type: SystemInt64
The UID value.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.AddIndex Method

UidCollectionAddIndex Method
Adds the UID specified as string, to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override void AddIndex(
    string index
)
Public Overrides Sub AddIndex (
    index As String
)

Parameters

index
Type: SystemString
The string containing the UID to be added.
Exceptions
Exception | Condition
Exception | Parsing the supplied string into UID failed.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.AddRange Method

UidCollectionAddRange Method
Adds the specified range of UIDs to the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override void AddRange(
    string startIndex,
    string endIndex
)
Public Overrides Sub AddRange (
    startIndex As String,
    endIndex As String
)

Parameters

startIndex
Type: SystemString
The string containing the lower UID in the range.
endIndex
Type: SystemString
The string containing the higher UID in the range.
Exceptions
Exception | Condition
Exception | Parsing the supplied strings into UIDs failed.
Remarks
endIndex must be not less than startIndex.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.IndexOf Method

UidCollectionIndexOf Method
Returns the zero-based index of the first occurrence of the specified UID in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int IndexOf(
    long uid
)
Public Function IndexOf (
    uid As Long
) As Integer

Parameters

uid
Type: SystemInt64
The UID to be searched for.

Return Value

Type: Int32
A zero-based index of the first occurrence of the specified UID in the collection, or -1 if not found.
Remarks
The collection is zero-based (the first item has the position of 0) but the item values are 1-based (because UIDs in IMAP start from 1).
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.IsPartOfRange Method

UidCollectionIsPartOfRange Method
This member is not intended to be used directly from your code.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected override bool IsPartOfRange(
    int index
)
Protected Overrides Function IsPartOfRange (
    index As Integer
) As Boolean

Parameters

index
Type: SystemInt32
Index.

Return Value

Type: Boolean
Boolean value.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.Parse Method

UidCollectionParse Method
Creates a new UidCollection from the specified UID sequence.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static UidCollection Parse(
    string uidString
)
Public Shared Function Parse (
    uidString As String
) As UidCollection

Parameters

uidString
Type: SystemString
The UID sequence string in IMAP4 format.

Return Value

Type: UidCollection
A reference to the UidCollection object representing the specified UID sequence, or a null reference (Nothing in Visual Basic) if the UID sequence could not be parsed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | uidString is a null reference (Nothing in Visual Basic).
Remarks
The uidString must conform to the rules described in AddSet(String) method remarks.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.ToArray Method

UidCollectionToArray Method
Gets all the items in the collection as an array.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long[] ToArray()
Public Function ToArray As Long()

Return Value

Type: Int64
The array containing all the UIDs in the collection.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection Properties

UidCollection Properties

The UidCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the UID at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidCollection.Item Property

UidCollectionItem Property
Gets the UID at the specified zero-based index in the collection.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Long
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the UID in the collection.

Property Value

Type: Int64
A Int64 value having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

UidCollection Class
MailBee.ImapMail Namespace


UidPlusResult Class

UidPlusResult Class
Represents a set of UIDs assigned to the copied or uploaded messages and other related information returned by the IMAP4 server which supports UIDPLUS extension.
Inheritance Hierarchy
SystemObject
MailBee.ImapMailUidPlusResult

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class UidPlusResult
Public Class UidPlusResult

The UidPlusResult type exposes the following members.

Constructors
 | Name | Description
Public method | UidPlusResult | Initializes a new instance of the UidPlusResult class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DestUids | Gets the UID collection of the messages been uploaded/copied/moved into the target folder.
Public property | DestUidString | Gets the UID sequence of the messages been uploaded/copied/moved into the target folder.
Public property | DestUidValidity | Gets the UIDVALIDITY of the folder the messages have been uploaded/copied/moved into.
Public property | IsSupported | Gets whether UIDPLUS is supported by the server.
Public property | IsValid | Gets whether UIDPLUS info in the response data is valid.
Public property | SrcUids | Gets the UID collection of the messages being copied/moved from the current folder.
Public property | SrcUidString | Gets the UID sequence of the messages being copied/moved from the current folder.
Top
Remarks

If the server supports UIDPLUS extension (RFC2359), this allows the client (MailBee) to obtain the information about UIDs of uploaded, copied, or moved messages, which may be useful if the application needs to save this information somewhere (usually, in a database). In this case, the developer can pass a reference to the UidPlusResult object instance to the corresponding method of Imap class (such as UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult)), call the method, and then examine the UidPlusResult object properties.

If, however, the server does not support UIDPLUS, the application may fall back to using UIDNEXT value to learn UID to be assigned to any new message in the folder. See the sample code and remarks in UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) topic for details.

See Also

Reference

MailBee.ImapMail Namespace
ImapGetExtension(String)
ImapUploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult)
ImapCopyMessages(String, Boolean, String, UidPlusResult)
ImapMoveMessages(String, Boolean, String, UidPlusResult)


UidPlusResult Constructor

UidPlusResult Constructor
Initializes a new instance of the UidPlusResult class

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public UidPlusResult()
Public Sub New
See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult Methods

UidPlusResult Methods

The UidPlusResult type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult Properties

UidPlusResult Properties

The UidPlusResult type exposes the following members.

Properties
 | Name | Description
Public property | DestUids | Gets the UID collection of the messages been uploaded/copied/moved into the target folder.
Public property | DestUidString | Gets the UID sequence of the messages been uploaded/copied/moved into the target folder.
Public property | DestUidValidity | Gets the UIDVALIDITY of the folder the messages have been uploaded/copied/moved into.
Public property | IsSupported | Gets whether UIDPLUS is supported by the server.
Public property | IsValid | Gets whether UIDPLUS info in the response data is valid.
Public property | SrcUids | Gets the UID collection of the messages being copied/moved from the current folder.
Public property | SrcUidString | Gets the UID sequence of the messages being copied/moved from the current folder.
Top
See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult.DestUids Property

UidPlusResultDestUids Property
Gets the UID collection of the messages been uploaded/copied/moved into the target folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public UidCollection DestUids { get; }
Public ReadOnly Property DestUids As UidCollection
    Get

Property Value

Type: UidCollection
The collection of UIDs of the messages been copied/moved into the target folder, or a null reference (Nothing in Visual Basic) if UIDPLUS extension is not supported or the messages were not copied or moved.
Remarks

After copying or moving messages, this property contains the UIDs of the messages copied/moved into the destination folder. For instance, if the messages with UIDs 567 and 680 were moved from "Inbox" folder into "Sent" folder and were assigned UID 13 and 14 in "Sent" folder, this property will return the collection containing UIDs 13 and 14.

UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method initializes this collection with the UID assigned to the uploaded message (or null if UIDPLUS is not supported by the server).

See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult.DestUidString Property

UidPlusResultDestUidString Property
Gets the UID sequence of the messages been uploaded/copied/moved into the target folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DestUidString { get; }
Public ReadOnly Property DestUidString As String
    Get

Property Value

Type: String
The string containing the UID sequence of the messages been copied/moved into the target folder, or a null reference (Nothing in Visual Basic) if UIDPLUS extension is not supported or the messages were not copied or moved.
Remarks

After copying or moving messages, this property contains the UID sequence of the messages copied/moved into the destination folder. For instance, if the message with UID 567 was copied from "Inbox" folder into "Sent" folder and was assigned UID 13 in "Sent" folder, this property will return "13".

UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method sets this property to the UID assigned to the uploaded message (or null if UIDPLUS is not supported by the server).

See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult.DestUidValidity Property

UidPlusResultDestUidValidity Property
Gets the UIDVALIDITY of the folder the messages have been uploaded/copied/moved into.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long DestUidValidity { get; }
Public ReadOnly Property DestUidValidity As Long
    Get

Property Value

Type: Int64
The new UIDVALIDITY value of the target folder after completion of uploading/copying/moving messages into this folder, or -1 if UIDPLUS is not supported by the server.
Remarks
For more information regarding UIDVALIDITY, see UidValidity topic.
See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace
ImapUidValidity


UidPlusResult.IsSupported Property

UidPlusResultIsSupported Property
Gets whether UIDPLUS is supported by the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSupported { get; }
Public ReadOnly Property IsSupported As Boolean
    Get

Property Value

Type: Boolean
true if UIDPLUS capability is supported; otherwise, false.
Remarks
The value of this property is set during calling the Imap class method this UidPlusResult object has been passed to.
See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult.IsValid Property

UidPlusResultIsValid Property
Gets whether UIDPLUS info in the response data is valid.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsValid { get; }
Public ReadOnly Property IsValid As Boolean
    Get

Property Value

Type: Boolean
true if UIDPLUS data is valid; otherwise, false.
Remarks
The value of this property is set during calling the Imap class method this UidPlusResult object has been passed to. If it's false, most other values are not set. This may occur if:
  • The UidPlusResult instance has just been created (not yet passed to any method which sets its values).
  • The copy/move operation affected zero messages.
  • The server does not support UIDPLUS or claims to support UIDPLUS but incorrectly sets its info in the response.
See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult.SrcUids Property

UidPlusResultSrcUids Property
Gets the UID collection of the messages being copied/moved from the current folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public UidCollection SrcUids { get; }
Public ReadOnly Property SrcUids As UidCollection
    Get

Property Value

Type: UidCollection
The collection of UIDs of the messages being copied/moved from the current folder, or a null reference (Nothing in Visual Basic) if UIDPLUS extension is not supported or the messages were not copied or moved.
Remarks

After copying or moving messages, this property contains the UIDs of the copied/moved messages in the source folder (which is the currently selected folder). For instance, if the messages with UIDs 567 and 680 were moved from "Inbox" folder into "Sent" folder and were assigned UID 13 and 14 in "Sent" folder, this property will return the collection containing UIDs 567 and 680.

UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method sets this property to null.

See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


UidPlusResult.SrcUidString Property

UidPlusResultSrcUidString Property
Gets the UID sequence of the messages being copied/moved from the current folder.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SrcUidString { get; }
Public ReadOnly Property SrcUidString As String
    Get

Property Value

Type: String
The string containing the UID sequence of the messages being copied/moved from the current folder, or a null reference (Nothing in Visual Basic) if UIDPLUS extension is not supported or the messages were not copied or moved.
Remarks

After copying or moving messages, this property contains the UID sequence of the copied/moved messages in the source folder (which is the currently selected folder). For instance, if the message with UID 567 was copied from "Inbox" folder into "Sent" folder and was assigned UID 13 in "Sent" folder, this property will return "567".

UploadMessage(MailMessage, String, String, String, Boolean, UidPlusResult) method sets this property to null.

See Also

Reference

UidPlusResult Class
MailBee.ImapMail Namespace


MailBee.Mime Namespace

MailBee.Mime Namespace
MailBee.Mime namespace provides classes and enumerations which can be used by your applications and by MailBee components (such as SmtpMail.Smtp and Pop3Mail.Pop3) for the following major tasks:
  • Automatically parse mail messages in MIME format into a set of easy-to-use properties and collections
  • Prepare mail messages for display in different containers such as browser or textbox control (including coloring quotations, highlighting links, processing embedded and external images, and more)
  • Compose new messages and automatically convert them into MIME format
  • Perform mail merge
  • Modify existing messages (including forwarding an existing message as attachment of a new message)
  • Load and save mail messages and individual parts from/into disk files, streams, strings, arrays
  • With the help of MailBee.Security.Smime class (licensed separately), MailBee.NET can also encrypt/decrypt e-mails, verify signatures, etc
MIME format (RFC2822) is the standard format for storing and transmitting mail messages in the Internet. Also, mail messages saved in this format (.EML files) are understood by most mail reader programs (including Microsoft Outlook Express).
Classes
 | Class | Description
 | Attachment | Provides properties and methods for constructing or examining a single attachment to the mail message.
 | AttachmentCollection | Provides properties and methods for managing and examining the collection of Attachment objects.
 | EmailAddress | Provides properties and methods used to parse, examine and construct a single e-mail address.
 | EmailAddressCollection | Provides properties and methods for managing and examining the collection of the EmailAddress objects.
 | Header | Provides properties for examining or setting the name or the value of a single field of the headers section of a MIME part.
 | HeaderCollection | Represents a collection of all the headers of a mail message or a MIME part.
 | MailMerge | Provides properties and methods for creating customized messages based on a template.
 | MailMessage | Provides properties and methods for constructing and examining a single e-mail message.
 | MailMessageCollection | Provides properties and methods for managing and examining the collection of MailMessage objects.
 | MessageBuilderConfig | Provides properties and methods which affect how the mail message is being built from the MailMessage object properties and collections into the message raw data (in MIME format).
 | MessageParserConfig | Provides properties and methods which affect how the mail message is being parsed from the raw data (MIME source) into the MailMessage object properties and collections.
 | MimePart | Represents a MIME part of the message.
 | MimePartCollection | Provides properties and methods for examining the collection of MimePart objects.
Public class | StringConversionConfig | Provides properties the developer can use to affect how the values of string properties of MailMessage and dependent objects should be charset-converted when being returned to the application.
 | TextBodyPart | Represents a text body of the message.
 | TextBodyPartCollection | Provides properties and methods for managing and examining the collection of TextBodyPart objects.
 | TimeStamp | Provides properties and methods for examining a time stamp representing a moment when the message was received by a mail gateway or a mail server.
 | TimeStampCollection | Provides properties and methods for examining the collection of TimeStamp objects.
Delegates
 | Delegate | Description
Public delegate | ReplaceUriWithCidHandler | Defines the signature of a method supplied by the application in order to decide whether a particular URI in the HTML being imported must be replaced with a CID and the corresponding resource be attached to the message.
Enumerations
 | Enumeration | Description
Public enumeration | AddressDelimeterChar | Defines the available characters for delimiting e-mail addresses when building an e-mail address string.
Public enumeration | AHRefTagAttributes | Defines the available attributes of <A HREF> tags contained in HTML message body which can be affected by cleanup process during parsing the message.
Public enumeration | CharsetMetaTagProcessing | Defines the available modes which affect processing of META tags during parsing HTML body of the message.
Public enumeration | HeaderEncodingOptions | Defines the available options which affect how message headers are encoded with mail transfer encodings such as Base64 or Quoted-Printable.
Public enumeration | HtmlMessageAutoSaving | Defines the available modes for automatic saving of the HTML body or related files of the message into WorkingFolder location during parsing the message.
Public enumeration | HtmlToPlainAutoConvert | Defines the available modes which specify when HTML body of a message should automatically be converted into plain text during parsing of this message.
Public enumeration | HtmlToPlainConvertOptions | Defines the available flags which affect how HTML body of a message is converted into plain text.
 | HtmlToSimpleHtmlAutoConvert | Defines the available modes which specify if HTML body of a message should be converted into simple HTML.
Public enumeration | HtmlToSimpleHtmlConvertOptions | Defines the available flags which affect how HTML body of a message should be converted into simple HTML.
Public enumeration | ImportBodyOptions | Defines the available flags for importing the body of the mail message from a file or URI via LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method.
Public enumeration | ImportRelatedFilesOptions | Defines the available flags which affect how files related to the HTML body of the mail message are attached to the message by ImportRelatedFiles(ImportRelatedFilesOptions) method.
Public enumeration | MailMergeTargets | Defines mail message elements where patterns should be searched and replaced with actual values during mail merge operation.
Public enumeration | MailPriority | Defines the available values for MailMessage.Priority property.
Public enumeration | MailSensitivity | Defines the available values for MailMessage.Sensitivity property.
Public enumeration | MailTransferEncoding | Defines the available values for the properties specifying mail transfer encoding for text parts or attachments of the message.
Public enumeration | MessageBodyType | Defines the available types of the mail message body being loaded with LoadBodyText(String, MessageBodyType) method.
Public enumeration | MessageElements | Defines a set of flags which specify message elements to be cleared by MailMessage.Clear method call.
Public enumeration | MessageFolderBehavior | Defines the available modes of maintaining the unique message folder associated with the mail message.
Public enumeration | MimePartType | Defines the available categories of MIME parts.
Public enumeration | NewAttachmentOptions | Defines the available flags affecting how a new Attachment object will be created by Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) method and its overloads which accept options parameter.
Public enumeration | PlainToHtmlAutoConvert | Defines modes which specify the condition which triggers automatic conversion of the plain-text body into HTML during parsing the message.
Public enumeration | PlainToHtmlConvertOptions | Defines the available flags affecting conversion of the plain-text body into HTML during parsing the message.
Public enumeration | StringConversionMode | Defines the modes which specify if (and how) the values of string properties of MailMessage and dependent objects should be charset-converted when being returned to the application.
Public enumeration | TnefExtractionOptions | Defines the available flags affecting which items to extract from a TNEF container (winmail.dat).
Public enumeration | VirtualMappingType | Defines the available modes which specify how the virtual paths should be generated by GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method for inline attachments referenced in HTML body.


AddressDelimeterChar Enumeration

AddressDelimeterChar Enumeration
Defines the available characters for delimiting e-mail addresses when building an e-mail address string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum AddressDelimeterChar
Public Enumeration AddressDelimeterChar
Members
Member name | Value | Description
Comma | 0 | Use comma character (",").
Semicolon | 1 | Use semicolon character (";").
Remarks

When building an e-mail address string containing multiple addresses (such as To, CC, BCC fields), MailBee can delimit individual addresses with either comma or semicolon. This can be set via MailMessage.Builder.AddressDelimeter property.

Still, it's recommended to leave the default value (comma) since using semicolon violates MIME standard and some mail clients might not be able to correctly parse messages containing semicolon-delimited e-mail addresses.

Note Note
When parsing (rather than building) e-mail address string, MailBee recognizes both comma and semicolon as delimiters.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser


AHRefTagAttributes Enumeration

AHRefTagAttributes Enumeration
Defines the available attributes of <A HREF> tags contained in HTML message body which can be affected by cleanup process during parsing the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum AHRefTagAttributes
<FlagsAttribute>
Public Enumeration AHRefTagAttributes
Members
Member name | Value | Description
None | 0 | No attributes will be affected.
Target | 1 | The target attribute will be affected.
ClassAndStyle | 2 | The class and style attributes will be affected.
Onclick | 4 | The onclick attribute will be affected.
Remarks

In order to display an HTML body of a message in the browser, it's a common practice to process links in a certain way. For instance, the developer may wish to apply specific styles or attributes to each <A HREF> tag (such as add target=_blank attribute to make links open in a new window). The existing attributes need to be deleted in this case (otherwise, they would interfere with the new ones).

To specify which attributes of <A HREF> tags must be deleted during parsing the message, the developer should set MailMessage.Parser.AHRefCleanup property.

To specify which attributes need to be added to <A HREF> tags, the developer should set MailMessage.Parser.AHRefSuffix property.

Note Note
More advanced processing of HTML documents is supported by MailBee.Html classes.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigAHRefCleanup
MessageParserConfigAHRefSuffix


Attachment Class

Attachment Class
Provides properties and methods for constructing or examining a single attachment to the mail message.
Inheritance Hierarchy
SystemObject
MailBee.MimeAttachment

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Attachment
Public Class Attachment

The Attachment type exposes the following members.

Constructors
Name | Description
Attachment | Creates a new instance of Attachment object from the specified MimePart object.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAttachmentsFromTnef | Extracts all the files from TNEF container and returns them as AttachmentCollection.
 | GetAttachmentsFromTnef(TnefExtractionOptions) | Extracts items of the specified kinds from TNEF container and returns them as AttachmentCollection.
 | GetData | Gets the actual content of the attachment as a byte array.
 | GetData(Int32, Int32) | Gets the specified portion of the actual content of the attachment as a byte array.
 | GetEncapsulatedMessage | Gets the encapsulated e-mail message as a MailMessage object.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Save | Saves the content of the attachment into the specified file.
Public method | SaveAsync | async/await version of Save(String, Boolean).
 | SaveToFolder | Saves the content of the attachment into a file in the specified folder.
Public method | SaveToFolderAsync | async/await version of SaveToFolder(String, Boolean).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
AsMimePart | Gets the attachment as MimePart object.
ContentID | Gets the Content-ID value of the attachment.
ContentLocation | Gets the content location of the attachment.
ContentType | Gets the content type of the attachment.
Description | Gets the description of the attachment.
Filename | Gets the filename of the attachment.
FilenameOriginal | Gets the original filename of the attachment.
Headers | Gets the collection of the attachment headers.
IsFile | Indicates if the attachment is a file.
IsInline | Indicates if the attachment is inline.
IsMessageInside | Indicates if the attachment contains a mail message.
IsTnef | Indicates if the attachment is MS-TNEF (winmail.dat) container which can have other attachments inside.
IsVCard | Indicates if the attachment is a vCard profile.
IsZip | Indicates if the attachment is a zip archive.
LastResult | Gets a numeric code of the last error.
Name | Gets the friendly name of the attachment.
RawHeader | Gets a string containing the header section of the attachment in the original form.
SavedAs | Gets the full path to the attachment which was saved to disk.
Size | Gets the length of the binary content of the attachment.
ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks

All the attachments to the message (including embedded pictures) are stored in Attachments collection of the MailMessage object.

You can also create MDN attachments (deliver-status reports). See Add(String, String, HeaderCollection, MailTransferEncoding) for details.

Examples
This sample loads the message from .EML file and displays filenames of all attachments to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the filename of the attachment.
    Console.WriteLine("Attachment name is " + attach.Filename);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the filename of the attachment.
    Console.WriteLine("Attachment name is " & attach.Filename)
Next
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeAttachmentCollection


Attachment Constructor

Attachment Constructor
Creates a new instance of Attachment object from the specified MimePart object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Attachment(
    MimePart src
)
Public Sub New (
    src As MimePart
)

Parameters

src
Type: MailBee.MimeMimePart
The MimePart object from which to create the attachment.
Examples
The example is available in GetEnvelopeItem(String, Boolean) method documentation.
See Also

Reference

Attachment Class
MailBee.Mime Namespace
MailBee.MimeMimePart


Attachment Methods

Attachment Methods

The Attachment type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAttachmentsFromTnef | Extracts all the files from TNEF container and returns them as AttachmentCollection.
 | GetAttachmentsFromTnef(TnefExtractionOptions) | Extracts items of the specified kinds from TNEF container and returns them as AttachmentCollection.
 | GetData | Gets the actual content of the attachment as a byte array.
 | GetData(Int32, Int32) | Gets the specified portion of the actual content of the attachment as a byte array.
 | GetEncapsulatedMessage | Gets the encapsulated e-mail message as a MailMessage object.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Save | Saves the content of the attachment into the specified file.
Public method | SaveAsync | async/await version of Save(String, Boolean).
 | SaveToFolder | Saves the content of the attachment into a file in the specified folder.
Public method | SaveToFolderAsync | async/await version of SaveToFolder(String, Boolean).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.GetAttachmentsFromTnef Method

AttachmentGetAttachmentsFromTnef Method
Extracts all the files and optionally the RTF message body from TNEF container and returns the result as AttachmentCollection.
Overload List
Name | Description
GetAttachmentsFromTnef | Extracts all the files from TNEF container and returns them as AttachmentCollection.
GetAttachmentsFromTnef(TnefExtractionOptions) | Extracts items of the specified kinds from TNEF container and returns them as AttachmentCollection.
Top
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.GetAttachmentsFromTnef Method

AttachmentGetAttachmentsFromTnef Method
Extracts all the files from TNEF container and returns them as AttachmentCollection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AttachmentCollection GetAttachmentsFromTnef()
Public Function GetAttachmentsFromTnef As AttachmentCollection

Return Value

Type: AttachmentCollection
An AttachmentCollection object representing the collection of attachments extracted from TNEF, or a null reference (Nothing in Visual Basic) if the attachment is not a valid TNEF container.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Prior to calling this method, check IsTnef property value to determine whether the attachment is TNEF or not.

This overload does not extract RFT message body from TNEF. Use GetAttachmentsFromTnef(TnefExtractionOptions) overload for that.

If winmail.dat contains nested winmail.dat files, they will be decoded as well as "message/rfc822" attachments. To process them, check IsMessageInside property and GetEncapsulatedMessage method to get internal MailMessage object. For that object, you can then iterate through Attachments collection to get its contents. You no longer need to call GetAttachmentsFromTnef for nested objects. Single GetAttachmentsFromTnef call extracts contents from all winmail.dat files on all levels.

Examples
The example is available in IsTnef topic. Advanced examples are available in GetAttachmentsFromTnef(TnefExtractionOptions) and TnefParser topics.
See Also

Reference

Attachment Class
GetAttachmentsFromTnef Overload
MailBee.Mime Namespace
AttachmentIsTnef


Attachment.GetAttachmentsFromTnef Method (TnefExtractionOptions)

AttachmentGetAttachmentsFromTnef Method (TnefExtractionOptions)
Extracts items of the specified kinds from TNEF container and returns them as AttachmentCollection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AttachmentCollection GetAttachmentsFromTnef(
    TnefExtractionOptions options
)
Public Function GetAttachmentsFromTnef (
    options As TnefExtractionOptions
) As AttachmentCollection

Parameters

options
Type: MailBee.MimeTnefExtractionOptions
Specifies which kinds of items (attachments and/or RTF message body) to extract from TNEF.

Return Value

Type: AttachmentCollection
An AttachmentCollection object representing the collection of the requested items extracted from TNEF, or a null reference (Nothing in Visual Basic) if the attachment is not a valid TNEF container.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Prior to calling this method, check IsTnef property value to determine whether the attachment is TNEF or not.

If winmail.dat contains nested winmail.dat files, they will be decoded as well as "message/rfc822" attachments. To process them, check IsMessageInside property and GetEncapsulatedMessage method to get internal MailMessage object. For that object, you can then iterate through Attachments collection to get its contents. You no longer need to call GetAttachmentsFromTnef for nested objects. Single GetAttachmentsFromTnef call extracts contents from all winmail.dat files on all levels. See TnefParser topic for example (it, however, extracts data from a standalone winmail.dat file but it's all the same for a winmail.dat attachment to an e-mail).

Examples
This example downloads the last e-mail in IMAP inbox, extracts all attachments and RTF body from the TNEF (if any), saves the attachments to disk and displays the contents of the RTF body in the console.
C#
VB
Copy
using System;
using System.Collections;
using System.Text;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Connect to the server, login and select inbox.
        imp.Connect("imap.domain.com");
        imp.Login("user", "password");
        imp.SelectFolder("INBOX");

        // Download the last e-mail in the inbox.
        // We assume that e-mail includes winmail.dat attachment.
        MailMessage msg = imp.DownloadEntireMessage(imp.MessageCount, false);

        bool tnefFound = false;
        bool rtfFound = false;

        foreach (Attachment attach in msg.Attachments)
        {
            // Check if it's MS-TNEF (e.g. winmail.dat).
            if (attach.IsTnef)
            {
                tnefFound = true;

                // Extract all the attachments and RTF body.
                AttachmentCollection tnefItems = attach.GetAttachmentsFromTnef(
                    TnefExtractionOptions.ExtractAttachments | TnefExtractionOptions.ExtractRtfBody);

                // If RTF body exists, it's the last item in the collection with name "richbody.rtf".
                if (tnefItems.Count > 0 && tnefItems[tnefItems.Count - 1].Filename == "richbody.rtf")
                {
                    rtfFound = true;
                    Attachment rtfBody = tnefItems[tnefItems.Count - 1];

                    // Print the RTF contents to the console.
                    Console.WriteLine(Global.DefaultEncoding.GetString(rtfBody.GetData()));

                    // Remove the RTF from the collection. But if you wish to have the RTF body saved
                    // with all the attachments, comment this line out.
                    tnefItems.RemoveAt(tnefItems.Count - 1);
                }

                // Save everything in a folder. If you commented out the removal of RTF (see above),
                // RTF will be saved as well, with "richbody.rtf" filename.
                tnefItems.SaveAll(@"C:\Temp");
                Console.WriteLine();
                Console.WriteLine(tnefItems.Count.ToString() + " item(s) saved");
            }
        }

        if (!tnefFound)
        {
            Console.WriteLine("No TNEF found");
        }
        else if (!rtfFound)
        {
            Console.WriteLine("No RTF found in TNEF");
        }

        imp.Disconnect();
    }
}
Imports System
Imports System.Collections
Imports System.Text
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.Mime

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim imp As Imap = New Imap

        ' Connect to the server, login and select inbox.
        imp.Connect("imap.domain.com")
        imp.Login("user", "password")
        imp.SelectFolder("INBOX")

        ' Download the last e-mail in the inbox.
        ' We assume that e-mail includes winmail.dat attachment.
        Dim msg As MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)

        Dim tnefFound As Boolean = False
        Dim rtfFound As Boolean = False

        Dim attach As Attachment
        For Each attach In msg.Attachments
            ' Check if it's MS-TNEF (e.g. winmail.dat).
            If attach.IsTnef Then
                tnefFound = True

                ' Extract all the attachments and RTF body.
                Dim tnefItems As AttachmentCollection = attach.GetAttachmentsFromTnef( _
                 TnefExtractionOptions.ExtractAttachments + TnefExtractionOptions.ExtractRtfBody)

                ' If RTF body exists, it's the last item in the collection with name "richbody.rtf".
                If (tnefItems.Count > 0 AndAlso tnefItems(tnefItems.Count - 1).Filename = "richbody.rtf") Then
                    rtfFound = True
                    Dim rtfBody As Attachment = tnefItems(tnefItems.Count - 1)

                    ' Print the RTF contents to the console.
                    Console.WriteLine(Global.DefaultEncoding.GetString(rtfBody.GetData()))

                    ' Remove the RTF from the collection. But if you wish to have the RTF body saved
                    ' with all the attachments, comment this line out.
                    tnefItems.RemoveAt(tnefItems.Count - 1)
                End If

                ' Save everything in a folder. If you commented out the removal of RTF (see above),
                ' RTF will be saved as well, with "richbody.rtf" filename.
                tnefItems.SaveAll("C:\Temp")
                Console.WriteLine()
                Console.WriteLine(tnefItems.Count.ToString() + " item(s) saved")
            End If
        Next

        If (Not tnefFound) Then
            Console.WriteLine("No TNEF found")
        ElseIf (Not rtfFound) Then
            Console.WriteLine("No RTF found in TNEF")
        End If

        imp.Disconnect()
    End Sub
End Class
See Also

Reference

Attachment Class
GetAttachmentsFromTnef Overload
MailBee.Mime Namespace
AttachmentIsTnef


Attachment.GetData Method

AttachmentGetData Method
Overload List
Name | Description
GetData | Gets the actual content of the attachment as a byte array.
GetData(Int32, Int32) | Gets the specified portion of the actual content of the attachment as a byte array.
Top
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.GetData Method

AttachmentGetData Method
Gets the actual content of the attachment as a byte array.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] GetData()
Public Function GetData As Byte()

Return Value

Type: Byte
A byte array containing the actual content of the attachment.
Remarks
To get a certain portion of the attachment's content (rather than the entire data), use GetData(Int32, Int32) overload.
Examples
This sample loads the message from .EML file and saves the first attachment to disk using GetData method and streams.
Note Note
In real-world apps, it's easier to use Save(String, Boolean) or SaveToFolder(String, Boolean) methods to save an attachment to disk.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// When there is any attachment...
if (msg.Attachments.Count > 0)
{
    // ...then open a file for writing...
    using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(@"C:\Temp\" + msg.Attachments[0].Filename)))
    {
        // ...and write the attachment's content to the file.
        bw.Write(msg.Attachments[0].GetData());
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' When there is any attachment...
If msg.Attachments.Count > 0 Then
    ' ...then open a file for writing...
    Dim bw As BinaryWriter
    Try
        bw = New BinaryWriter(File.OpenWrite("C:\Temp\" & msg.Attachments(0).Filename))

        ' ...and write the attachment's content to the file.
        bw.Write(msg.Attachments(0).GetData())
    Finally
        If Not bw Is Nothing Then
            bw.Close()
        End If
    End Try
End If
See Also

Reference

Attachment Class
GetData Overload
MailBee.Mime Namespace
AttachmentSave(String, Boolean)
AttachmentSize


Attachment.GetData Method (Int32, Int32)

AttachmentGetData Method (Int32, Int32)
Gets the specified portion of the actual content of the attachment as a byte array.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] GetData(
    int offset,
    int size
)
Public Function GetData (
    offset As Integer,
    size As Integer
) As Byte()

Parameters

offset
Type: SystemInt32
The number of bytes which should be skipped before starting reading the attachment content.
size
Type: SystemInt32
The number of bytes which should be read. If -1, the content will be read from the offset position till the end of the data.

Return Value

Type: Byte
The specified portion of the actual content of the attachment as a byte array.
Examples
This sample loads the message from .EML file and saves the first attachment to disk using BinaryWriter object.
Note Note
In real-world apps, it's easier to use Save(String, Boolean) or SaveToFolder(String, Boolean) methods to save an attachment to disk.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// When there is any attachment...
if (msg.Attachments.Count > 0)
{
    // ...open a file for writing...
    using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(@"C:\Temp\" + msg.Attachments[0].Filename)))
    {
        // ...and write the attachment content to the file.
        bw.Write(msg.Attachments[0].GetData(0, -1));
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' When there is any attachment...
If msg.Attachments.Count > 0 Then
    ' ...open a file for writing...
    Dim bw As BinaryWriter
    Try
        bw = New BinaryWriter(System.IO.File.OpenWrite("C:\Temp\" & msg.Attachments(0).Filename))

        ' ...and write the attachment content to the file.
        bw.Write(msg.Attachments(0).GetData(0, -1))
    Finally
        If Not bw Is Nothing Then
            bw.Close()
        End If
    End Try
End If
See Also

Reference

Attachment Class
GetData Overload
MailBee.Mime Namespace
AttachmentSave(String, Boolean)
AttachmentSize


Attachment.GetEncapsulatedMessage Method

AttachmentGetEncapsulatedMessage Method
Gets the encapsulated e-mail message as a MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage GetEncapsulatedMessage()
Public Function GetEncapsulatedMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object containing the encapsulated e-mail message, or a null reference (Nothing in Visual Basic) if the attachment is not an e-mail message.
Remarks
This method extracts the encapsulated e-mail message from the attachment content, and represents it as a MailMessage object for any further use. The extracted message can then be easily examined, resent, replied, saved to disk, or processed in any other way.
Note Note
To detect if the attachment is an e-mail message, the developer can use IsMessageInside property.
Examples
This sample loads the message from .EML file, extracts the encapsulated message, and displays all headers of the encapsulated message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

MailMessage attachedMsg = null;

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...get the inner e-mail from the attachment.
    attachedMsg = attach.GetEncapsulatedMessage();

    // When there is any inner e-mail...
    if (attachedMsg != null)
    {
        // ...show the header section of that e-mail.
        Console.WriteLine(attachedMsg.RawHeader);
        Console.WriteLine();
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

Dim attachedMsg As MailMessage = Nothing

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...get the inner e-mail from the attachment.
    attachedMsg = attach.GetEncapsulatedMessage()

    ' When there is any inner e-mail...
    If Not attachedMsg Is Nothing Then
        ' ...show the header section of that e-mail.
        Console.WriteLine(attachedMsg.RawHeader)
        Console.WriteLine()
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
MailBee.MimeMailMessage
AttachmentIsMessageInside


Attachment.Save Method

AttachmentSave Method
Saves the content of the attachment into the specified file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Save(
    string filename,
    bool overwrite
)
Public Function Save (
    filename As String,
    overwrite As Boolean
) As Boolean

Parameters

filename
Type: SystemString
The absolute or relative path under which to save the attachment.
overwrite
Type: SystemBoolean
Denotes if the file must be overwritten if it already exists.

Return Value

Type: Boolean
true if the attachment was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks
The developer can use SaveToFolder(String, Boolean) method to save the attachment into specified folder under the actual filename of the attachment.
Note Note
If overwrite is false and the file with the same filename already exists, the attachment will be saved under another name. For instance, if cat.gif is being saved and such file already exists, it will be actually saved as cat[1].gif. The developer can use SavedAs property to obtain the filename of the saved file.
Examples
This sample loads the message from .EML file and saves all the attachments to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...save it to disk.
    attach.Save(@"C:\Temp\" + attach.Filename, true);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...save it to disk.
    attach.Save("C:\Temp\" & attach.Filename, True)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentSaveToFolder(String, Boolean)


Attachment.SaveAsync Method

AttachmentSaveAsync Method
async/await version of Save(String, Boolean).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveAsync(
    string filename,
    bool overwrite
)
Public Function SaveAsync (
    filename As String,
    overwrite As Boolean
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The absolute or relative path under which to save the attachment.
overwrite
Type: SystemBoolean
Denotes if the file must be overwritten if it already exists.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the attachment was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.SaveToFolder Method

AttachmentSaveToFolder Method
Saves the content of the attachment into a file in the specified folder.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveToFolder(
    string folderName,
    bool overwrite
)
Public Function SaveToFolder (
    folderName As String,
    overwrite As Boolean
) As Boolean

Parameters

folderName
Type: SystemString
The absolute or relative path to the folder where the attachment file should be saved.
overwrite
Type: SystemBoolean
Specifies if the file must be overwritten if it already exists.

Return Value

Type: Boolean
true if the attachment was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks
This method saves the attachment content to the folder under the actual filename of the attachment (which is taken from Filename property). To save the attachment under another filename, use the Save(String, Boolean) method.
Note Note
If overwrite is false and the file with the same filename already exists, the attachment will be saved under another name. For instance, if cat.gif is being saved and such file already exists, it will be actually saved as cat[1].gif. The developer can use SavedAs property to obtain the filename of the saved file.
Examples
This sample downloads the message from POP3 account and saves all the message attachments into the specified folder. ,
Note Note
SaveToFolder(String, Boolean) method is used for demonstration purposes only. Real-world applications can use the SaveAll(String) method to save all the message attachments into the specified folder with a single method call.
C#
VB
Copy
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Quickly download the first message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "jdoe", "password", 1);

        // For every attachment...
        foreach (Attachment attach in msg.Attachments)
        {
            // ...save it into the specified folder.
            attach.SaveToFolder(@"C:\Temp\", true);
        }
    }
}
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Quickly download the first message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "jdoe", "password", 1)

        ' For every attachment...
        For Each attach As Attachment In msg.Attachments
            ' ...save it into the specified folder.
            attach.SaveToFolder("C:\Temp\", True)
        Next
    End Sub
End Module
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentSave(String, Boolean)


Attachment.SaveToFolderAsync Method

AttachmentSaveToFolderAsync Method
async/await version of SaveToFolder(String, Boolean).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveToFolderAsync(
    string folderName,
    bool overwrite
)
Public Function SaveToFolderAsync (
    folderName As String,
    overwrite As Boolean
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The absolute or relative path to the folder where the attachment file should be saved.
overwrite
Type: SystemBoolean
Specifies if the file must be overwritten if it already exists.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the attachment was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment Properties

Attachment Properties

The Attachment type exposes the following members.

Properties
Name | Description
AsMimePart | Gets the attachment as MimePart object.
ContentID | Gets the Content-ID value of the attachment.
ContentLocation | Gets the content location of the attachment.
ContentType | Gets the content type of the attachment.
Description | Gets the description of the attachment.
Filename | Gets the filename of the attachment.
FilenameOriginal | Gets the original filename of the attachment.
Headers | Gets the collection of the attachment headers.
IsFile | Indicates if the attachment is a file.
IsInline | Indicates if the attachment is inline.
IsMessageInside | Indicates if the attachment contains a mail message.
IsTnef | Indicates if the attachment is MS-TNEF (winmail.dat) container which can have other attachments inside.
IsVCard | Indicates if the attachment is a vCard profile.
IsZip | Indicates if the attachment is a zip archive.
LastResult | Gets a numeric code of the last error.
Name | Gets the friendly name of the attachment.
RawHeader | Gets a string containing the header section of the attachment in the original form.
SavedAs | Gets the full path to the attachment which was saved to disk.
Size | Gets the length of the binary content of the attachment.
ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.AsMimePart Property

AttachmentAsMimePart Property
Gets the attachment as MimePart object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePart AsMimePart { get; }
Public ReadOnly Property AsMimePart As MimePart
    Get

Property Value

Type: MimePart
A MimePart object representing the attachment of the mail message as a MIME part.
Remarks

MimePart corresponding to the given attachment provides access to those properties that are not available in Attachment but accessible in MimePart only.

To get the root part of the MIME parts tree of the message, use MimePartTree property of MailMessage object. MimePartTree MIME part contains all the MIME parts of the message.

Examples
This sample loads the message from .EML file and displays Content-Disposition of all attachments of this message. Content-Disposition value is not available in Attachment object but can be retrieved using MimePart object.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the filename and content-disposition of the attachment.
    Console.WriteLine("Attachment name: " + attach.Filename);
    Console.WriteLine("Disposition: " + attach.AsMimePart.Disposition);
    Console.WriteLine();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the filename and content-disposition of the attachment.
    Console.WriteLine("Attachment name: " & attach.Filename)
    Console.WriteLine("Disposition: " & attach.AsMimePart.Disposition)
    Console.WriteLine()
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.ContentID Property

AttachmentContentID Property
Gets the Content-ID value of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentID { get; }
Public ReadOnly Property ContentID As String
    Get

Property Value

Type: String
A string containing the Content-ID (CID) value of the attachment, or an empty string if the attachment has no Content-ID.
Remarks

Each attachment which is referenced in the message body (e.g. a picture in HTML body) usually has a Content-ID header which is used to reference this attachment from the message body.

For instance, if the HTML body contains <IMG SRC="cid:picture1">, it's expected there is an attached image with Content-ID picture1. This image must be displayed in place of <IMG SRC="cid:picture1"> tag when the HTML body is being rendered.

Note Note
MailBee.NET has special features for displaying HTML body with embedded pictures. See SaveHtmlAndRelatedFiles(String) and GetHtmlAndSaveRelatedFiles methods for more information.
Examples
This sample loads the message from .EML file and displays CIDs of each attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the attachment identifier.
    Console.WriteLine("CID is " + attach.ContentID);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the attachment identifier.
    Console.WriteLine("CID is " & attach.ContentID)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentContentLocation
AttachmentIsInline


Attachment.ContentLocation Property

AttachmentContentLocation Property
Gets the content location of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentLocation { get; }
Public ReadOnly Property ContentLocation As String
    Get

Property Value

Type: String
A string containing the attachment's content location taken from Content-Location header, or an empty string if Content-Location header is not set.
Remarks
ContentLocation, if present, is typically a URL to the resource (where resource is the attachment data). Some mail clients, however, place Content-ID value in ContentLocation. Thus, if Content-ID is expected and ContentID header is missing while ContentLocation is present, MailBee uses its value as Content-ID of the resource.
Examples
This sample loads the message from .EML file and displays content location of each attachment of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show attachment content location.
    Console.WriteLine("The location is " + attach.ContentLocation);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show attachment content location.
    Console.WriteLine("The location is " & attach.ContentLocation)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentContentID
AttachmentHeaders


Attachment.ContentType Property

AttachmentContentType Property
Gets the content type of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentType { get; }
Public ReadOnly Property ContentType As String
    Get

Property Value

Type: String
A string containing the attachment's content type taken from Content-Type header, or an empty string if the content type is not set.
Remarks
Some examples of attachment content types:
  • text/plain
  • text/html
  • text/calendar
  • multipart/related
  • multipart/alternative
  • multipart/mixed
  • application/x-zip-compressed
  • application/msword

When adding an attachment to the e-mail message (for instance, using Add(String) method of AttachmentCollection) and the content type is not specified, MailBee automatically determines its content type according to the file extension.

Examples
This sample loads the message from .EML file and displays the content type of each attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show attachment type.
    Console.WriteLine("The type is " + attach.ContentType);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show attachment type.
    Console.WriteLine("The type is " & attach.ContentType)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentHeaders


Attachment.Description Property

AttachmentDescription Property
Gets the description of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Description { get; }
Public ReadOnly Property Description As String
    Get

Property Value

Type: String
A string containing the attachment description taken from Content-Description header, or an empty string if Content-Description header is not set. The default value is an empty string.
Examples
This sample loads the message from .EML file and displays the content description of each attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the attachment description.
    Console.WriteLine("Description is " + attach.Description);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the attachment description.
    Console.WriteLine("Description is " & attach.Description)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentHeaders


Attachment.Filename Property

AttachmentFilename Property
Gets the filename of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; }
Public ReadOnly Property Filename As String
    Get

Property Value

Type: String
A string containing the filename of the attachment. The value is NEVER an empty string.
Remarks

Within the Attachments collection, every attachment has the unique Filename.

Filename property value is set accordingly the following considerations:

  • If filename parameter of Content-Disposition header is set, its value is passed to this property
  • If filename parameter of Content-Disposition header is missing, name parameter of Content-Type header is used
  • If the value obtained from the previous steps is an empty string, Subject of the message is used
  • If the value obtained from the previous steps is not a unique name (i.e. Attachments collection already contains another attachment with the same Filename), this value is extended with [i] where i is a unique number (1, 2, 3, etc). For instance, picture.gif becomes picture[2].gif if Attachments collection already contains picture.gif and picture[1].gif.

To get the real name of the attached file (as it appears in the e-mail message), use FilenameOriginal property.

Thus, Filename is usually equal to FilenameOriginal of the same attachment, but it may be different sometimes.

Other useful properties are Name (gets the friendly name of the attachment if available) and SavedAs (gets the full path to the file if the attachment was saved to disk).

Examples
This sample creates a new message, attaches 3 files, and displays the unique filename for each attached file. The sample demonstrates attaching files which will have the same filenames in the e-mail message (although their source locations are different). The message will have 1.jpg, 1.jpg and 2.jpg attachments (these will be their FilenameOriginal values) while their unqiue Filename values will be 1.jpg, 1[1].jpg and 2.jpg.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Attach some files.
msg.Attachments.Add(@"C:\Temp\My_Images\1.jpg", "1.jpg");
msg.Attachments.Add(@"C:\Temp\My_Images\2.jpg", "1.jpg");
msg.Attachments.Add(@"C:\Temp\Other_Images\1.jpg", "2.jpg");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the unique filename of the attachment.
    Console.WriteLine("Unique filename is " + attach.Filename);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Create a new MailMessage object.
Dim msg As New MailMessage

' Attach some files.
msg.Attachments.Add("C:\Temp\My_Images\1.jpg", "1.jpg")
msg.Attachments.Add("C:\Temp\My_Images\2.jpg", "1.jpg")
msg.Attachments.Add("C:\Temp\Other_Images\1.jpg", "2.jpg")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the unique filename of the attachment.
    Console.WriteLine("Unique filename is " & attach.Filename)
Next
Running the code above produces the following results:
Copy
1.jpg
1[1].jpg
2.jpg
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentName
AttachmentSavedAs
AttachmentFilenameOriginal


Attachment.FilenameOriginal Property

AttachmentFilenameOriginal Property
Gets the original filename of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string FilenameOriginal { get; }
Public ReadOnly Property FilenameOriginal As String
    Get

Property Value

Type: String
A string containing the original filename of the attachment.
Remarks

The value of this property is taken from filename parameter of Content-Disposition header.

If Content-Disposition header or filename parameter is missing, FilenameOriginal property will contain an empty string, while Filename property will be set to non-empty value (taken from other headers or autogenerated by MailBee).

The developer can use FilenameOriginal to get the real name of the attached file as it was specified in the e-mail. To get the unique filename of the attachment within the Attachments collection, use Filename property.

For instance, when two files with equal filenames cat.jpg are attached to the message, their original filenames will be cat.jpg for both the files, but their Filename values will be cat.jpg and cat[1].jpg.

Thus, Filename is usually equal to FilenameOriginal of the same attachment, but it may be different sometimes.
Examples
This sample loads the message from .EML file and displays the original filename of each attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the original filename of the attachment.
    Console.WriteLine("Filename is " + attach.FilenameOriginal);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the original filename of the attachment.
    Console.WriteLine("Filename is " & attach.FilenameOriginal)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentName
AttachmentFilename
AttachmentSavedAs


Attachment.Headers Property

AttachmentHeaders Property
Gets the collection of the attachment headers.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection Headers { get; }
Public ReadOnly Property Headers As HeaderCollection
    Get

Property Value

Type: HeaderCollection
A HeaderCollection object containing the headers of the attachment.
Remarks

This property allows the developer to access any headers of the attachment, add new headers, or modify/delete existing ones.

Use RawHeader property to get the header section of the attachment as a string.

Examples
This sample loads the message from .EML file and displays the headers of each attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the name of the attachment and iterate through its headers.
    Console.WriteLine("Headers of " + attach.Filename + " attachment:");

    // For every header...
    foreach (Header hdr in attach.Headers)
    {
        // ...show the header name and value.
        Console.WriteLine(hdr.Name + ": " + hdr.Value);
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the name of the attachment and iterate through its headers.
    Console.WriteLine("Headers of " & attach.Name & " attachment:")

    ' For every header...
    For Each hdr As Header In attach.Headers
        ' ...show the header name and value.
        Console.WriteLine(hdr.Name & ": " & hdr.Value)
    Next
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentRawHeader


Attachment.IsFile Property

AttachmentIsFile Property
Indicates if the attachment is a file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsFile { get; }
Public ReadOnly Property IsFile As Boolean
    Get

Property Value

Type: Boolean
true if the attachment is a file; otherwise, false.
Remarks
If the filename parameter of Content-Disposition header is not empty, attachment is considered to be a file. Some attachments, however, are not files: for instance, antivirus program may add some textual information as an attachment to the message, but this attachment has no filename and is not intended for saving to disk.
Examples
This sample loads the message from .EML file and displays filenames of all files attached to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...when it's a file...
    if (attach.IsFile)
    {
        // ...then show its filename.
        Console.WriteLine("Attachment " + attach.Filename + " is a file.");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...when it's a file...
    If attach.IsFile Then
        ' ...then show its filename.
        Console.WriteLine("Attachment " & attach.Filename & " is a file.")
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentIsInline


Attachment.IsInline Property

AttachmentIsInline Property
Indicates if the attachment is inline.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsInline { get; }
Public ReadOnly Property IsInline As Boolean
    Get

Property Value

Type: Boolean
true if the attachment is inline; otherwise, false.
Remarks
Attachment is considered inline when it should be rendered along with the message body. For instance, images and sounds in an HTML message are inline attachments while .zip archives are not. Inline attachments often have non-empty ContentID value which is used to reference such attachments within HTML body of the message.
Examples
This sample loads the message from .EML file and displays the filenames of all inline attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...when attachment is inline...
    if (attach.IsInline)
    {
        // ...then show its filename.
        Console.WriteLine("Attachment " + attach.Filename + " is inline.");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...when attachment is inline...
    If attach.IsInline Then
        ' ...then show its filename.
        Console.WriteLine("Attachment " & attach.Filename & " is inline.")
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentContentID


Attachment.IsMessageInside Property

AttachmentIsMessageInside Property
Indicates if the attachment contains a mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsMessageInside { get; }
Public ReadOnly Property IsMessageInside As Boolean
    Get

Property Value

Type: Boolean
true if the attachment is a mail message; otherwise, false.
Remarks
For instance, if the mail message was forwarded as attachment to another message, the developer can use this property to determine whether the attachment contains the forwarded message. If it does, GetEncapsulatedMessage method can be used to extract the encapsulated MailMessage object from the attachment.
Examples
This sample loads the message from .EML file and displays subjects of all attached e-mails.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...when the attachment is an e-mail message...
    if (attach.IsMessageInside)
    {
        // ...then extract the e-mail message from the attachment...
        MailMessage attachedMsg = attach.GetEncapsulatedMessage();

        // and show its Subject field.
        Console.WriteLine("Forwarded message subject is " + attachedMsg.Subject);
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...when the attachment is an e-mail message...
    If attach.IsMessageInside Then
        ' ...then extract the e-mail message from the attachment...
        Dim attachedMsg As MailMessage = attach.GetEncapsulatedMessage()

        ' and show its Subject field.
        Console.WriteLine("Forwarded message subject is " & attachedMsg.Subject)
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentGetEncapsulatedMessage
MailBee.MimeMailMessage


Attachment.IsTnef Property

AttachmentIsTnef Property
Indicates if the attachment is MS-TNEF (winmail.dat) container which can have other attachments inside.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsTnef { get; }
Public ReadOnly Property IsTnef As Boolean
    Get

Property Value

Type: Boolean
true if the attachment has MS-TNEF format; otherwise, false.
Remarks

Transport Neutral Encapsulation Format or TNEF is a Microsoft data format used by Microsoft Outlook and Microsoft Exchange Server. TNEF attachments are usually named winmail.dat or win.dat.

TNEF is not a common standard so that most mail clients do not natively support it. However, MailBee allows the developer to extract attachments from TNEF containers into AttachmentCollection using GetAttachmentsFromTnef method and then treat them like any other attachments.

Examples
This sample loads the message from .EML file and saves all TNEF-formatted attachments to disk (if any).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\mstnef.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...when the attachment is TNEF...
    if (attach.IsTnef)
    {
        // ...extract all the files from it and save them to the folder.
        attach.GetAttachmentsFromTnef().SaveAll(@"C:\Temp");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\mstnef.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...when the attachment is TNEF...
    If (attach.IsTnef) Then
        ' ...extract all the files from it and save them to the folder.
        attach.GetAttachmentsFromTnef().SaveAll("C:\Temp")
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentGetAttachmentsFromTnef


Attachment.IsVCard Property

AttachmentIsVCard Property
Indicates if the attachment is a vCard profile.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsVCard { get; }
Public ReadOnly Property IsVCard As Boolean
    Get

Property Value

Type: Boolean
true if the attachment has vCard profile inside; otherwise, false.
Remarks

The samples below utilize vCard functionality provided by a separate .DLL. To proceed, you should add a reference to ICalVCard.dll to your project.

You can find ICalVCard.dll in the same folder as MailBee.NET.dll (such as "C:\Program Files\MailBee.NET Objects\2.0").

To read more on ICalVCard.dll, view or download its documentation or source code, navigate to http://www.afterlogic.com/mailbee-net/icalvcard.

You can also refer to iCal and vCard Developer's Guide for sample code and further explanations.

You do not need any license keys to use ICalVCard.dll, it's a free library. Moreover, the full source code is available.

Examples

This topic contains several examples.

The first sample loads the message from an .EML file (it's assumed the message has a vCard attachment) and displays several fields from the vCard user profile.

C#
VB
Copy
using System;
using MailBee.Mime;
using vCards;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\vcard.eml");

        foreach (Attachment attach in msg.Attachments)
        {
            if (attach.IsVCard)
            {
                vCard crd = new vCard(attach.GetData());

                Console.WriteLine("Name: " + crd.FormattedName);
                Console.WriteLine("Title: " + crd.Title);
                Console.WriteLine("BirthDate: " + crd.BirthDate);
                Console.WriteLine("Organization: " + crd.Organization);

                foreach (vCardPhone phone in crd.Phones)
                {
                    if (phone.IsCellular)
                    {
                        Console.WriteLine("Cellular phone number: " + phone.FullNumber);
                    }
                    else if (phone.IsHome)
                    {
                        Console.WriteLine("Home phone number: " + phone.FullNumber);
                    }
                    else if (phone.IsWork)
                    {
                        Console.WriteLine("Work phone number: " + phone.FullNumber);
                    }
                    else if (phone.IsFax)
                    {
                        Console.WriteLine("Fax number: " + phone.FullNumber);
                    }
                }
            }
        }
    }
}
Imports System
Imports MailBee.Mime
Imports vCards

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim msg As MailMessage = New MailMessage
        msg.LoadMessage("C:\Docs\vcard.eml")

        Dim attach As Attachment
        For Each attach In msg.Attachments
            If attach.IsVCard Then
                Dim crd As vCard = New vCard(attach.GetData())

                Console.WriteLine("Name: " & crd.FormattedName)
                Console.WriteLine("Title: " & crd.Title)
                Console.WriteLine("BirthDate: " & crd.BirthDate)
                Console.WriteLine("Organization: " & crd.Organization)

                Dim phone As vCardPhone
                For Each phone In crd.Phones
                    If phone.IsCellular Then
                        Console.WriteLine("Cellular phone number: " & phone.FullNumber)
                    ElseIf phone.IsHome Then
                        Console.WriteLine("Home phone number: " & phone.FullNumber)
                    ElseIf phone.IsWork Then
                        Console.WriteLine("Work phone number: " & phone.FullNumber)
                    ElseIf phone.IsFax Then
                        Console.WriteLine("Fax number: " & phone.FullNumber)
                    End If
                Next
            End If
        Next
    End Sub
End Class
Examples
The next sample creates a vCard user profile with a photo and sends it to a recipient. The sample does not set any body in the message but you can add it if you need to.
C#
VB
Copy
using System;
using System.IO;
using System.Text;
using MailBee.Mime;
using MailBee.SmtpMail;
using vCards;

class Sample
{
    static void Main(string[] args)
    {
        // Create a new user profile.
        vCard crd = new vCard();

        crd.GivenName = "John";
        crd.FamilyName = "Smith";

        crd.Gender = vCardGender.Male;
        crd.BirthDate = new DateTime(1980, 3, 2);

        crd.Phones.Add(new vCardPhone("123-456-789", vCardPhoneTypes.Cellular));
        crd.Phones.Add(new vCardPhone("893-111-789", vCardPhoneTypes.Home));
        crd.Phones.Add(new vCardPhone("222-555-333", vCardPhoneTypes.Work));

        vCardPhoto photo = new vCardPhoto(@"C:\Docs\john_smith.jpg");

        crd.Photos.Add(photo);

        MailMessage msg = new MailMessage();
        msg.From.AsString = "user@mail.com";
        msg.To.Add("newuser@mail.com");
        msg.Subject = "See attached vCard";

        vCardStandardWriter wrt = new vCardStandardWriter();

        StringWriter sw = new StringWriter();

        // Specify charset to encode non-ascii strings.
        wrt.Write(crd, sw, "windows-1252");

        // Add vCard as attachment.
        msg.Attachments.Add(
            Encoding.GetEncoding("windows-1252").GetBytes(sw.ToString()),
            "John Smith.vcf", null, "application/octet-stream", null,
            NewAttachmentOptions.None, MailTransferEncoding.QuotedPrintable);

        // And send it.
        Smtp.QuickSend(msg);
    }
}
Imports System.IO
Imports System.Text
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports vCards

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Create a new user profile.
        Dim crd As vCard = New vCard

        crd.GivenName = "John"
        crd.FamilyName = "Smith"

        crd.Gender = vCardGender.Male
        crd.BirthDate = New DateTime(1980, 3, 2)

        crd.Phones.Add(New vCardPhone("123-456-789", vCardPhoneTypes.Cellular))
        crd.Phones.Add(New vCardPhone("893-111-789", vCardPhoneTypes.Home))
        crd.Phones.Add(New vCardPhone("222-555-333", vCardPhoneTypes.Work))

        Dim photo As vCardPhoto = New vCardPhoto("C:\Docs\john_smith.jpg")

        crd.Photos.Add(photo)

        Dim msg As MailMessage = New MailMessage
        msg.From.AsString = "user@mail.com"
        msg.To.Add("newuser@mail.com")
        msg.Subject = "See attached vCard"

        Dim wrt As vCardStandardWriter = New vCardStandardWriter

        Dim sw As StringWriter = New StringWriter

        ' Specify charset to encode non-ascii strings.
        wrt.Write(crd, sw, "windows-1252")

        ' Add vCard as attachment.
        msg.Attachments.Add( _
                Encoding.GetEncoding("windows-1252").GetBytes(sw.ToString()), _
                "John Smith.vcf", Nothing, "application/octet-stream", Nothing, _
                NewAttachmentOptions.None, MailTransferEncoding.QuotedPrintable)

        ' And send it.
        Smtp.QuickSend(msg)
    End Sub
End Class
Examples
The following code shows how to display Name and Surname with photo from vCard in a simple Windows Forms application. You should add two Labels on the form for text output and a PictureBox control to display the image.
C#
VB
Copy
using MailBee.Mime;
using vCards;

MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\vCardWithPhoto.eml");

foreach (Attachment attach in msg.Attachments)
{
    if (attach.IsVCard)
    {
        vCard crd = new vCard(attach.GetData());

        label1.Text = crd.GivenName;
        label2.Text = crd.FamilyName;

        pictureBox1.Image = Image.FromStream(
            new MemoryStream(crd.Photos[0].GetBytes()));
    }
}
Imports MailBee.Mime
Imports vCards

Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Docs\vCardWithPhoto.eml")

Dim attach As Attachment
For Each attach In msg.Attachments
    If attach.IsVCard Then
        Dim crd As vCard = New vCard(attach.GetData())

        label1.Text = crd.GivenName
        label2.Text = crd.FamilyName

        pictureBox1.Image = Image.FromStream( _
            New MemoryStream(crd.Photos(0).GetBytes()))
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace


Attachment.IsZip Property

AttachmentIsZip Property
Indicates if the attachment is a zip archive.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsZip { get; }
Public ReadOnly Property IsZip As Boolean
    Get

Property Value

Type: Boolean
true if the attachment filename has .ZIP extension; otherwise, false.
Examples
This sample loads the message from .EML file and displays the filenames of all attached zip files.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...when the attachment is a zip file...
    if (attach.IsZip)
    {
        // ...show its filename.
        Console.WriteLine("Attachment " + attach.Filename + " is a zip archive.");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...when the attachment is a zip file...
    If attach.IsZip Then
        ' ...show its filename.
        Console.WriteLine("Attachment " & attach.Filename & " is zip archive.")
    End If
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentFilenameOriginal


Attachment.LastResult Property

AttachmentLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
Examples
The example is available in ThrowExceptions property documentation.
See Also

Reference

Attachment Class
MailBee.Mime Namespace
MailBeeErrorCodes
AttachmentThrowExceptions


Attachment.Name Property

AttachmentName Property
Gets the friendly name of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; }
Public ReadOnly Property Name As String
    Get

Property Value

Type: String
A string containing the "friendly name" (or "display name") of the attachment, or an empty string if the friendly name is not available.
Remarks
This property contains the attachment friendly name which is taken from name parameter of Content-Type header of the attachment. An attachment friendly name is usually equal to its FilenameOriginal, but it may be different sometimes. To obtain the original filename of the attached file, use FilenameOriginal property.
Note Note
Since Name value can be empty, it's usually more convenient to use Filename value instead.
Examples
This sample loads the message from .EML file and displays the friendly names of all attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show its friendly name.
    Console.WriteLine("Name is " + attach.Name);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show its friendly name.
    Console.WriteLine("Name is " & attach.Name)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentFilenameOriginal
AttachmentFilename
AttachmentSavedAs


Attachment.RawHeader Property

AttachmentRawHeader Property
Gets a string containing the header section of the attachment in the original form.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RawHeader { get; }
Public ReadOnly Property RawHeader As String
    Get

Property Value

Type: String
A string containing the attachment header section as it came with the message, or an empty string if the attachment was added by the application rather than extracted from the message.
Examples
This sample loads the message from .EML file and displays the raw header of each attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show its header section.
    Console.WriteLine(attach.RawHeader);
    Console.WriteLine();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show its header section.
    Console.WriteLine(attach.RawHeader)
    Console.WriteLine()
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentHeaders


Attachment.SavedAs Property

AttachmentSavedAs Property
Gets the full path to the attachment which was saved to disk.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SavedAs { get; }
Public ReadOnly Property SavedAs As String
    Get

Property Value

Type: String
A string containing the full path to the attachment which was saved to disk, or empty string if the attachment was not saved to disk yet.
Remarks

This property is especially useful when the attachment was saved to disk implicitly (for instance, when all embedded pictures/files referenced in the HTML body were saved to disk by GetHtmlAndSaveRelatedFiles method call, and the developer wants to know the exact paths to the saved files).

Filenames of such files depend on the way they were saved. Usually attachments are saved under the path specified by the developer if saving was explicit (e.g. with Save(String, Boolean) method); or if saving was implicit (e.g. with GetHtmlAndSaveRelatedFiles method), attachments are saved to MailMessage.Parser.WorkingFolder.

Examples
This sample loads the message from .EML file, saves every attachment to disk specifying only the folder, and displays the full path to each saved file.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...save the attachment into the specified folder overwriting the existing file if necessary,
    attach.SaveToFolder(@"C:\Temp\", true);

    // and show the full path to the saved file.
    Console.WriteLine("The path is " + attach.SavedAs);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...save the attachment into the specified folder overwriting the existing file if necessary,
    attach.SaveToFolder("C:\Temp\", True)

    ' and show the full path to the saved file.
    Console.WriteLine("The path is " & attach.SavedAs)
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentName
AttachmentFilename
AttachmentFilenameOriginal


Attachment.Size Property

AttachmentSize Property
Gets the length of the binary content of the attachment.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Size { get; }
Public ReadOnly Property Size As Integer
    Get

Property Value

Type: Int32
The length of the binary content of the message attachment in bytes.
Remarks
This property contains the length of the attachment's content in decoded form (after the mail message has already been parsed and all MIME parts have been decoded from base64, quoted-printable, etc).
Examples
This sample loads the message from .EML file and displays the size of each attachment's data.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment...
foreach (Attachment attach in msg.Attachments)
{
    // ...show the length of the attachment data in bytes.
    Console.WriteLine("The size is " + attach.Size.ToString());
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment...
For Each attach As Attachment In msg.Attachments
    ' ...show the length of the attachment data in bytes.
    Console.WriteLine("The size is " & attach.Size.ToString())
Next
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentGetData


Attachment.ThrowExceptions Property

AttachmentThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; }
Public ReadOnly Property ThrowExceptions As Boolean
    Get

Property Value

Type: Boolean
true if the Attachment object will throw exceptions on errors; otherwise, false. The default value is true.
Remarks
If this property is set to true and an error occurs, an exception derived from MailBeeException is thrown. Otherwise, the exception will not occur but the method which caused will report error (returning false, null reference, etc). Anyway, the code of the last occurred error will be contained in the LastResult property. The list of all error codes is available in ErrorCodes class overview.
Examples
The example is available in MailMessage.ThrowExceptions topic.
See Also

Reference

Attachment Class
MailBee.Mime Namespace
AttachmentLastResult


AttachmentCollection Class

AttachmentCollection Class
Provides properties and methods for managing and examining the collection of Attachment objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeAttachmentCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class AttachmentCollection : CollectionBase
Public Class AttachmentCollection
    Inherits CollectionBase

The AttachmentCollection type exposes the following members.

Methods
 | Name | Description
 | Add(String) | Adds the attachment from a file.
 | Add(Attachment) | Adds the specified Attachment object to the collection.
 | Add(String, String) | Adds the attachment from a file.
 | Add(String, String, String) | Adds the attachment from a file.
 | Add(String, String, HeaderCollection, MailTransferEncoding) | Adds text-only part with the specified content-type.
 | Add(Byte, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a byte array.
 | Add(Stream, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a stream.
 | Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a file.
 | Add(MailMessage, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the specified the MailMessage as attachment (i.e. forwards that message as attachment).
Public method | AddAsync(String) | async/await version of Add(String).
Public method | AddAsync(String, String) | async/await version of Add(String, String).
Public method | AddAsync(String, String, String) | async/await version of Add(String, String, String).
Public method | AddAsync(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | async/await version of Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding).
 | Clear | Clears the attachments collection.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Remove | Removes the attachment having the specified unique name from the collection.
 | RemoveAt | Removes the attachment with the specified index from the collection.
 | SaveAll(String) | Saves all attachments of the message to the specified folder.
 | SaveAll(String, Boolean) | Saves real (and, optionally, inline) attachments.
Public method | SaveAllAsync(String) | async/await version of SaveAll(String).
Public method | SaveAllAsync(String, Boolean) | async/await version of SaveAll(String, Boolean).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Public property | InlineCount | Returns the number of inline attachments in the collection.
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets or sets the Attachment object at the specified zero-based index in the collection.
 | ItemString | Gets the Attachment object in the collection by the specified filename.
 | LastResult | Gets a numeric code of the last error.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks
This collection represents all attachments of the mail message. It's available through Attachments property of MailMessage object. GetAttachmentsFromTnef method can also return AttachmentCollection.
Examples
This sample loads the message from .EML file and saves all attachments to the disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every attachment from the attachments collection...
foreach (Attachment attach in msg.Attachments)
{
    // Save the attachment to the file.
    attach.Save(@"C:\Temp\" + attach.Name, true);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every attachment from the attachments collection...
For Each attach As Attachment In msg.Attachments
    ' Save the attachment to the file.
    attach.Save("C:\Temp\" & attach.Name, True)
Next
See Also

Reference

MailBee.Mime Namespace


AttachmentCollection Methods

AttachmentCollection Methods

The AttachmentCollection type exposes the following members.

Methods
 | Name | Description
 | Add(String) | Adds the attachment from a file.
 | Add(Attachment) | Adds the specified Attachment object to the collection.
 | Add(String, String) | Adds the attachment from a file.
 | Add(String, String, String) | Adds the attachment from a file.
 | Add(String, String, HeaderCollection, MailTransferEncoding) | Adds text-only part with the specified content-type.
 | Add(Byte, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a byte array.
 | Add(Stream, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a stream.
 | Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a file.
 | Add(MailMessage, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the specified the MailMessage as attachment (i.e. forwards that message as attachment).
Public method | AddAsync(String) | async/await version of Add(String).
Public method | AddAsync(String, String) | async/await version of Add(String, String).
Public method | AddAsync(String, String, String) | async/await version of Add(String, String, String).
Public method | AddAsync(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | async/await version of Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding).
 | Clear | Clears the attachments collection.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Remove | Removes the attachment having the specified unique name from the collection.
 | RemoveAt | Removes the attachment with the specified index from the collection.
 | SaveAll(String) | Saves all attachments of the message to the specified folder.
 | SaveAll(String, Boolean) | Saves real (and, optionally, inline) attachments.
Public method | SaveAllAsync(String) | async/await version of SaveAll(String).
Public method | SaveAllAsync(String, Boolean) | async/await version of SaveAll(String, Boolean).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.Add Method

AttachmentCollectionAdd Method
Adds an attachment to the collection.
Overload List
Name | Description
Add(String) | Adds the attachment from a file.
Add(Attachment) | Adds the specified Attachment object to the collection.
Add(String, String) | Adds the attachment from a file.
Add(String, String, String) | Adds the attachment from a file.
Add(String, String, HeaderCollection, MailTransferEncoding) | Adds text-only part with the specified content-type.
Add(Byte, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a byte array.
Add(Stream, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a stream.
Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the attachment from a file.
Add(MailMessage, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | Adds the specified the MailMessage as attachment (i.e. forwards that message as attachment).
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.Add Method (String)

AttachmentCollectionAdd Method (String)
Adds the attachment from a file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    string filename
)
Public Function Add (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.

Return Value

Type: Boolean
true if the attachment was successfully added to the collection; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
Examples
This sample loads the message from .EML file and adds an attachment to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Add the attachment to the message.
msg.Attachments.Add(@"C:\Temp\my_photo.jpg");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Add the attachment to the message.
msg.Attachments.Add("C:\Temp\my_photo.jpg")
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (Attachment)

AttachmentCollectionAdd Method (Attachment)
Adds the specified Attachment object to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    Attachment attach
)
Public Sub Add (
    attach As Attachment
)

Parameters

attach
Type: MailBee.MimeAttachment
The Attachment object which should be added.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | attach is a null reference (Nothing in Visual Basic).
Examples
This sample loads two messages from .EML files, adds all attachments of the second message to the first message, and saves the first message (which now includes all the original plus added attachments) to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

MailMessage msg1 = new MailMessage();
msg1.LoadMessage(@"C:\Docs\TestMail1.eml");

MailMessage msg2 = new MailMessage();
msg2.LoadMessage(@"C:\Docs\TestMail2.eml");

for (int i = 0; i < msg2.Attachments.Count; i++)
{
    msg1.Attachments.Add(msg2.Attachments[i]);
}
msg1.SaveMessage(@"C:\Temp\TestMail1.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim msg1 As New MailMessage
msg1.LoadMessage("C:\Docs\TestMail1.eml")

Dim msg2 As New MailMessage
msg2.LoadMessage("C:\Docs\TestMail2.eml")

Dim i As Integer
For i = 0 To msg2.Attachments.Count - 1
    msg1.Attachments.Add(msg2.Attachments(i))
Next
msg1.SaveMessage("C:\Temp\TestMail1.eml")
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (String, String)

AttachmentCollectionAdd Method (String, String)
Adds the attachment from a file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    string filename,
    string targetFilename
)
Public Function Add (
    filename As String,
    targetFilename As String
) As Boolean

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.
targetFilename
Type: SystemString
The filename of the attachment as it should appear in the mail message. If a null reference (Nothing in Visual Basic), MailBee will take it from filename parameter value. If an empty string, the attachment will have no name.

Return Value

Type: Boolean
true if the attachment was successfully added; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks
The targetFilename parameter allows the developer to override the filename under which the attachment will be added to the collection. This is useful when the developer wants to add the attachment from a temporary file such as ETQB4914.TMP under meaningful name such as report.doc.
Examples
This sample loads the message from .EML file and adds an attachment to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Add the attachment to the message.
msg.Attachments.Add(@"C:\Docs\pict1.tmp","map.jpg");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Add the attachment to the message.
msg.Attachments.Add("C:\Docs\pict1.tmp", "map.jpg")
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (String, String, String)

AttachmentCollectionAdd Method (String, String, String)
Adds the attachment from a file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    string filename,
    string targetFilename,
    string contentID
)
Public Function Add (
    filename As String,
    targetFilename As String,
    contentID As String
) As Boolean

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.
targetFilename
Type: SystemString
The filename of the attachment as it should appear in the mail message. If a null reference (Nothing in Visual Basic), MailBee will take it from filename parameter value. If an empty string, the attachment will have no name.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.

Return Value

Type: Boolean
true if the attachment was successfully added; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks
The targetFilename parameter allows the developer to override the filename under which the attachment will be added to the collection. This is useful when the developer wants to add the attachment from a temporary file such as ETQB4914.TMP under meaningful name such as report.doc.
Examples
This sample creates a new message and adds an attachment to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add the attachment to the message.
msg.Attachments.Add(@"C:\Temp\mypic.gif", "my.gif","<00s4a8m8918c$5664i1b1$iw671781@tlffmdqjobxj>");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add the attachment to the message.
msg.Attachments.Add("C:\Temp\mypic.gif", "my.gif", "<00s4a8m8918c$5664i1b1$iw671781@tlffmdqjobxj>")
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (String, String, HeaderCollection, MailTransferEncoding)

AttachmentCollectionAdd Method (String, String, HeaderCollection, MailTransferEncoding)
Adds text-only part with the specified content-type.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    string data,
    string contentType,
    HeaderCollection customHeaders,
    MailTransferEncoding mailEnc
)
Public Sub Add (
    data As String,
    contentType As String,
    customHeaders As HeaderCollection,
    mailEnc As MailTransferEncoding
)

Parameters

data
Type: SystemString
Text to be inserted as part's body.
contentType
Type: SystemString
Content-Type of the part being added.
customHeaders
Type: MailBee.MimeHeaderCollection
The collection of the headers which should be included into the header section in additon to the Content-Type. If a null reference (Nothing in Visual Basic), no custom headers will be added.
mailEnc
Type: MailBee.MimeMailTransferEncoding
The content-transfer encoding to be used. Usually, None.
Remarks

This overload can typically be used to add such MIME parts as delivery-status reports (Message Disposition Notification, MDN). For MDNs, you usually supply "message/delivery-status" as contentType value and None as mailEnc value.

The only mandatory header which will be added is Content-Type (unless you added some custom headers). No "attachment" marker will be added.

Note Note
Text lines in data which have more than 76 chars will be explicitly wrapped by defaut (unless QuotedPrintable or Base64 is selected, they can handle wrapping internally). You can adjust this behavior by increasing UnwrappedLineLengthLimit property value.
Examples
This sample prepares a Message Disposition Notification e-mail.
C#
VB
Copy
MailMessage msg = new MailMessage();
string mdnBody = @"Reporting-MTA: dns;mx.company.com
Received-From-MTA: dns;servo01.domain.net
Arrival-Date: Wed, 18 May 2016 08:28:53 +0000

Original-Recipient: rfc822;jdoe@company.com
Final-Recipient: rfc822;jdoe@company.com
Action: failed
Status: 5.1.10
Diagnostic-Code: smtp;550 5.1.10 RESOLVER.ADR.RecipientNotFound;
 Recipient not found by SMTP address lookup
";
msg.Attachments.Add(mdnBody, "message/delivery-status", null, MailTransferEncoding.None);
msg.MdnReportType = "delivery-status";
msg.From.AsString = "Internet Mail Delivery <postmaster@company.com>";
msg.Subject = "Delivery Notification: Delivery has failed";
msg.To.Add("sender@domain.net");
msg.BodyPlainText = @"Your message to jdoe@company.com couldn't be delivered.
jdoe@company.com wasn't found at company.com.
";
msg.SaveMessage(@"C:\Temp\mdn.eml"); // Or assign msg to Message property of Smtp object to send it out.

            Dim msg As New MailMessage()
            Dim mdnBody As String = "Reporting-MTA: dns;mx.company.com" & vbCrLf & _
              "Received-From-MTA: dns;servo01.domain.net" & vbCrLf & _
              "Arrival-Date: Wed, 18 May 2016 08:28:53 +0000" & vbCrLf & vbCrLf & _
              "Original-Recipient: rfc822;jdoe@company.com" & vbCrLf & _
              "Final-Recipient: rfc822;jdoe@company.com" & vbCrLf & _
              "Action: failed" & vbCrLf & _
              "Status: 5.1.10" & vbCrLf & _
              "Diagnostic-Code: smtp;550 5.1.10 RESOLVER.ADR.RecipientNotFound;" & vbCrLf & _
              " Recipient not found by SMTP address lookup" & vbCrLf
            msg.Attachments.Add(mdnBody, "message/delivery-status", Nothing, MailTransferEncoding.None)
            msg.MdnReportType = "delivery-status"
            msg.From.AsString = "Internet Mail Delivery <postmaster@company.com>"
            msg.Subject = "Delivery Notification: Delivery has failed"
            msg.To.Add("sender@domain.net")
            msg.BodyPlainText = "Your message to jdoe@company.com couldn't be delivered." & vbCrLf & vbCrLf & _
              "jdoe@company.com wasn't found at company.com." & vbCrLf
            msg.MailTransferEncodingPlain = MailTransferEncoding.None
            msg.SaveMessage("C:\Temp\mdn.eml") ' Or assign msg to Message property of Smtp object to send it out.

  See Also
Reference
AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
Copyright © 2006-2019 AfterLogic Corporation. All rights reserved.
Send comments on this topic to
        AfterLogic


AttachmentCollection.Add Method (Byte[], String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)

AttachmentCollectionAdd Method (Byte, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)
Adds the attachment from a byte array.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    byte[] data,
    string targetFilename,
    string contentID,
    string contentType,
    HeaderCollection customHeaders,
    NewAttachmentOptions options,
    MailTransferEncoding mailEnc
)
Public Sub Add (
    data As Byte(),
    targetFilename As String,
    contentID As String,
    contentType As String,
    customHeaders As HeaderCollection,
    options As NewAttachmentOptions,
    mailEnc As MailTransferEncoding
)

Parameters

data
Type: SystemByte
The binary content of the attachment represented as a byte array.
targetFilename
Type: SystemString
The filename under which to add the attachment into the collection. If an empty string, the attachment will have no name.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.
contentType
Type: SystemString
The content type of the attachment, or a null reference (Nothing in Visual Basic) to let MailBee detect the content type automatically.
customHeaders
Type: MailBee.MimeHeaderCollection
The collection of the headers which should be included into the header section in additon to the standard attachment headers. If a null reference (Nothing in Visual Basic), no custom headers will be added.
options
Type: MailBee.MimeNewAttachmentOptions
The options which affect how the attachment is added.
mailEnc
Type: MailBee.MimeMailTransferEncoding
The mail encoding to use when placing the attachment data into the message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | data or targetFilename is a null reference (Nothing in Visual Basic).
Remarks
Note Note
If you're attaching another e-mail message, be sure to use as None as mailEnc value. Some mail services cannot decode attached emails if they are Base64-encoded.
Examples
This sample reads a file into memory buffer and adds it as attachment to the message.
Note Note
In real-world apps, it's easier to use Add(String) overload to add an attachment from a file.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// Create new data buffer as binary array.
byte[] fileData = null;

// Open a file for reading.
using (FileStream fs = new FileStream(@"C:\Temp\1.gif", FileMode.Open))
{
    // Set the size of the buffer.
    fileData = new byte[fs.Length];

    // Create new BinaryReader object.
    BinaryReader br = new BinaryReader(fs);

    // Read binary data from file to buffer.
    br.Read(fileData, 0, fileData.Length);
}

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add an attachment to the message.
msg.Attachments.Add(fileData, "my.gif", "<12s4a8a8778c$5664i1b1$ir671781@tlffmdqjobxj>", "image/gif", null, NewAttachmentOptions.None, MailTransferEncoding.Base64);
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' Create new data buffer as binary array.
Dim fileData As Byte() = Nothing

' Open file for read.
Dim fs As FileStream
Try
    fs = New FileStream("C:\Temp\1.gif", System.IO.FileMode.Open)

    ' Set the size of the buffer.
    ReDim fileData(fs.Length)

    ' Create new BinaryReader object.
    Dim br As New BinaryReader(fs)

    ' Read binary data from file to buffer.
    br.Read(fileData, 0, fileData.Length)
Finally
    If Not fs Is Nothing Then fs.Close()
End Try

' Create new MailMessage object.
Dim msg As New MailMessage

' Add an attachment to the message.
msg.Attachments.Add(fileData, "my.gif", "<12s4a8a8778c$5664i1b1$ir671781@tlffmdqjobxj>", "image/gif", Nothing, NewAttachmentOptions.None, MailTransferEncoding.Base64)
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (Stream, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)

AttachmentCollectionAdd Method (Stream, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)
Adds the attachment from a stream.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    Stream stream,
    string targetFilename,
    string contentID,
    string contentType,
    HeaderCollection customHeaders,
    NewAttachmentOptions options,
    MailTransferEncoding mailEnc
)
Public Function Add (
    stream As Stream,
    targetFilename As String,
    contentID As String,
    contentType As String,
    customHeaders As HeaderCollection,
    options As NewAttachmentOptions,
    mailEnc As MailTransferEncoding
) As Boolean

Parameters

stream
Type: System.IOStream
The data stream from which to read the binary content of the attachment.
targetFilename
Type: SystemString
The filename under which to add the attachment into the collection.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.
contentType
Type: SystemString
The content type of the attachment, or a null reference (Nothing in Visual Basic) to let MailBee detect the content type automatically.
customHeaders
Type: MailBee.MimeHeaderCollection
The collection of the headers which should be included into the header section in additon to the standard attachment headers. If a null reference (Nothing in Visual Basic), no custom headers will be added.
options
Type: MailBee.MimeNewAttachmentOptions
The options which affect how the attachment is added.
mailEnc
Type: MailBee.MimeMailTransferEncoding
The mail encoding to use when placing the attachment data into the message.

Return Value

Type: Boolean
true if the attachment was successfully added to the collection; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | stream or targetFilename is a null reference (Nothing in Visual Basic).
MailBeeStreamException | An error occurred and ThrowExceptions is true.
Remarks
The targetFilename parameter allows the developer to override the filename under which the attachment will be added to the collection. This is useful if the attachment is being added from a temporary file such as ETQB4914.TMP under meaningful name such as report.doc.
Examples
This sample opens a file stream, reads the file into the stream, adds the attachment from the stream, and saves the message to disk.
Note Note
In real-world apps, it's easier to use Add(String) overload to add an attachment from a file.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Open the file as stream for reading.
using (FileStream fs = new FileStream(@"C:\Docs\1.gif", FileMode.Open))
{
    // Create new MailMessage object.
    MailMessage msg = new MailMessage();

    // Set plain text body of the message.
    msg.BodyPlainText = "Hello, World!";

    // Add the attachment to the message.
    msg.Attachments.Add(fs, "pic1.gif", "<12s4a8a8778c$5664i1b1$ir671781@tlffmdqjobxj>", "image/gif", null, NewAttachmentOptions.None, MailTransferEncoding.Base64);

    // Save message to disk.
    msg.SaveMessage(@"C:\Temp\SavedMessage.eml");
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Open the file as stream for reading.
Dim fs As FileStream
fs = Nothing
Try
    fs = New FileStream("C:\Docs\1.gif", FileMode.Open)

    ' Create new MailMessage object.
    Dim msg As New MailMessage

    ' Set plain text body of the message.
    msg.BodyPlainText = "Hello, World!"

    ' Add the attachment to the message.
    msg.Attachments.Add(fs, "pic1.gif", "<12s4a8a8778c$5664i1b1$ir671781@tlffmdqjobxj>", "image/gif", Nothing, NewAttachmentOptions.None, MailTransferEncoding.None)

    ' Save message to disk.
    msg.SaveMessage("C:\Temp\SavedMessage.eml")
Finally
    If Not fs Is Nothing Then fs.Close()
End Try
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)

AttachmentCollectionAdd Method (String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)
Adds the attachment from a file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    string filename,
    string targetFilename,
    string contentID,
    string contentType,
    HeaderCollection customHeaders,
    NewAttachmentOptions options,
    MailTransferEncoding mailEnc
)
Public Function Add (
    filename As String,
    targetFilename As String,
    contentID As String,
    contentType As String,
    customHeaders As HeaderCollection,
    options As NewAttachmentOptions,
    mailEnc As MailTransferEncoding
) As Boolean

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.
targetFilename
Type: SystemString
The filename of the attachment as it should appear in the mail message. If a null reference (Nothing in Visual Basic), MailBee will take it from filename parameter value. If an empty string, the attachment will have no name.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.
contentType
Type: SystemString
The content type of the attachment, or a null reference (Nothing in Visual Basic) to let MailBee detect the content type automatically.
customHeaders
Type: MailBee.MimeHeaderCollection
The collection of the headers which should be included into the header section in additon to the standard attachment headers. If a null reference (Nothing in Visual Basic), no custom headers will be added.
options
Type: MailBee.MimeNewAttachmentOptions
The options which affect how the attachment is added.
mailEnc
Type: MailBee.MimeMailTransferEncoding
The mail encoding to use when placing the attachment data into the message.

Return Value

Type: Boolean
true if the attachment was successfully added to the collection; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks
The targetFilename parameter allows the developer to override the filename under which the attachment will be added to the collection. This is useful when the developer wants to add the attachment from a temporary file such as ETQB4914.TMP under meaningful name such as report.doc.
Note Note
If you're attaching another e-mail message, be sure to use as None as mailEnc value. Some mail services cannot decode attached emails if they are Base64-encoded.
Examples
This sample creates a new message and adds an attachment to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add the attachment to the message.
msg.Attachments.Add(@"C:\Docs\mypic.gif", "my.gif", "<00s4a8m8918c$5664i1b1$iw671781@tlffmdqjobxj>", "image/gif", null, NewAttachmentOptions.None, MailTransferEncoding.Base64);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add the attachment to the message.
msg.Attachments.Add("C:\Docs\mypic.gif", "my.gif", "<00s4a8m8918c$5664i1b1$iw671781@tlffmdqjobxj>", "image/gif", Nothing, NewAttachmentOptions.None, MailTransferEncoding.Base64)
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Add Method (MailMessage, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)

AttachmentCollectionAdd Method (MailMessage, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)
Adds the specified the MailMessage as attachment (i.e. forwards that message as attachment).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    MailMessage message,
    string targetFilename,
    string contentID,
    string contentType,
    HeaderCollection customHeaders,
    NewAttachmentOptions options,
    MailTransferEncoding mailEnc
)
Public Sub Add (
    message As MailMessage,
    targetFilename As String,
    contentID As String,
    contentType As String,
    customHeaders As HeaderCollection,
    options As NewAttachmentOptions,
    mailEnc As MailTransferEncoding
)

Parameters

message
Type: MailBee.MimeMailMessage
The mail message to be added as attachment.
targetFilename
Type: SystemString
The filename under which to add the attachment into the collection. If a null reference (Nothing in Visual Basic), MailBee will take it from the Subject of the message being attached. If an empty string, the attachment will have no name.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.
contentType
Type: SystemString
The content type of the attachment. If a null reference (Nothing in Visual Basic), message/rfc822 value is used.
customHeaders
Type: MailBee.MimeHeaderCollection
The collection of the headers which should be included into the header section in additon to the standard attachment headers. If a null reference (Nothing in Visual Basic), no custom headers will be added.
options
Type: MailBee.MimeNewAttachmentOptions
The options which affect how the attachment is added.
mailEnc
Type: MailBee.MimeMailTransferEncoding
The mail encoding to use when placing the attachment data into the message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
Remarks
This method can be used to forward mail messages with another mail message. To forward a single message, it's easier to use ForwardAsAttachment method.
Note Note
Be sure to use as None as mailEnc value. Some mail services cannot decode attached emails if they are Base64-encoded.
Examples
The following example demonstrates how a mail message can be attached to another mail message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage messageToAttach = new MailMessage();
messageToAttach.LoadMessage(@"C:\Docs\TestMail.eml");

// Create new MailMessage object.
MailMessage msg = new MailMessage();

// Set plain text body of the message.
msg.BodyPlainText = "Hello, World!";

// Add the attachment to the message.
msg.Attachments.Add(messageToAttach, "original.eml", "", "message/rfc822", null, NewAttachmentOptions.Inline, MailTransferEncoding.None);

// Save message to disk.
msg.SaveMessage(@"C:\Temp\forwarded.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim messageToAttach As New MailMessage
messageToAttach.LoadMessage("C:\Docs\TestMail.eml")

' Create new MailMessage object.
Dim msg As New MailMessage

' Set plain text body of the message.
msg.BodyPlainText = "Hello, World!"

' Add the attachment to the message.
msg.Attachments.Add(messageToAttach, "original.eml", "", "message/rfc822", Nothing, NewAttachmentOptions.Inline, MailTransferEncoding.None)

' Save message to disk.
msg.SaveMessage("C:\Temp\forwarded.eml")
See Also

Reference

AttachmentCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeAttachment
MailBee.MimeMailMessage


AttachmentCollection.AddAsync Method

AttachmentCollectionAddAsync Method
Overload List
 | Name | Description
Public method | AddAsync(String) | async/await version of Add(String).
Public method | AddAsync(String, String) | async/await version of Add(String, String).
Public method | AddAsync(String, String, String) | async/await version of Add(String, String, String).
Public method | AddAsync(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) | async/await version of Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding).
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.AddAsync Method (String)

AttachmentCollectionAddAsync Method (String)
async/await version of Add(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> AddAsync(
    string filename
)
Public Function AddAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the attachment was successfully added to the collection; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

AttachmentCollection Class
AddAsync Overload
MailBee.Mime Namespace


AttachmentCollection.AddAsync Method (String, String)

AttachmentCollectionAddAsync Method (String, String)
async/await version of Add(String, String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> AddAsync(
    string filename,
    string targetFilename
)
Public Function AddAsync (
    filename As String,
    targetFilename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.
targetFilename
Type: SystemString
The filename of the attachment as it should appear in the mail message. If a null reference (Nothing in Visual Basic), MailBee will take it from filename parameter value. If an empty string, the attachment will have no name.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the attachment was successfully added; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

AttachmentCollection Class
AddAsync Overload
MailBee.Mime Namespace


AttachmentCollection.AddAsync Method (String, String, String)

AttachmentCollectionAddAsync Method (String, String, String)
async/await version of Add(String, String, String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> AddAsync(
    string filename,
    string targetFilename,
    string contentID
)
Public Function AddAsync (
    filename As String,
    targetFilename As String,
    contentID As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.
targetFilename
Type: SystemString
The filename of the attachment as it should appear in the mail message. If a null reference (Nothing in Visual Basic), MailBee will take it from filename parameter value. If an empty string, the attachment will have no name.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the attachment was successfully added; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

AttachmentCollection Class
AddAsync Overload
MailBee.Mime Namespace


AttachmentCollection.AddAsync Method (String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)

AttachmentCollectionAddAsync Method (String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)
async/await version of Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> AddAsync(
    string filename,
    string targetFilename,
    string contentID,
    string contentType,
    HeaderCollection customHeaders,
    NewAttachmentOptions options,
    MailTransferEncoding mailEnc
)
Public Function AddAsync (
    filename As String,
    targetFilename As String,
    contentID As String,
    contentType As String,
    customHeaders As HeaderCollection,
    options As NewAttachmentOptions,
    mailEnc As MailTransferEncoding
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The absolute or relative path to the file which should be attached.
targetFilename
Type: SystemString
The filename of the attachment as it should appear in the mail message. If a null reference (Nothing in Visual Basic), MailBee will take it from filename parameter value. If an empty string, the attachment will have no name.
contentID
Type: SystemString
The content identifier (CID) of the attachment (for inline attachments), or empty string if the attachment is not inline.
contentType
Type: SystemString
The content type of the attachment, or a null reference (Nothing in Visual Basic) to let MailBee detect the content type automatically.
customHeaders
Type: MailBee.MimeHeaderCollection
The collection of the headers which should be included into the header section in additon to the standard attachment headers. If a null reference (Nothing in Visual Basic), no custom headers will be added.
options
Type: MailBee.MimeNewAttachmentOptions
The options which affect how the attachment is added.
mailEnc
Type: MailBee.MimeMailTransferEncoding
The mail encoding to use when placing the attachment data into the message.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the attachment was successfully added to the collection; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

AttachmentCollection Class
AddAsync Overload
MailBee.Mime Namespace


AttachmentCollection.Clear Method

AttachmentCollectionClear Method
Clears the attachments collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear()
Public Sub Clear
Remarks
All Attachment objects contained in the collection will be removed from the mail message.
Examples
This sample loads the message from .EML file and clears the attachment collection.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all the attachments from the message.
msg.Attachments.Clear();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all the attachments from the message.
msg.Attachments.Clear()
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.Remove Method

AttachmentCollectionRemove Method
Removes the attachment having the specified unique name from the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    string filename
)
Public Function Remove (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The unique name of the attachment (as returned by Filename property) to be removed.

Return Value

Type: Boolean
true if the specified attachment was successfully removed; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic).
Remarks
The developer can also use RemoveAt(Int32) method to remove the attachment by its integer zero-based index in the collection.
Examples
This sample loads the message from .EML file and removes the attachment with me.jpg filename.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove the specified attachment from the collection.
msg.Attachments.Remove("me.jpg");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove the specified attachment from the collection.
msg.Attachments.Remove("me.jpg")
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.RemoveAt Method

AttachmentCollectionRemoveAt Method
Removes the attachment with the specified index from the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index of the attachment to be removed.

Return Value

Type:
true if the specified attachment was successfully removed from the collection; otherwise, false.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and removes the first attachment from the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove the first attachment from the collection.
msg.Attachments.RemoveAt(0);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove the first attachment from the collection.
msg.Attachments.RemoveAt(0)
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace
AttachmentCollectionRemove(String)


AttachmentCollection.SaveAll Method

AttachmentCollectionSaveAll Method
Overload List
Name | Description
SaveAll(String) | Saves all attachments of the message to the specified folder.
SaveAll(String, Boolean) | Saves real (and, optionally, inline) attachments.
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.SaveAll Method (String)

AttachmentCollectionSaveAll Method (String)
Saves all attachments of the message to the specified folder.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveAll(
    string folderName
)
Public Function SaveAll (
    folderName As String
) As Boolean

Parameters

folderName
Type: SystemString
The absolute or relative path to the folder where to save the attachments.

Return Value

Type: Boolean
true if all attachments were successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | folderName is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks

If the specified folder does not exist, MailBee will try to create it first.

Attachments having duplicate filenames will be renamed and then saved. For instance, if there are three attachments with my_cat.jpg file name, they will be saved to disk under the following filenames:

  • my_cat.jpg
  • my_cat[1].jpg
  • my_cat[2].jpg
For each attachment, SavedAs property can be examined to get the actual file path each file was saved under.

Examples
This sample loads the message from .EML file and saves all attachments into the specified folder.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Save all attachments into the folder.
msg.Attachments.SaveAll(@"C:\Temp");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Save all attachments into the folder.
msg.Attachments.SaveAll("C:\Temp")
See Also

Reference

AttachmentCollection Class
SaveAll Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.SaveAll Method (String, Boolean)

AttachmentCollectionSaveAll Method (String, Boolean)
Saves real (and, optionally, inline) attachments.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveAll(
    string folderName,
    bool ignoreInlineAttachments
)
Public Function SaveAll (
    folderName As String,
    ignoreInlineAttachments As Boolean
) As Boolean

Parameters

folderName
Type: SystemString
The absolute or relative path to the folder where to save the attachments.
ignoreInlineAttachments
Type: SystemBoolean
If true, only real attachments (not inline) will be saved; otherwise, both inline and not inline attachments will be saved.

Return Value

Type: Boolean
true if all attachments were successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | folderName is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
Remarks

If the specified folder does not exist, MailBee will try to create it first.

Attachments having duplicate filenames will be renamed and then saved. For instance, if there are three attachments with my_cat.jpg filename, they will be saved to disk under the following filenames:

  • my_cat.jpg
  • my_cat[1].jpg
  • my_cat[2].jpg
For each attachment, SavedAs property can be examined to get the actual file path each file was saved under.

Note Note
Inline attachments are usually used in the process of rendering the HTML body of the message. Thus, they are usually saved to disk by methods like GetHtmlAndSaveRelatedFiles. The current method, on other hand, is useful when the developer wants to save only real attachments (files which were explicitly attached to the message by the sender) and skip any files which have already been rendered with the message body.
Examples
This sample loads the message from .EML file and saves all attachments to the specified folder.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

' Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Save all attachments to folder.
msg.Attachments.SaveAll(@"C:\Temp", false);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Save all attachments to folder.
msg.Attachments.SaveAll("C:\Temp", False)
See Also

Reference

AttachmentCollection Class
SaveAll Overload
MailBee.Mime Namespace
MailBee.MimeAttachment


AttachmentCollection.SaveAllAsync Method

AttachmentCollectionSaveAllAsync Method
Overload List
 | Name | Description
Public method | SaveAllAsync(String) | async/await version of SaveAll(String).
Public method | SaveAllAsync(String, Boolean) | async/await version of SaveAll(String, Boolean).
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.SaveAllAsync Method (String)

AttachmentCollectionSaveAllAsync Method (String)
async/await version of SaveAll(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveAllAsync(
    string folderName
)
Public Function SaveAllAsync (
    folderName As String
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The absolute or relative path to the folder where to save the attachments.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if all attachments were successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | folderName is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

AttachmentCollection Class
SaveAllAsync Overload
MailBee.Mime Namespace


AttachmentCollection.SaveAllAsync Method (String, Boolean)

AttachmentCollectionSaveAllAsync Method (String, Boolean)
async/await version of SaveAll(String, Boolean).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveAllAsync(
    string folderName,
    bool ignoreInlineAttachments
)
Public Function SaveAllAsync (
    folderName As String,
    ignoreInlineAttachments As Boolean
) As Task(Of Boolean)

Parameters

folderName
Type: SystemString
The absolute or relative path to the folder where to save the attachments.
ignoreInlineAttachments
Type: SystemBoolean
If true, only real attachments (not inline) will be saved; otherwise, both inline and not inline attachments will be saved.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if all attachments were successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | folderName is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An error occurred and ThrowExceptions is true.
See Also

Reference

AttachmentCollection Class
SaveAllAsync Overload
MailBee.Mime Namespace


AttachmentCollection Properties

AttachmentCollection Properties

The AttachmentCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Public property | InlineCount | Returns the number of inline attachments in the collection.
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets or sets the Attachment object at the specified zero-based index in the collection.
 | ItemString | Gets the Attachment object in the collection by the specified filename.
 | LastResult | Gets a numeric code of the last error.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.InlineCount Property

AttachmentCollectionInlineCount Property
Returns the number of inline attachments in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int InlineCount { get; }
Public ReadOnly Property InlineCount As Integer
    Get

Property Value

Type: Int32
The count of the attachments having IsInline set to true.
Remarks
To get the count of real (not inline) attachments, use msg.Attachments.Count - msg.Attachments.InlineCount
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.Item Property

AttachmentCollectionItem Property
Overload List
Name | Description
ItemInt32 | Gets or sets the Attachment object at the specified zero-based index in the collection.
ItemString | Gets the Attachment object in the collection by the specified filename.
Top
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace


AttachmentCollection.Item Property (Int32)

AttachmentCollectionItem Property (Int32)
Gets or sets the Attachment object at the specified zero-based index in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Attachment this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As Attachment
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index number of the attachment in the collection.

Property Value

Type: Attachment
An Attachment object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and saves the first attachment to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// When there are any attachments...
if (msg.Attachments.Count > 0)
{
    // Get the attachment by its index.
    Attachment attach = msg.Attachments[0];

    // Save the attachment to folder.
    attach.SaveToFolder(@"C:\Temp", true);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' When there are any attachments...
If msg.Attachments.Count > 0 Then
    ' Get the attachment by its index.
    Dim attach As Attachment = msg.Attachments(0)

    ' Save the attachment to the folder.
    attach.SaveToFolder("C:\Temp", True)
End If
See Also

Reference

AttachmentCollection Class
Item Overload
MailBee.Mime Namespace
AttachmentCollectionItemString


AttachmentCollection.Item Property (String)

AttachmentCollectionItem Property (String)
Gets the Attachment object in the collection by the specified filename.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Attachment this[
    string filename
] { get; }
Public ReadOnly Default Property Item (
    filename As String
) As Attachment
    Get

Parameters

filename
Type: SystemString
The unique filename of the attachment in the collection (as returned by the Filename property).

Property Value

Type: Attachment
An Attachment object having the specified unique filename, or a null reference (Nothing in Visual Basic) if the attachment with the specified unique filename does not exist in the collection.
Examples
This sample loads the message from .EML file and saves the specified attachment to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Access the attachment in the collection by the unique name.
Attachment attach = msg.Attachments["my_photo.jpg"];

// When there is an attachment...
if (attach != null)
{
    // Save the attachment to folder.
    attach.SaveToFolder(@"C:\Temp", true);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Access the attachment in the collection by the unique name.
Dim attach As Attachment = msg.Attachments("my_photo.jpg")

' When there is an attachment...
If Not attach Is Nothing Then
    ' Save the attachment to the folder.
    attach.SaveToFolder("C:\Temp", True)
End If
See Also

Reference

AttachmentCollection Class
Item Overload
MailBee.Mime Namespace
AttachmentCollectionItemInt32


AttachmentCollection.LastResult Property

AttachmentCollectionLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
A code number of the last occurred error.

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Examples
The example is available in ThrowExceptions property documentation.
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace
MailBeeErrorCodes
AttachmentCollectionThrowExceptions


AttachmentCollection.ThrowExceptions Property

AttachmentCollectionThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; }
Public ReadOnly Property ThrowExceptions As Boolean
    Get

Property Value

Type: Boolean
true if the Attachment object will throw exceptions on errors; otherwise, false. The default value is true.
Remarks
If this property is set to true and an error occurs, an exception derived from MailBeeException is thrown. Otherwise, the last occurred error is contained in the LastResult property. The list of all error codes is available in the ErrorCodes class overview.
Examples
MailMessage.ThrowExceptions topic.
See Also

Reference

AttachmentCollection Class
MailBee.Mime Namespace
AttachmentCollectionLastResult


CharsetMetaTagProcessing Enumeration

CharsetMetaTagProcessing Enumeration
Defines the available modes which affect processing of META tags during parsing HTML body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum CharsetMetaTagProcessing
Public Enumeration CharsetMetaTagProcessing
Members
Member name | Value | Description
DoNothing | 0 | No modifications.
RemoveCharsetMetaTag | 1 | Remove <META content="xxxxxx; charset=xxxxxx"> tag completely.
SetCorrectCharset | 2 | Replace the value specified in charset parameter of the <META> tag with the target charset which will be used to output data to the client (according to MailMessage.Parser.CharsetConverter settings), or remove this tag completely if the target charset is not specified (the value of MailMessage.Parser.CharsetConverter.StringConversionConfig.ConversionMode is NoConversion).
Remarks

If the HTML body of the message contains META tag with charset information, this may prevent the body from being properly displayed in the client browser if the HTML body content was converted from the original charset to another charset (for instance, if gb2312 (Chinese Simplified) text has been converted into UTF-8 which is a default response encoding of ASP.NET web applications). In such cases, it's recommended to tell MailBee to remove META tag containing charset information (RemoveCharsetMetaTag option).

You can set any of these modes via MailMessage.Parser.CharsetMetaTagMode property.

See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigCharsetMetaTagMode


EmailAddress Class

EmailAddress Class
Provides properties and methods used to parse, examine and construct a single e-mail address.
Inheritance Hierarchy
SystemObject
MailBee.MimeEmailAddress

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EmailAddress
Public Class EmailAddress

The EmailAddress type exposes the following members.

Constructors
 | Name | Description
Public method | EmailAddress | Initializes a new instance of the EmailAddress class
 | EmailAddress(String) | Initializes a new instance of the EmailAddress object with the specified e-mail address.
 | EmailAddress(String, String) | Initializes a new instance of the EmailAddress object from the specified e-mail address and display name.
 | EmailAddress(String, String, String) | Initializes a new instance of the EmailAddress object from the specified e-mail address parts.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | EscapeIdnDomain | Converts domain part of e-mail address string into IDN format.
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | FromIdnAddress | Gets a new EmailAddress object which is a copy of the current object with the domain part converted from IDN format.
 | GetAccountName | Gets the account name of the e-mail address.
 | GetAccountNameFromEmail | Gets the account name of the specified e-mail address as a string.
 | GetDomain | Gets the domain name of the e-mail address.
 | GetDomainFromEmail | Gets the domain name of the specified e-mail address as a string.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Parse | Parses an e-mail address string and returns EmailAddress object which represents the given e-mail addresses.
Public method | ToIdnAddress | Gets a new EmailAddress object which is a copy of the current object with the domain part converted into IDN format.
 | ToString | Returns the e-mail address as a string. (Overrides ObjectToString.)
 | UnescapeIdnDomain | Converts domain part of e-mail address string from IDN format into Unicode.
Top
Operators
Name | Description
(EmailAddress to String) | Defines an implicit conversion of an e-mail address into a string.
Top
Properties
Name | Description
AsString | Gets or sets the full e-mail address (with optional remarks and display name) as a string.
DisplayName | Gets or sets the name which is displayed with the e-mail address.
Email | Gets or sets the actual e-mail address as a string.
Remarks | Contains the additional information (remarks) about the e-mail address.
Top
Remarks

In the most cases, the developer does not need to directly create an EmailAddress object to specify e-mail addresses because the most methods and properties which deal with e-mail addresses also accept string inputs as e-mail address values.

EmailAddress class offers AsString property for this. For instance, to specify MailMessage.From as a string, set msg.From.AsString value (assuming msg is MailMessage instance).

Multiple e-mail addresses (such as the list of To, CC or BCC recipients) can be stored in EmailAddressCollection of EmailAddress objects.

If you need to deal with international e-mail addresses (IDN domains), use FromIdnAddress and ToIdnAddress methods to convert e-mail addresses between human-readable and SMTP-safe formats.

Examples
This sample loads a message from .EML file and displays e-mail address details for each recipient.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every recipient...
foreach (EmailAddress adr in msg.To)
{
    // Show full information about the recipient's e-mail address.
    Console.WriteLine("Recipient name: " + adr.DisplayName);
    Console.WriteLine("Recipient address: " + adr.Email);
    Console.WriteLine("Recipient info: " + adr.Remarks);
    Console.WriteLine("Account name: " + adr.GetAccountName());
    Console.WriteLine("Domain name: " + adr.GetDomain());
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every recipient...
For Each adr As EmailAddress In msg.To
    ' Show full information about the recipient's e-mail address.
    Console.WriteLine("Recipient name: " & adr.DisplayName)
    Console.WriteLine("Recipient address: " & adr.Email)
    Console.WriteLine("Recipient info: " & adr.Remarks)
    Console.WriteLine("Account name: " & adr.GetAccountName())
    Console.WriteLine("Domain name: " & adr.GetDomain())
Next
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeEmailAddressCollection


EmailAddress Constructor

EmailAddress Constructor
Overload List
 | Name | Description
Public method | EmailAddress | Initializes a new instance of the EmailAddress class
 | EmailAddress(String) | Initializes a new instance of the EmailAddress object with the specified e-mail address.
 | EmailAddress(String, String) | Initializes a new instance of the EmailAddress object from the specified e-mail address and display name.
 | EmailAddress(String, String, String) | Initializes a new instance of the EmailAddress object from the specified e-mail address parts.
Top
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress Constructor

EmailAddress Constructor
Initializes a new instance of the EmailAddress class

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress()
Public Sub New
See Also

Reference

EmailAddress Class
EmailAddress Overload
MailBee.Mime Namespace


EmailAddress Constructor (String)

EmailAddress Constructor (String)
Initializes a new instance of the EmailAddress object with the specified e-mail address.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress(
    string email
)
Public Sub New (
    email As String
)

Parameters

email
Type: SystemString
The actual e-mail address (such as johndoe@domain.com).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Remarks
To build an EmailAddress object from the full e-mail address (such as "John Doe, Jr." <jdoe@domain.com>), the developer can use Parse(String) method.
Examples
This sample creates a new instance of the EmailAddress object.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress("john_doe@domain.com");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adr As New EmailAddress("john_doe@domain.com")
See Also

Reference

EmailAddress Class
EmailAddress Overload
MailBee.Mime Namespace
EmailAddressParse(String)


EmailAddress Constructor (String, String)

EmailAddress Constructor (String, String)
Initializes a new instance of the EmailAddress object from the specified e-mail address and display name.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress(
    string email,
    string displayName
)
Public Sub New (
    email As String,
    displayName As String
)

Parameters

email
Type: SystemString
The actual e-mail address (such as johndoe@domain.com).
displayName
Type: SystemString
The name which is displayed with the actual e-mail address (such as John Doe). If a null reference (Nothing in Visual Basic), no display name will be assigned to the e-mail address.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new instance of the EmailAddress object.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress("john_doe@domain.com", "John Doe");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adr As New EmailAddress("john_doe@domain.com", "John Doe")
See Also

Reference

EmailAddress Class
EmailAddress Overload
MailBee.Mime Namespace
MailBee.MimeEmailAddressCollection
MailBee.MimeMailMessage


EmailAddress Constructor (String, String, String)

EmailAddress Constructor (String, String, String)
Initializes a new instance of the EmailAddress object from the specified e-mail address parts.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress(
    string email,
    string displayName,
    string remarks
)
Public Sub New (
    email As String,
    displayName As String,
    remarks As String
)

Parameters

email
Type: SystemString
The actual e-mail address (such as johndoe@domain.com).
displayName
Type: SystemString
The name which is displayed with the actual e-mail address (such as John Doe). If a null reference (Nothing in Visual Basic), no display name will be assigned to the e-mail address.
remarks
Type: SystemString
The remarks which are displayed with the actual e-mail address (such as ABC Company). If a null reference (Nothing in Visual Basic), no remarks will be assigned to the e-mail address.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new instance of the EmailAddress object.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress("john_doe@domain.com", "John Doe", "ABC Company");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adr As New EmailAddress("john_doe@domain.com", "John Doe", "ABC Company")
See Also

Reference

EmailAddress Class
EmailAddress Overload
MailBee.Mime Namespace
MailBee.MimeEmailAddressCollection
MailBee.MimeMailMessage


EmailAddress Methods

EmailAddress Methods

The EmailAddress type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | EscapeIdnDomain | Converts domain part of e-mail address string into IDN format.
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | FromIdnAddress | Gets a new EmailAddress object which is a copy of the current object with the domain part converted from IDN format.
 | GetAccountName | Gets the account name of the e-mail address.
 | GetAccountNameFromEmail | Gets the account name of the specified e-mail address as a string.
 | GetDomain | Gets the domain name of the e-mail address.
 | GetDomainFromEmail | Gets the domain name of the specified e-mail address as a string.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Parse | Parses an e-mail address string and returns EmailAddress object which represents the given e-mail addresses.
Public method | ToIdnAddress | Gets a new EmailAddress object which is a copy of the current object with the domain part converted into IDN format.
 | ToString | Returns the e-mail address as a string. (Overrides ObjectToString.)
 | UnescapeIdnDomain | Converts domain part of e-mail address string from IDN format into Unicode.
Top
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress.EscapeIdnDomain Method

EmailAddressEscapeIdnDomain Method
Converts domain part of e-mail address string into IDN format.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string EscapeIdnDomain(
    string email
)
Public Shared Function EscapeIdnDomain (
    email As String
) As String

Parameters

email
Type: SystemString
E-mail address string.

Return Value

Type: String
E-mail address string whose domain part is encoded in Punycode.
Remarks

You can use this method to get an international e-mail address string in SMTP friendly format (called Punycode). It's safe to use this method for addresses which don't contain any international characters, you'll just get the same output as input.

This method converts "user@яндекс.рф" to "user@xn--d1acpjx3f.xn--p1ai". Only domain part (after "@") is converted.

If you have an EmailAddress object (not just a string) which you want to convert, you can use ToIdnAddress method instead.

Note Note
Punycode works for domain part only. See ToIdnAddress method documentation on how to deal with e-mail addresses having international chars in username (not just in domain).
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress.FromIdnAddress Method

EmailAddressFromIdnAddress Method
Gets a new EmailAddress object which is a copy of the current object with the domain part converted from IDN format.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress FromIdnAddress()
Public Function FromIdnAddress As EmailAddress

Return Value

Type: EmailAddress
A reference to newly created EmailAddress which is a copy of the current object with the domain part converted from Punycode.
Remarks

If you have an e-mail address which may potentially have Punycode sequences (ASCII-encoded international characters) in the domain part, you can call this method to make this address human-readable and use the resulting object instead of the original EmailAddress object.

It's safe to use this method for addresses which don't contain any international characters, you'll just get the new object which has the same values as the current one (it will still be a new EmailAddress object, not a reference to the original EmailAddress object).

In case if you have just an e-mail address string, not an EmailAddress object, you can use UnescapeIdnDomain(String) method instead.

See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressCollectionFromIdnAddress


EmailAddress.GetAccountName Method

EmailAddressGetAccountName Method
Gets the account name of the e-mail address.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetAccountName()
Public Function GetAccountName As String

Return Value

Type: String
A string containing the account name of the e-mail address.
Remarks

For instance, the account value will be returned for the account@domain.com e-mail. To get the domain name, the developer should use the GetDomain method.

To extract account name from the supplied e-mail address without creating an instance of EmailAddress class, use GetAccountNameFromEmail(String) method.

Examples
This sample creates a new e-mail address and displays the account name of this address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Add display name.
adr.DisplayName = "John Doe";

// Add e-mail address.
adr.Email = "jdoe@domain.com";

// Add remarks.
adr.Remarks = "ABC Company";

// Show account name string.
Console.WriteLine(adr.GetAccountName());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr As New EmailAddress

' Add display name.
adr.DisplayName = "John Doe"

' Add e-mail address.
adr.Email = "jdoe@domain.com"

' Add remarks.
adr.Remarks = "ABC Company"

' Show account name string.
Console.WriteLine(adr.GetAccountName())
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressGetDomain
EmailAddressGetAccountNameFromEmail(String)


EmailAddress.GetAccountNameFromEmail Method

EmailAddressGetAccountNameFromEmail Method
Gets the account name of the specified e-mail address as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetAccountNameFromEmail(
    string email
)
Public Shared Function GetAccountNameFromEmail (
    email As String
) As String

Parameters

email
Type: SystemString
The e-mail address as a string.

Return Value

Type: String
A string containing the account name of the specified e-mail address.
Remarks

For instance, the account value will be returned for the account@domain.com e-mail address. To get the domain part, the developer should use the GetDomainFromEmail(String) method.

To get account name part or domain part of the existing EmailAddress object, the developer can use GetAccountName or GetDomain methods.

Examples
This sample extracts the account and domain names from the specified e-mail address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

Console.WriteLine(EmailAddress.GetAccountNameFromEmail("user1@domain.com"));
Console.WriteLine(EmailAddress.GetDomainFromEmail("user1@domain.com"));
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Console.WriteLine(EmailAddress.GetAccountNameFromEmail("user1@domain.com"))
Console.WriteLine(EmailAddress.GetDomainFromEmail("user1@domain.com"))
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressGetAccountName
EmailAddressGetDomainFromEmail(String)


EmailAddress.GetDomain Method

EmailAddressGetDomain Method
Gets the domain name of the e-mail address.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetDomain()
Public Function GetDomain As String

Return Value

Type: String
A string containing the domain name of the e-mail address.
Remarks
For instance, the domain value will be returned for the account@domain.com e-mail. To get the account name, the developer should use the GetAccountName method.
Examples
This sample creates a new instance of the EmailAddress object and displays the domain name of this address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Add display name.
adr.DisplayName = "John Doe";

// Add e-mail address.
adr.Email = "jdoe@domain.com";

// Add remarks.
adr.Remarks = "ABC Company";

// Show domain name string.
Console.WriteLine(adr.GetDomain());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr As New EmailAddress

' Add display name.
adr.DisplayName = "John Doe"

' Add e-mail address.
adr.Email = "jdoe@domain.com"

' Add remarks.
adr.Remarks = "ABC Company"

' Show domain name string.
Console.WriteLine(adr.GetDomain())
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressGetAccountName


EmailAddress.GetDomainFromEmail Method

EmailAddressGetDomainFromEmail Method
Gets the domain name of the specified e-mail address as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetDomainFromEmail(
    string email
)
Public Shared Function GetDomainFromEmail (
    email As String
) As String

Parameters

email
Type: SystemString
The e-mail address as a string.

Return Value

Type: String
A string containing the domain name of the specified e-mail address.
Remarks

For instance, the domain value will be returned for the account@domain.com e-mail address. To get the account name from specified e-mail address the developer should use the GetAccountNameFromEmail(String) method of the EmailAddress object.

To get an account name part or domain part of the existing EmailAddress object, the developer can use GetAccountName or GetDomain methods.

Examples
This sample extracts the account and domain names from the specified e-mail address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

Console.WriteLine(EmailAddress.GetAccountNameFromEmail("user1@domain.com"));
Console.WriteLine(EmailAddress.GetDomainFromEmail("user1@domain.com"));
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Console.WriteLine(EmailAddress.GetAccountNameFromEmail("user1@domain.com"))
Console.WriteLine(EmailAddress.GetDomainFromEmail("user1@domain.com"))
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressGetDomain
EmailAddressGetAccountNameFromEmail(String)


EmailAddress.Parse Method

EmailAddressParse Method
Parses an e-mail address string and returns EmailAddress object which represents the given e-mail addresses.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static EmailAddress Parse(
    string addressString
)
Public Shared Function Parse (
    addressString As String
) As EmailAddress

Parameters

addressString
Type: SystemString
The full e-mail address string (with optional remarks and friendly name) to parse.

Return Value

Type: EmailAddress
EmailAddress object representing addressString address.
Examples
This sample creates a new instance of EmailAddress object from string.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = EmailAddress.Parse("User <user@domain.com>");
Console.WriteLine(adr.DisplayName);
Console.WriteLine(adr.Email);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adr As EmailAddress = EmailAddress.Parse("User <user@domain.com>")
Console.WriteLine(adr.DisplayName)
Console.WriteLine(adr.Email)
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress.ToIdnAddress Method

EmailAddressToIdnAddress Method
Gets a new EmailAddress object which is a copy of the current object with the domain part converted into IDN format.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress ToIdnAddress()
Public Function ToIdnAddress As EmailAddress

Return Value

Type: EmailAddress
A reference to newly created EmailAddress which is a copy of the current object with the domain part converted into Punycode.
Remarks

If you have an e-mail address which may potentially have international characters in the domain part, you should call this method to make this address safe for SMTP servers and use the resulting object instead of the original EmailAddress object.

It's safe to use this method for addresses which don't contain any international characters, you'll just get the new object which has the same values as the current one (it will still be a new EmailAddress object, not a reference to the original EmailAddress object).

In case if you have just an e-mail address string, not an EmailAddress object, you can use EscapeIdnDomain(String) method instead.

Note Note
Punycode works for domain part only. If you want to send to an e-mail address having international chars in username (not just in domain), you need to set RequestEncoding property to UTF8. Still no guarantee this will work as many SMTP servers can't deal with international characters in an e-mail address. When they support this, they usually expose UTF8SMTP or SMTPUTF8 capability in EHLO response.
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressCollectionToIdnAddress


EmailAddress.ToString Method

EmailAddressToString Method
Returns the e-mail address as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
A string containing the full e-mail address (including display name and remarks if any).
Remarks
The return value of this method is equivalent to the AsString property value. However, with AsString property, the developer can both get and set the e-mail address.
Examples
This sample creates the new instance of the EmailAddress object and converts it into a string.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Set the display name.
adr.DisplayName = "John Doe";

// Set the e-mail address.
adr.Email = "jdoe@domain.com";

// Set the remarks.
adr.Remarks = "ABC Company";

// Show full e-mail address.
Console.WriteLine(adr.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr As New EmailAddress

' Set the display name.
adr.DisplayName = "John Doe"

' Set the e-mail address.
adr.Email = "jdoe@domain.com"

' Set the remarks.
adr.Remarks = "ABC Company"

' Show full e-mail address.
Console.WriteLine(adr.ToString())
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressAsString
EmailAddressEmail
EmailAddressDisplayName


EmailAddress.UnescapeIdnDomain Method

EmailAddressUnescapeIdnDomain Method
Converts domain part of e-mail address string from IDN format into Unicode.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string UnescapeIdnDomain(
    string email
)
Public Shared Function UnescapeIdnDomain (
    email As String
) As String

Parameters

email
Type: SystemString
E-mail address string with domain part in Punycode format.

Return Value

Type: String
E-mail address string whose domain part is not encoded in Punycode.
Remarks

You can use this method to convert e-mail address string you received from external sources (such as in e-incoming mails) back to human-readable format. It's safe to use this method for addresses which don't contain any Punycode sequences, you'll just get the same output as input.

This method converts "user@xn--d1acpjx3f.xn--p1ai" to "user@яндекс.рф". Only domain part (after "@") is converted.

If you have an EmailAddress object (not just a string) which you want to convert, you can use FromIdnAddress method instead.

See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress Type Conversions

EmailAddress Type Conversions

The EmailAddress type exposes the following members.

Operators
Name | Description
(EmailAddress to String) | Defines an implicit conversion of an e-mail address into a string.
Top
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress Implicit Conversion (EmailAddress to String)

EmailAddress Conversion (EmailAddress to String)
Defines an implicit conversion of an e-mail address into a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static implicit operator string (
    EmailAddress email
)
Public Shared Widening Operator CType (
    email As EmailAddress
) As String

Parameters

email
Type: MailBee.MimeEmailAddress
The e-mail address to convert into a string.

Return Value

Type: String
A string containing the full e-mail address (including display name and remarks if any), or a null reference (Nothing in Visual Basic) if email is null.
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress Properties

EmailAddress Properties

The EmailAddress type exposes the following members.

Properties
Name | Description
AsString | Gets or sets the full e-mail address (with optional remarks and display name) as a string.
DisplayName | Gets or sets the name which is displayed with the e-mail address.
Email | Gets or sets the actual e-mail address as a string.
Remarks | Contains the additional information (remarks) about the e-mail address.
Top
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace


EmailAddress.AsString Property

EmailAddressAsString Property
Gets or sets the full e-mail address (with optional remarks and display name) as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AsString { get; set; }
Public Property AsString As String
    Get
    Set

Property Value

Type: String
A string containing all the full e-mail address (including display name and remarks if availalble).
Remarks
Typical values you can assign to this property:
  • jdoe@domain.com
  • <jdoe@domain.com>
  • John Doe <jdoe@domain.com>
  • "John Doe, Jr." <jdoe@domain.com>
  • "John Doe, Jr." <jdoe@domain.com> (ABC Company)
Once this property is set, the DisplayName, Email and Remarks property values will be updated as well.
Examples
This sample creates a new instance of the EmailAddress object and displays the actual e-mail address part (without display name, etc).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Set e-mail.
adr.AsString = "\"John Doe\" <jdoe@domain.com>";

// Show the actual e-mail address without any additional information.
Console.WriteLine(adr.Email);

// As a result, "jdoe@domain.com" string will be printed in the console window.
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr = New EmailAddress

' Set e-mail.
adr.AsString = """John Doe"" <jdoe@domain.com>"

' Show the actual e-mail address without any additional information.
Console.WriteLine(adr.Email)

' As a result, "jdoe@domain.com" string will be printed in the console window.
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressEmail
EmailAddressDisplayName


EmailAddress.DisplayName Property

EmailAddressDisplayName Property
Gets or sets the name which is displayed with the e-mail address.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DisplayName { get; set; }
Public Property DisplayName As String
    Get
    Set

Property Value

Type: String
A string containing the display name of the current e-mail address. The default value is an empty string.
Remarks
For instance, if the full e-mail address string is Support Team <support@domain.com> (My Company), the Support Team is a display name.
Examples
This sample creates a new instance of the EmailAddress object and displays the full address (including display name).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Add display name.
adr.DisplayName = "John Doe";

// Add e-mail address.
adr.Email = "doe@domain.com";

// Add remarks.
adr.Remarks = "ABC Company";

// Show entire e-mail address string.
Console.WriteLine(adr.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr As New EmailAddress

' Add display name.
adr.DisplayName = "John Doe"

' Add e-mail address.
adr.Email = "doe@domain.com"

' Add remarks.
adr.Remarks = "ABC Company"

' Show entire e-mail address string.
Console.WriteLine(adr.ToString())
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressAsString
EmailAddressEmail


EmailAddress.Email Property

EmailAddressEmail Property
Gets or sets the actual e-mail address as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Email { get; set; }
Public Property Email As String
    Get
    Set

Property Value

Type: String
A string containing the actual e-mail address (without DisplayName and Remarks).
Remarks

For instance, if the full e-mail address string is Support Team <support@domain.com> (My Company), the actual e-mail address is support@domain.com.

If you need to deal with international e-mail addresses (IDN domains), consider FromIdnAddress and ToIdnAddress methods.

Examples
This sample creates a new instance of the EmailAddress object and displays the full address (including e-mail address).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Add display name.
adr.DisplayName = "John Doe";

// Add e-mail address.
adr.Email = "doe@domain.com";

// Add remarks.
adr.Remarks = "ABC Company";

// Show entire e-mail address string.
Console.WriteLine(adr.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr As New EmailAddress

' Add display name.
adr.DisplayName = "John Doe"

' Add e-mail address.
adr.Email = "doe@domain.com"

' Add remarks.
adr.Remarks = "ABC Company"

' Show entire e-mail address string.
Console.WriteLine(adr.ToString())
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressAsString
EmailAddressDisplayName


EmailAddress.Remarks Property

EmailAddressRemarks Property
Contains the additional information (remarks) about the e-mail address.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Remarks { get; set; }
Public Property Remarks As String
    Get
    Set

Property Value

Type: String
A string containing the remarks about e-mail address.
Remarks
For instance, if the full e-mail address string is Support Team <support@domain.com> (My Company), the remarks are My Company.
Examples
This sample creates a new instance of the EmailAddress object and displays the full address (including display name and remarks).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddress adr = new EmailAddress();

// Add display name.
adr.DisplayName = "John Doe";

// Add e-mail address.
adr.Email = "doe@domain.com";

// Add remarks.
adr.Remarks = "ABC Company";

// Show entire e-mail address string.
Console.WriteLine(adr.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create new EmailAddress object.
Dim adr As New EmailAddress

' Add display name.
adr.DisplayName = "John Doe"

' Add e-mail address.
adr.Email = "doe@domain.com"

' Add remarks.
adr.Remarks = "ABC Company"

' Show entire e-mail address string.
Console.WriteLine(adr.ToString())
See Also

Reference

EmailAddress Class
MailBee.Mime Namespace
EmailAddressAsString
EmailAddressEmail


EmailAddressCollection Class

EmailAddressCollection Class
Provides properties and methods for managing and examining the collection of the EmailAddress objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeEmailAddressCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class EmailAddressCollection : CollectionBase
Public Class EmailAddressCollection
    Inherits CollectionBase

The EmailAddressCollection type exposes the following members.

Constructors
 | Name | Description
Public method | EmailAddressCollection | Initializes a new instance of the EmailAddressCollection class
 | EmailAddressCollection(String) | Initializes a new EmailAddressCollection instance from a string containing e-mail addresses.
Top
Methods
 | Name | Description
 | Add(String) | Adds the specified e-mail address to the collection.
 | Add(EmailAddress) | Adds the specified EmailAddress object to the collection.
 | Add(EmailAddressCollection) | Adds the list of the e-mail addresses specified as EmailAddressCollection to the current collection.
 | Add(String, String) | Adds the e-mail address (specified as actual e-mail address and display name parts) to the collection.
 | Add(String, String, String) | Adds the e-mail address (specified as actual e-mail address, display name and remarks parts) to the collection.
 | AddFromString | Adds the specified full e-mail addresses (including display name if any) to the collection.
 | Clear | Clears the entire collection of the e-mail addresses.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | FromIdnAddress | Gets a new EmailAddress object which is a copy of the current object with the domain part of each e-mail address converted from IDN format.
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Parse | Creates a new EmailAddressCollection instance from the specified string containing the list of e-mail addresses.
 | Remove | Removes the specified e-mail address from the collection.
 | RemoveAt | Removes the EmailAddress object having the the specified zero-based index from the collection.
Public method | ToIdnAddress | Gets a new EmailAddressCollection object which is a copy of the current object with the domain part of each e-mail address converted into IDN format.
 | ToString | Returns the string containing all the e-mail addresses in the collection. (Overrides ObjectToString.)
Top
Operators
Name | Description
(EmailAddressCollection to String) | Defines an implicit conversion of an e-mail address collection into a string.
Top
Properties
 | Name | Description
 | AsString | Gets or sets all the e-mail addresses in the collection as a string.
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | Item | Gets the EmailAddress object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks
EmailAddressCollection of EmailAddress objects stores multiple e-mail addresses (such as the list of To, CC or BCC recipients).

In the most cases, the developer does not need to directly create an EmailAddress to specify e-mail addresses because the most methods and properties which deal with e-mail addresses also accept string inputs as e-mail address values.

EmailAddressCollection class offers AsString property for this. For instance, to specify MailMessage.To as a string, set msg.To.AsString value (assuming msg is MailMessage instance).

If you need to deal with international e-mail addresses (IDN domains), use FromIdnAddress and ToIdnAddress methods to convert e-mail addresses between human-readable and SMTP-safe formats.

Examples
This sample loads the message from .EML file and displays the e-mail address of each message recipient.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every recipient...
foreach (EmailAddress adr in msg.To)
{
    // Show full information about the recipient's e-mail address.
    Console.WriteLine("Recipient name: " + adr.DisplayName);
    Console.WriteLine("Recipient address: " + adr.Email);
    Console.WriteLine("Recipient info: " + adr.Remarks);
    Console.WriteLine("Account name: " + adr.GetAccountName());
    Console.WriteLine("Domain name: " + adr.GetDomain());
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every recipient...
For Each adr As EmailAddress In msg.To
    ' Show full information about the recipient's e-mail address.
    Console.WriteLine("Recipient name: " & adr.DisplayName)
    Console.WriteLine("Recipient address: " & adr.Email)
    Console.WriteLine("Recipient info: " & adr.Remarks)
    Console.WriteLine("Account name: " & adr.GetAccountName())
    Console.WriteLine("Domain name: " & adr.GetDomain())
Next
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeEmailAddress


EmailAddressCollection Constructor

EmailAddressCollection Constructor
Overload List
 | Name | Description
Public method | EmailAddressCollection | Initializes a new instance of the EmailAddressCollection class
 | EmailAddressCollection(String) | Initializes a new EmailAddressCollection instance from a string containing e-mail addresses.
Top
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection Constructor

EmailAddressCollection Constructor
Initializes a new instance of the EmailAddressCollection class

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection()
Public Sub New
See Also

Reference

EmailAddressCollection Class
EmailAddressCollection Overload
MailBee.Mime Namespace


EmailAddressCollection Constructor (String)

EmailAddressCollection Constructor (String)
Initializes a new EmailAddressCollection instance from a string containing e-mail addresses.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection(
    string emails
)
Public Sub New (
    emails As String
)

Parameters

emails
Type: SystemString
The string containing the list of the e-mail addresses delimited with comma (,) or semicolon (;). The e-mail addresses may include display names or remarks.
Examples
This sample creates a new collection of the e-mail addresses and displays each address in this collection.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddressCollection adrs = new EmailAddressCollection("jdoe@domain1.com, some one <someone@domain2.com>, me@host.com (Comment)");
foreach (EmailAddress address in adrs)
{
    Console.WriteLine(address.Email);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adrs As EmailAddressCollection = New EmailAddressCollection("jdoe@domain1.com, some one <someone@domain2.com>, me@host.com (Comment)")
For Each address As EmailAddress In adrs
    Console.WriteLine(address.Email)
Next
See Also

Reference

EmailAddressCollection Class
EmailAddressCollection Overload
MailBee.Mime Namespace
EmailAddressCollectionAsString


EmailAddressCollection Methods

EmailAddressCollection Methods

The EmailAddressCollection type exposes the following members.

Methods
 | Name | Description
 | Add(String) | Adds the specified e-mail address to the collection.
 | Add(EmailAddress) | Adds the specified EmailAddress object to the collection.
 | Add(EmailAddressCollection) | Adds the list of the e-mail addresses specified as EmailAddressCollection to the current collection.
 | Add(String, String) | Adds the e-mail address (specified as actual e-mail address and display name parts) to the collection.
 | Add(String, String, String) | Adds the e-mail address (specified as actual e-mail address, display name and remarks parts) to the collection.
 | AddFromString | Adds the specified full e-mail addresses (including display name if any) to the collection.
 | Clear | Clears the entire collection of the e-mail addresses.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | FromIdnAddress | Gets a new EmailAddress object which is a copy of the current object with the domain part of each e-mail address converted from IDN format.
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Parse | Creates a new EmailAddressCollection instance from the specified string containing the list of e-mail addresses.
 | Remove | Removes the specified e-mail address from the collection.
 | RemoveAt | Removes the EmailAddress object having the the specified zero-based index from the collection.
Public method | ToIdnAddress | Gets a new EmailAddressCollection object which is a copy of the current object with the domain part of each e-mail address converted into IDN format.
 | ToString | Returns the string containing all the e-mail addresses in the collection. (Overrides ObjectToString.)
Top
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection.Add Method

EmailAddressCollectionAdd Method
Adds an e-mail address or addresses to the collection.
Overload List
Name | Description
Add(String) | Adds the specified e-mail address to the collection.
Add(EmailAddress) | Adds the specified EmailAddress object to the collection.
Add(EmailAddressCollection) | Adds the list of the e-mail addresses specified as EmailAddressCollection to the current collection.
Add(String, String) | Adds the e-mail address (specified as actual e-mail address and display name parts) to the collection.
Add(String, String, String) | Adds the e-mail address (specified as actual e-mail address, display name and remarks parts) to the collection.
Top
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection.Add Method (String)

EmailAddressCollectionAdd Method (String)
Adds the specified e-mail address to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    string email
)
Public Sub Add (
    email As String
)

Parameters

email
Type: SystemString
The string containing the actual e-mail address (such as user@domain.com).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Remarks
To add a full e-mail address (such as "John Doe, Jr." <jdoe@domain.com>), the developer can use AddFromString(String) method.
Examples
This sample creates a new message and adds a recipient to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add a new mail address to the "To:" collection.
msg.To.Add("john_doe@domain.com");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add a new mail address to the "To:" collection.
msg.To.Add("john_doe@domain.com")
See Also

Reference

EmailAddressCollection Class
Add Overload
MailBee.Mime Namespace
EmailAddressCollectionAddFromString(String)


EmailAddressCollection.Add Method (EmailAddress)

EmailAddressCollectionAdd Method (EmailAddress)
Adds the specified EmailAddress object to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    EmailAddress address
)
Public Sub Add (
    address As EmailAddress
)

Parameters

address
Type: MailBee.MimeEmailAddress
The EmailAddress object to be added.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | address is a null reference (Nothing in Visual Basic).
Examples
This sample loads creates new message and adds a recipient to this message as a new EmailAddress object.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();

// Set a new e-mail address.
EmailAddress adr = new EmailAddress("john_doe@domain.com");

// Add the e-mail address to the list of the recipients.
msg.To.Add(adr);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage

' Set a new e-mail address.
Dim adr As EmailAddress = New EmailAddress("john_doe@domain.com")

' Add the e-mail address to the list of the recipients.
msg.To.Add(adr)
See Also

Reference

EmailAddressCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeEmailAddress


EmailAddressCollection.Add Method (EmailAddressCollection)

EmailAddressCollectionAdd Method (EmailAddressCollection)
Adds the list of the e-mail addresses specified as EmailAddressCollection to the current collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    EmailAddressCollection addresses
)
Public Sub Add (
    addresses As EmailAddressCollection
)

Parameters

addresses
Type: MailBee.MimeEmailAddressCollection
The EmailAddressCollection object containing the list of the e-mail addresses to be added.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | addresses is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new collection of the e-mail addresses and populates it with some addresses, loads the message from .EML file, and adds this collection to the message recipients collection.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddressCollection adrs = new EmailAddressCollection();
adrs.AddFromString("User1 <user1@domain.com>");
adrs.Add("user2@domain.com");

MailMessage msg = new MailMessage();
msg.To.Add(adrs);
foreach (EmailAddress adr in adrs)
{
    Console.WriteLine(adr.Email);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adrs = New EmailAddressCollection
adrs.AddFromString("User1 <user1@domain.com>")
adrs.Add("user2@domain.com")

Dim msg As New MailMessage
msg.To.Add(adrs)
For Each adr As EmailAddress In adrs
    Console.WriteLine(adr.Email)
Next
See Also

Reference

EmailAddressCollection Class
Add Overload
MailBee.Mime Namespace
EmailAddressCollectionAsString


EmailAddressCollection.Add Method (String, String)

EmailAddressCollectionAdd Method (String, String)
Adds the e-mail address (specified as actual e-mail address and display name parts) to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    string email,
    string name
)
Public Sub Add (
    email As String,
    name As String
)

Parameters

email
Type: SystemString
The actual e-mail address (such as JohnDoe@domain.com).
name
Type: SystemString
The name which is displayed with the actual e-mail address (such as John Doe). If a null reference (Nothing in Visual Basic), no display name will be assigned to the e-mail address.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new message and adds a recipient to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add a new mail address to the collection.
msg.To.Add("jdoe@domain.com", "John Doe");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add a new mail address to the collection.
msg.To.Add("jdoe@domain.com", "John Doe")
See Also

Reference

EmailAddressCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeEmailAddress


EmailAddressCollection.Add Method (String, String, String)

EmailAddressCollectionAdd Method (String, String, String)
Adds the e-mail address (specified as actual e-mail address, display name and remarks parts) to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    string email,
    string name,
    string remarks
)
Public Sub Add (
    email As String,
    name As String,
    remarks As String
)

Parameters

email
Type: SystemString
The actual e-mail address (such as JohnDoe@domain.com).
name
Type: SystemString
The name which is displayed with the actual e-mail address (such as John Doe). If a null reference (Nothing in Visual Basic), no display name will be assigned to the e-mail address.
remarks
Type: SystemString
The remarks which are displayed with the actual e-mail address (such as ABC Company). If a null reference (Nothing in Visual Basic), no remarks will be assigned to the e-mail address.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new message and adds a recipient to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add a new mail address to the collection.
msg.To.Add("jdoe@domain.com", "John Doe", "ABC Company");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add a new mail address to the collection.
msg.To.Add("jdoe@domain.com", "John Doe", "ABC Company")
See Also

Reference

EmailAddressCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeEmailAddress


EmailAddressCollection.AddFromString Method

EmailAddressCollectionAddFromString Method
Adds the specified full e-mail addresses (including display name if any) to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddFromString(
    string addressString
)
Public Sub AddFromString (
    addressString As String
)

Parameters

addressString
Type: SystemString
The string containing the full e-mail addresses delimited with comma (,) or semicolon (;).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | addressString is a null reference (Nothing in Visual Basic).
Remarks

For instance, if the string is "John Doe" <j.doe@domain.com> (ABC Company), a single EmailAddress object will be appended to the collection and its DisplayName property will be set to John Doe, Remarks property will be set to ABC Company, and the Email property will be set to j.doe@domain.com value.

Examples
This sample creates the new message and adds the new recipient's e-mail address to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add the mail address to the collection.
msg.To.AddFromString("John Doe <jdoe@domain.com> (ABC Company)");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add the mail address to the collection.
msg.To.AddFromString("John Doe <jdoe@domain.com> (ABC Company)")
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
EmailAddressCollectionAsString
EmailAddressParse(String)


EmailAddressCollection.Clear Method

EmailAddressCollectionClear Method
Clears the entire collection of the e-mail addresses.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear()
Public Sub Clear
Remarks
Removes all EmailAddress objects from the collection.
Examples
This sample loads the message from .EML file and removes all the message recipients:
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();

msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all recipients from the message.
msg.To.Clear();
msg.Cc.Clear();
msg.Bcc.Clear();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all recipients from the message.
msg.To.Clear()
msg.Cc.Clear()
msg.Bcc.Clear()
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
MailMessageClear(MessageElements)


EmailAddressCollection.FromIdnAddress Method

EmailAddressCollectionFromIdnAddress Method
Gets a new EmailAddress object which is a copy of the current object with the domain part of each e-mail address converted from IDN format.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection FromIdnAddress()
Public Function FromIdnAddress As EmailAddressCollection

Return Value

Type: EmailAddressCollection
A reference to newly created EmailAddressCollection which is a copy of the current object with the domain part of each e-mail address converted from Punycode.
Remarks

If you have an e-mail address which may potentially have Punycode sequences (ASCII-encoded international characters) in the domain part, you can call this method to make this address human-readable and use the resulting object instead of the original EmailAddressCollection object. See more at FromIdnAddress topic.

See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection.Parse Method

EmailAddressCollectionParse Method
Creates a new EmailAddressCollection instance from the specified string containing the list of e-mail addresses.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static EmailAddressCollection Parse(
    string addressString
)
Public Shared Function Parse (
    addressString As String
) As EmailAddressCollection

Parameters

addressString
Type: SystemString
The string specifying the list of the e-mail addresses delimited with comma (,) or semicolon (;).

Return Value

Type: EmailAddressCollection
EmailAddressCollection object representing addressString addresses.
Examples
This sample creates a new collection of full e-mail addresses and displays each actual e-mail address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddressCollection adrs =
    EmailAddressCollection.Parse(@"User1 <user1@domain.com>, user2@domain.com");
foreach (EmailAddress adr in adrs)
{
    Console.WriteLine(adr.Email);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adrs As EmailAddressCollection = _
    EmailAddressCollection.Parse("User1 <user1@domain.com>, user2@domain.com")
For Each adr As EmailAddress In adrs
    Console.WriteLine(adr.Email)
Next
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
EmailAddressCollectionEmailAddressCollection(String)


EmailAddressCollection.Remove Method

EmailAddressCollectionRemove Method
Removes the specified e-mail address from the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Remove(
    string email
)
Public Sub Remove (
    email As String
)

Parameters

email
Type: SystemString
Actual e-mail address to be deleted (i.e. user@domain.com).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | email is a null reference (Nothing in Visual Basic).
Remarks

If the specified e-mail address appears multiple times in the collection, all such entries will be removed.

To remove the e-mail address from the collection by the index, the developer should use RemoveAt(Int32) method.

Examples
This sample adds some e-mail addresses into To: field and then removes one of them.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();

msg.To.Add("user1@domain.com");
msg.To.Add("user2@domain.com", "User 2");
msg.To.Add("user3@domain.com", null, "User 3");

Console.WriteLine(msg.To.ToString());

msg.To.Remove("user2@domain.com");

Console.WriteLine(msg.To.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage

msg.To.Add("user1@domain.com")
msg.To.Add("user2@domain.com", "User 2")
msg.To.Add("user3@domain.com", Nothing, "User 3")

Console.WriteLine(msg.To.ToString())

msg.To.Remove("user2@domain.com")

Console.WriteLine(msg.To.ToString())
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
EmailAddressCollectionRemoveAt(Int32)


EmailAddressCollection.RemoveAt Method

EmailAddressCollectionRemoveAt Method
Removes the EmailAddress object having the the specified zero-based index from the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index number of the e-mail address in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and removes the first recipient's e-mail address.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// If there are any recipients...
if (msg.To.Count > 0)
{
    // Remove the first recipient.
    msg.To.RemoveAt(0);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' If there are any recipients...
If (msg.To.Count > 0) Then
    ' Remove the first recipient.
    msg.To.RemoveAt(0)
End If
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
EmailAddressCollectionRemove(String)


EmailAddressCollection.ToIdnAddress Method

EmailAddressCollectionToIdnAddress Method
Gets a new EmailAddressCollection object which is a copy of the current object with the domain part of each e-mail address converted into IDN format.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ToIdnAddress()
Public Function ToIdnAddress As EmailAddressCollection

Return Value

Type: EmailAddressCollection
A reference to newly created EmailAddressCollection which is a copy of the current object with the domain part of each e-mail address converted into Punycode.
Remarks

If you have an e-mail address collection which may potentially have international characters in the domain part of its contained addresses, you should call this method to make this address safe for SMTP servers and use the resulting object instead of the original EmailAddressCollection object. See more at ToIdnAddress topic.

See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection.ToString Method

EmailAddressCollectionToString Method
Returns the string containing all the e-mail addresses in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override string ToString()
Public Overrides Function ToString As String

Return Value

Type: String
The comma-separated list of the full e-mail addresses (with optional friendly names and remarks) in the collection.
Remarks
By default, the e-mail addresses are delimited with comma (",") character. See AsString topic on how to change the delimiter to semicolon (;).
Examples
This sample creates the new collection of the e-mail addresses and displays this collection as string.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddressCollection adrs = new EmailAddressCollection();
adrs.AddFromString("jdoe@domain1.com");
adrs.AddFromString("some one <someone@domain2.com>");
adrs.AddFromString("me@host.com (Comment)");
Console.WriteLine(adrs.ToString());

// Output: jdoe@domain1.com, "some one" <someone@domain2.com>, me@host.com (Comment)
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adrs = New EmailAddressCollection
adrs.AddFromString("jdoe@domain1.com")
adrs.AddFromString("some one <someone@domain2.com>")
adrs.AddFromString("me@host.com (Comment)")
Console.WriteLine(adrs.ToString())

' Output: jdoe@domain1.com, "some one" <someone@domain2.com>, me@host.com (Comment)
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
EmailAddressCollectionAsString


EmailAddressCollection Type Conversions

EmailAddressCollection Type Conversions

The EmailAddressCollection type exposes the following members.

Operators
Name | Description
(EmailAddressCollection to String) | Defines an implicit conversion of an e-mail address collection into a string.
Top
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection Implicit Conversion (EmailAddressCollection to String)

EmailAddressCollection Conversion (EmailAddressCollection to String)
Defines an implicit conversion of an e-mail address collection into a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static implicit operator string (
    EmailAddressCollection emails
)
Public Shared Widening Operator CType (
    emails As EmailAddressCollection
) As String

Parameters

emails
Type: MailBee.MimeEmailAddressCollection
The e-mail addresses to convert into a string.

Return Value

Type: String
A string containing all the e-mail addresses in the collection, or a null reference (Nothing in Visual Basic) if emails is null.
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection Properties

EmailAddressCollection Properties

The EmailAddressCollection type exposes the following members.

Properties
 | Name | Description
 | AsString | Gets or sets all the e-mail addresses in the collection as a string.
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | Item | Gets the EmailAddress object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace


EmailAddressCollection.AsString Property

EmailAddressCollectionAsString Property
Gets or sets all the e-mail addresses in the collection as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AsString { get; set; }
Public Property AsString As String
    Get
    Set

Property Value

Type: String
A string containing all the full e-mail addresses in the collection (with display names and remarks if any).
Remarks

Another way of adding e-mail addresses to the collection is using Add(EmailAddress) method.

The e-mail addresses will be delimited with comma (,). However, if the given collection belongs to the MailMessage object (for instance, represents To property), the delimiter in the output string will be either comma (,) or semicolon (;) depending on MailMessage.Builder.AddressDelimeter property value. Anyway, when parsing an e-mail address string rather than building it, both comma and semicolon are recognized as valid delimiters.

Examples
This sample creates a new collection of e-mail addresses and displays each address from this collection.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

EmailAddressCollection adrs = new EmailAddressCollection("jdoe@domain1.com, some one <someone@domain2.com>, me@host.com (Comment)");
adrs.AsString = @"user1@domain.com, ""User 2"" <user2@domain.com>, user3@domain.com (Domain Company, LLC)";
foreach (EmailAddress address in adrs)
{
    Console.WriteLine(address.Email);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim adrs As EmailAddressCollection = New EmailAddressCollection("jdoe@domain1.com, some one <someone@domain2.com>, me@host.com (Comment)")
adrs.AsString = "user1@domain.com, ""User 2"" <user2@domain.com>, user3@domain.com (Domain Company, LLC)"
For Each address As EmailAddress In adrs
    Console.WriteLine(address.Email)
Next
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
EmailAddressCollectionAdd(EmailAddress)


EmailAddressCollection.Item Property

EmailAddressCollectionItem Property
Gets the EmailAddress object at the specified zero-based index in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As EmailAddress
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the e-mail address in the collection.

Property Value

Type: EmailAddress
An EmailAddress object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and displays the e-mail address of each message recipient.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

EmailAddressCollection adr = msg.GetAllRecipients();
for (int i = 0; i < msg.GetAllRecipients().Count; i++)
{
    Console.WriteLine(adr[i]);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

Dim i As Integer
Dim adr As EmailAddressCollection = msg.GetAllRecipients()
For i = 0 To msg.GetAllRecipients().Count
    Console.WriteLine(adr(i))
Next
See Also

Reference

EmailAddressCollection Class
MailBee.Mime Namespace
MailBee.MimeEmailAddress


Header Class

Header Class
Provides properties for examining or setting the name or the value of a single field of the headers section of a MIME part.
Inheritance Hierarchy
SystemObject
MailBee.MimeHeader

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Header
Public Class Header

The Header type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
Name | Gets or sets the name of the message header as a string.
Value | Gets or sets the value of the message header as a string.
Top
Remarks

Each MIME part of the message (including the message itself which is actually a root MIME part) have header section containing of some name-value pairs. Header class represents such a pair. To access the entire collection of MIME part headers, use MimePart.Headers property. To access headers of the message itself, it's easier to use MailMessage.Headers property.

Some examples of header names and values are represented below:

Name | Value
From | John Doe <jdoe@hisdomain.com> (XXX Company)
To | Katy Smith <k.smith@herdomain.com>
Cc | techsupport@ourdomain.com
Subject | Meeting request.
Content-Type | multipart/mixed; boundary="--511842ECA261D"
Date | Thu, 8 Dec 2005 19:27:22 -0500
X-Priority | 3 (Normal)

Examples
This sample loads the message from .EML file and shows all the message headers.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every header...
foreach (Header hdr in msg.Headers)
{
    // Show the header.
    Console.WriteLine(string.Format("Name: {0}; Value: {1}", hdr.Name, hdr.Value));
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every header...
For Each hdr As Header In msg.Headers
    ' Show the header.
    Console.WriteLine(String.Format("Name: {0}; Value: {1}", hdr.Name, hdr.Value))
Next
See Also

Reference

MailBee.Mime Namespace
MailMessageRawHeader
MailBee.MimeMimePart


Header Methods

Header Methods

The Header type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Header Class
MailBee.Mime Namespace


Header Properties

Header Properties

The Header type exposes the following members.

Properties
Name | Description
Name | Gets or sets the name of the message header as a string.
Value | Gets or sets the value of the message header as a string.
Top
See Also

Reference

Header Class
MailBee.Mime Namespace


Header.Name Property

HeaderName Property
Gets or sets the name of the message header as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; set; }
Public Property Name As String
    Get
    Set

Property Value

Type: String
A string containing the name of the message header.
Remarks
Some header names are:
  • Received
  • Date
  • From
  • X-Mailer
  • Reply-To
  • Organization
  • X-Priority
  • Message-ID
  • To
  • CC
  • Subject
  • MIME-Version
  • Content-Type
  • Content-Transfer-Encoding
Examples
The example is available in Header class overview.
See Also

Reference

Header Class
MailBee.Mime Namespace
MailBee.MimeHeaderCollection
MailBee.MimeMailMessage


Header.Value Property

HeaderValue Property
Gets or sets the value of the message header as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Value { get; set; }
Public Property Value As String
    Get
    Set

Property Value

Type: String
A string containing the value of the message header.
Remarks
The examples of the header's names and values are available in Header class overview.
Examples
The example is available in Header class overview.
See Also

Reference

Header Class
MailBee.Mime Namespace
MailBee.MimeHeaderCollection
MailBee.MimeMailMessage


HeaderCollection Class

HeaderCollection Class
Represents a collection of all the headers of a mail message or a MIME part.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeHeaderCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class HeaderCollection : CollectionBase
Public Class HeaderCollection
    Inherits CollectionBase

The HeaderCollection type exposes the following members.

Constructors
 | Name | Description
Public method | HeaderCollection | Initializes a new instance of the HeaderCollection class
Top
Methods
 | Name | Description
 | Add(String, String, Boolean) | Adds a header to the collection.
 | Add(String, String, Boolean, Int32) | Adds a header to the collection at the specified position.
 | Clear | Clears the collection of the headers.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | Exists | Checks whether a header with the given name exists in the collection.
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | Items | Returns the collection of headers having the given name.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Remove | Removes the header from the collection by the given name.
 | RemoveAt | Removes the header from the collection at the given zero-based index.
 | RemoveCustomHeaders | Removes any custom headers from the collection of the message headers.
 | RemoveRouteHeaders | Removes all route headers from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets or sets the Header object in the collection at the specified zero-based index.
 | ItemString | Gets or sets the Header object of the collection by the header name.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks
This collection can be used to examine, modify, add or remove headers to the mail message or its individual parts (such as attachments).

For mail messages, this collection is available through the MailMessage.Headers.

For individual MIME parts, the developer can access headers via MimePart.Headers property.

Attachment and TextBodyPart objects also support MimePart.Headers property.

To get the headers section of the message as string, use MailMessage.RawHeader property. MimePart class also supports such property. Please note that RawHeader properties will return empty string if the source of the message is not available (this is common when you're composing a new message rather than examining an existing one).

Examples
The example is available in Header class overview.
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeHeader


HeaderCollection Constructor

HeaderCollection Constructor
Initializes a new instance of the HeaderCollection class

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection()
Public Sub New
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace


HeaderCollection Methods

HeaderCollection Methods

The HeaderCollection type exposes the following members.

Methods
 | Name | Description
 | Add(String, String, Boolean) | Adds a header to the collection.
 | Add(String, String, Boolean, Int32) | Adds a header to the collection at the specified position.
 | Clear | Clears the collection of the headers.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | Exists | Checks whether a header with the given name exists in the collection.
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | Items | Returns the collection of headers having the given name.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Remove | Removes the header from the collection by the given name.
 | RemoveAt | Removes the header from the collection at the given zero-based index.
 | RemoveCustomHeaders | Removes any custom headers from the collection of the message headers.
 | RemoveRouteHeaders | Removes all route headers from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace


HeaderCollection.Add Method

HeaderCollectionAdd Method
Overload List
Name | Description
Add(String, String, Boolean) | Adds a header to the collection.
Add(String, String, Boolean, Int32) | Adds a header to the collection at the specified position.
Top
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace


HeaderCollection.Add Method (String, String, Boolean)

HeaderCollectionAdd Method (String, String, Boolean)
Adds a header to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    string name,
    string value,
    bool overwrite
)
Public Function Add (
    name As String,
    value As String,
    overwrite As Boolean
) As Boolean

Parameters

name
Type: SystemString
The name of the header.
value
Type: SystemString
The value of the header.
overwrite
Type: SystemBoolean
If true all found headers having the specified name are removed, while only one header will be inserted instead of them; otherwise, another header having the same name will be added.

Return Value

Type: Boolean
true if the header was successfully added; otherwise, false.
Examples
This sample creates a new message and adds a header to this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a MailMessage object.
MailMessage msg = new MailMessage();

// Add a header.
msg.Headers.Add("MyHeader", "Some value for my own header", false);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a MailMessage object.
Dim msg As New MailMessage

' Add a header.
msg.Headers.Add("MyHeader", "Some value for my own header", False)
See Also

Reference

HeaderCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeHeader


HeaderCollection.Add Method (String, String, Boolean, Int32)

HeaderCollectionAdd Method (String, String, Boolean, Int32)
Adds a header to the collection at the specified position.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Add(
    string name,
    string value,
    bool overwrite,
    int index
)
Public Function Add (
    name As String,
    value As String,
    overwrite As Boolean,
    index As Integer
) As Boolean

Parameters

name
Type: SystemString
The name of the header.
value
Type: SystemString
The value of the header.
overwrite
Type: SystemBoolean
If true all found headers having the specified name are removed, while only one header will be inserted instead of them; otherwise, another header having the same name will be added.
index
Type: SystemInt32
The zero-based index of the newly added header in the collection.

Return Value

Type: Boolean
true if the header was successfully added; otherwise, false.
Examples
This sample creates a new message and adds a header at the beginning of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a MailMessage object.
MailMessage msg = new MailMessage();

// Add a header.
msg.Headers.Add("MyHeader", "Some value for my own header", false, 0);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a MailMessage object.
Dim msg As New MailMessage

' Add a header.
msg.Headers.Add("MyHeader", "Some value for my own header", False, 0)
See Also

Reference

HeaderCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeHeader


HeaderCollection.Clear Method

HeaderCollectionClear Method
Clears the collection of the headers.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear()
Public Sub Clear
Examples
This sample loads the message from .EML file and removes all headers from this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all headers.
msg.Headers.Clear();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all headers.
msg.Headers.Clear()
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
MailBee.MimeHeader


HeaderCollection.Exists Method

HeaderCollectionExists Method
Checks whether a header with the given name exists in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Exists(
    string name
)
Public Function Exists (
    name As String
) As Boolean

Parameters

name
Type: SystemString
The name of the header.

Return Value

Type: Boolean
true if the collection contains the header with the specified name; otherwise, false.
Examples
This sample creates the new message and adds a custom header if it does not yet exist.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();
if (!msg.Headers.Exists("X-MyHeader"))
{
    msg.Headers.Add("X-MyHeader", "some value for the header", false);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage
If (Not msg.Headers.Exists("X-MyHeader")) Then
    msg.Headers.Add("X-MyHeader", "some value for the header", False)
End If
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
MailBee.MimeHeader
MailBee.MimeMailMessage


HeaderCollection.Items Method

HeaderCollectionItems Method
Returns the collection of headers having the given name.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection Items(
    string name
)
Public Function Items (
    name As String
) As HeaderCollection

Parameters

name
Type: SystemString
The name of the header.

Return Value

Type: HeaderCollection
A HeaderCollection object containing the headers having the specified name, or a null reference (Nothing in Visual Basic) if such headers do not exist in the collection.
Remarks
This method should be used if the mail message contains several headers with the same name and the developer wants to examine them all. In other cases, it's easier to use ItemString property.
Examples
This sample loads the message from .EML file and displays "Received" headers of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Access the list of "Received" headers.
HeaderCollection receivedHeaders = msg.Headers.Items("Received");

if (receivedHeaders != null)
{
    // For each header...
    foreach (Header hdr in receivedHeaders)
    {
        // Show the name and the value of the header.
        Console.WriteLine(string.Format("{0}: {1}", hdr.Name, hdr.Value));
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Access the list of "Received" headers.
Dim receivedHeaders As HeaderCollection = msg.Headers.Items("Received")

If Not receivedHeaders Is Nothing Then
    ' For each header...
    For Each hdr As Header In receivedHeaders
        ' Show the name and the value of the header.
        Console.WriteLine(String.Format("{0}: {1}", hdr.Name, hdr.Value))
    Next
End If
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
HeaderCollectionItemString
MailBee.MimeHeader


HeaderCollection.Remove Method

HeaderCollectionRemove Method
Removes the header from the collection by the given name.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    string name
)
Public Function Remove (
    name As String
) As Boolean

Parameters

name
Type: SystemString
The name of the header.

Return Value

Type: Boolean
true if the header with the specified name was found and removed; otherwise, false.
Remarks

All headers having the specified name will be removed from the collection. To remove only one header having the specified name the developer should use the RemoveAt(Int32) method.

Examples
This sample loads the message from .EML file and removes Subject header from this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// When specified header exists...
if (msg.Headers["Subject"] != null)
{
    // Remove the specified header.
    msg.Headers.Remove("Subject");
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' When specified header exists...
If Not msg.Headers("Subject") Is Nothing Then
    ' Remove the specified header.
    msg.Headers.Remove("Subject")
End If
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
HeaderCollectionRemoveAt(Int32)


HeaderCollection.RemoveAt Method

HeaderCollectionRemoveAt Method
Removes the header from the collection at the given zero-based index.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index of the message header in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and removes the first header of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// When the first header exists...
if (msg.Headers.Count > 0)
{
    // Remove the first header.
    msg.Headers.RemoveAt(0);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' When the first header exists...
If (msg.Headers.Count > 0) Then
    ' Remove the first header.
    msg.Headers.RemoveAt(0)
End If
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
HeaderCollectionRemove(String)


HeaderCollection.RemoveCustomHeaders Method

HeaderCollectionRemoveCustomHeaders Method
Removes any custom headers from the collection of the message headers.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveCustomHeaders()
Public Sub RemoveCustomHeaders
Remarks
Removes the Header objects with non-standard names from the collection of the message headers. The following headers are standard (and thus will not be removed by this method):
  • BCC
  • CC
  • Content-Type
  • Date
  • From
  • Message-ID
  • MIME-Version
  • Organization
  • Reply-To
  • Return-Path
  • Subject
  • To
  • X-Mailer
  • X-MSMail-Priority
  • X-Priority
Examples
This sample loads the message from .EML file and removes the custom headers from this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all non-standard headers from the collection.
msg.Headers.RemoveCustomHeaders();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all non-standard headers from the collection.
msg.Headers.RemoveCustomHeaders()
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeHeader


HeaderCollection.RemoveRouteHeaders Method

HeaderCollectionRemoveRouteHeaders Method
Removes all route headers from the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveRouteHeaders()
Public Sub RemoveRouteHeaders
Remarks
Removes all Header objects having Return-Path or Received names.
Examples
The following example demonstrates how the all route headers can be removed:
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all route headers.
msg.Headers.RemoveRouteHeaders();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all route headers.
msg.Headers.RemoveRouteHeaders()
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeHeader


HeaderCollection Properties

HeaderCollection Properties

The HeaderCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets or sets the Header object in the collection at the specified zero-based index.
 | ItemString | Gets or sets the Header object of the collection by the header name.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace


HeaderCollection.Item Property

HeaderCollectionItem Property
Overload List
Name | Description
ItemInt32 | Gets or sets the Header object in the collection at the specified zero-based index.
ItemString | Gets or sets the Header object of the collection by the header name.
Top
See Also

Reference

HeaderCollection Class
MailBee.Mime Namespace


HeaderCollection.Item Property (Int32)

HeaderCollectionItem Property (Int32)
Gets or sets the Header object in the collection at the specified zero-based index.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Header this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As Header
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index of the header in the headers collection.

Property Value

Type: Header
A Header object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | If the specified index doesn't exist.
Examples
This sample loads the message from .EML file and displays all headers of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

for (int i = 0; i < msg.Headers.Count; i++)
{
    Console.WriteLine(string.Format("{0}: {1}", msg.Headers[i].Name, msg.Headers[i].Value));
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

Dim i As Integer
For i = 0 To msg.Headers.Count - 1
    Console.WriteLine(String.Format("{0}: {1}", msg.Headers(i).Name, msg.Headers(i).Value))
Next
See Also

Reference

HeaderCollection Class
Item Overload
MailBee.Mime Namespace
MailBee.MimeMailMessage


HeaderCollection.Item Property (String)

HeaderCollectionItem Property (String)
Gets or sets the Header object of the collection by the header name.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string this[
    string name
] { get; set; }
Public Default Property Item (
    name As String
) As String
    Get
    Set

Parameters

name
Type: SystemString
The name of the header. Some examples: To, Content-Type, X-UIDL.

Property Value

Type: String
The Header object representing the header with the specified name, or a null reference (Nothing in Visual Basic) if no such header exists in the collection.
Remarks
If the collection contains several headers with the specified name, the first matching header will be returned. To access multiple headers with the same name, the developer should use Items(String) method.
Examples
This sample loads the message from .EML file and displays the value of Subject: header of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Get the header value by its name.
string subjectHeaderValue = msg.Headers["Subject"];

// If this header exists...
if (subjectHeaderValue != null)
{
    // Show the header of the message.
    Console.WriteLine("Message subject: " + subjectHeaderValue);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Get the header value by its name.
Dim subjectHeaderValue As String = msg.Headers("Subject")

' If this header exists...
If Not subjectHeaderValue Is Nothing Then
    ' Show the header of the message.
    Console.WriteLine("Message subject: " & subjectHeaderValue)
End If
See Also

Reference

HeaderCollection Class
Item Overload
MailBee.Mime Namespace
HeaderCollectionItems(String)
MailBee.MimeHeader


HeaderEncodingOptions Enumeration

HeaderEncodingOptions Enumeration
Defines the available options which affect how message headers are encoded with mail transfer encodings such as Base64 or Quoted-Printable.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum HeaderEncodingOptions
<FlagsAttribute>
Public Enumeration HeaderEncodingOptions
Members
Member name | Value | Description
None | 0 | Use default Quoted-Printable encoding when required.
ForceEncoding | 1 | Force headers encoding even if there are no extended characters in the header.
Base64 | 2 | Use Base64 instead of Quoted-Printable encoding. Base64 encoding is more efficient than Quoted-Printable when header values mainly consist of extended characters. Quoted-Printable is preferred if header values mostly contain standard ASCII characters.
IgnoreAttachments | 4 | Headers of message attachments should NOT be encoded (even if the ForceEncoding flag is set). Useful if the mail reader program used by the message recipients can not properly handle encoded filenames.
Remarks

The MIME standard requires message headers containing extended (non-ASCII) characters be encoded using Base64 or Quoted-Printable mail transfer encodings.

EncodeAllHeaders(Encoding, HeaderEncodingOptions) method can be used to encode the message headers automatically.

To encode individual headers, use GetEncodedHeaderValue(String, String, Encoding, HeaderEncodingOptions) method.

See Also

Reference

MailBee.Mime Namespace
MailMessageEncodeAllHeaders(Encoding, HeaderEncodingOptions)


HtmlMessageAutoSaving Enumeration

HtmlMessageAutoSaving Enumeration
Defines the available modes for automatic saving of the HTML body or related files of the message into WorkingFolder location during parsing the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum HtmlMessageAutoSaving
Public Enumeration HtmlMessageAutoSaving
Members
Member name | Value | Description
NoAutoSave | 0 | Do nothing.
SaveMessageHtmAndRelatedFiles | 1 | Save HTML body of the message into the message.htm file. All related files will be saved into the same location.
SaveMessageMht | 2 | Save HTML body of the message and all related files into a single message.mht file (Web Archive).
AlterHtmlBody | 3 | Save all related objects into MailMessage.Parser.WorkingFolder and replace all CIDs in the message HTML body with relatives URIs (in fact, filenames) pointing to the corresponding related files in WorkingFolder.
Remarks
You can set any of these modes via MailMessage.Parser.AutoSaveHtmlMode property.
Note Note
If you wish to make plain-text messages be saved as HTML files as well (so that it would always be possible to render any e-mail message just by displaying message.htm file, regardless if the message is HTML or plain-text), set MailMessage.Parser.PlainToHtmlMode to IfNoHtml in addition to setting of MailMessage.Parser.AutoSaveHtmlMode.
Note Note
Async methods are not compatible with HTML body autosave. Use methods like SaveHtmlAndRelatedFilesAsync(String) directly.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigAutoSaveHtmlMode


HtmlToPlainAutoConvert Enumeration

HtmlToPlainAutoConvert Enumeration
Defines the available modes which specify when HTML body of a message should automatically be converted into plain text during parsing of this message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum HtmlToPlainAutoConvert
Public Enumeration HtmlToPlainAutoConvert
Members
Member name | Value | Description
IfNoPlain | 0 | Convert when the message does not have a plain text body.
IfHtml | 1 | Convert when the message has an HTML body (if the plain text body exists as well, it will be overwritten).
Never | 2 | HTML body of the message will never be automatically converted into plain text during parsing of this message.
Remarks
You can set any of these mode via MailMessage.Parser.HtmlToPlainMode property.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigHtmlToPlainMode
MessageParserConfigHtmlToPlainOptions


HtmlToPlainConvertOptions Enumeration

HtmlToPlainConvertOptions Enumeration
Defines the available flags which affect how HTML body of a message is converted into plain text.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum HtmlToPlainConvertOptions
<FlagsAttribute>
Public Enumeration HtmlToPlainConvertOptions
Members
Member name | Value | Description
None | 0 | No extra processing.
AddImgAltText | 1 | Alternative text contained in the ALT attribute of the <IMG> tag will be put into plain-text.
WriteImageIfNoAlt | 2 | If alternative text was not set in the <IMG> tag, the image string will be put into plain text.
AddUriForImg | 4 | For each image, its URI will be placed into plain text.
AddUriForAHRef | 8 | The URI contained in the <a href=""> tag will be put into plain-text after the content of this tag. For instance, if HTML was <a href="http://www.afterlogic.com">AfterLogic Corporation</a>, the plain-text version will be AfterLogic Corporation <http://www.afterlogic.com>.
Remarks
You can set any combination of these options via MailMessage.Parser.HtmlToPlainOptions property.

By default (None value), all HTML tags are removed and line terminators are inserted instead of HTML's line terminators such as <br>, <p>, etc.

Note Note
URI is a synonym of an URL.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigHtmlToPlainOptions
MessageParserConfigHtmlToPlainMode


HtmlToSimpleHtmlAutoConvert Enumeration

HtmlToSimpleHtmlAutoConvert Enumeration
Defines the available modes which specify if HTML body of a message should be converted into simple HTML.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum HtmlToSimpleHtmlAutoConvert
Public Enumeration HtmlToSimpleHtmlAutoConvert
Members
Member name | Value | Description
IfHtml | 0 | If the HTML message body exists, it will automatically be converted into simple HTML. The previous HTML body of the message will be overwritten.
Never | 1 | The HTML message body will never be automatically converted into simple HTML.
Remarks

Simple HTML is a plain text representation intended for displaying in HTML container (such as browser) where line terminators are replaced with <br> tags, URIs are high-lighted using <a href="URI"> tags, etc.

For instance, Outlook Express displays simple HTML version of plain text body for those messages which do not have their original HTML body. In other words, simple HTML is an HTML converted into plain-text and then back to HTML.

The developer may consider to render HTML documents into simple HTML format for security reasons (because all potentially dangerous content will be removed from the document).

The developer can set this mode via MailMessage.Parser.HtmlToSimpleHtmlMode property.
Note Note
URI is a synonym of an URL.
Examples
The example is available in MailMessage.Parser.HtmlToSimpleHtmlMode property documentation.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigHtmlToSimpleHtmlMode
MessageParserConfigHtmlToSimpleHtmlOptions


HtmlToSimpleHtmlConvertOptions Enumeration

HtmlToSimpleHtmlConvertOptions Enumeration
Defines the available flags which affect how HTML body of a message should be converted into simple HTML.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum HtmlToSimpleHtmlConvertOptions
<FlagsAttribute>
Public Enumeration HtmlToSimpleHtmlConvertOptions
Members
Member name | Value | Description
None | 0 | No extra processing.
AddImgAltText | 1 | The alternative text (contents of ALT element of IMG tag) will be put in simple HTML in place of this image in the original HTML. If this flag is not set, no mention of the image will be available in the resulting simple HTML.
WriteImageIfNoAlt | 2 | If there is no alternative text for the image, the "image" string will be added as the alternative text. Has no effect if AddImgAltText flag is not specified.
MakeLinkForImg | 4 | Make alternative text of the original image a link to the original image. For example, if the original HTML was <img src="http://www.server.com/picture.gif" alt="Our Picture">, the following simple HTML is produced: <a href="http://www.server.com/picture.gif">Our Picture</a>. Has no effect if AddImgAltText flag is not specified.
Remarks
You can set any combination of these options via MailMessage.Parser.HtmlToSimpleHtmlOptions property.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MessageParserConfigHtmlToSimpleHtmlMode
MessageParserConfigHtmlToSimpleHtmlOptions


ImportBodyOptions Enumeration

ImportBodyOptions Enumeration
Defines the available flags for importing the body of the mail message from a file or URI via LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum ImportBodyOptions
<FlagsAttribute>
Public Enumeration ImportBodyOptions
Members
Member name | Value | Description
None | 0 | Simply overwrite the existing message body with the imported data.
Append | 1 | The imported body will be appended to the existing message body.
PathIsUri | 2 | The path parameter of LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method is URI rather than disk file path. If this option is not set, absolute or relative path on disk is assumed.
ImportRelatedFiles | 4 | The files related to the imported message body (inline pictures, etc) will also be imported (they will appear as inline attachments, having IsInline set to true).
ImportRelatedFilesFromUris | 8 | The files which are referenced in the imported message body via URIs will be downloaded from their web locations and attached to the message. If this flag is not set, only local files will be imported while URI references will be left as-is.
PreferCharsetFromMetaTag | 16 | If sourceEncoding parameter of LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method is set, use it only if charset information is not available in META tag of the HTML data being imported. Has no effect for plain-text data or when sourceEncoding is a null reference (Nothing in Visual Basic).
Remarks
URI is a synonym of an URL.
See Also

Reference

MailBee.Mime Namespace
MailMessageLoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions)


ImportRelatedFilesOptions Enumeration

ImportRelatedFilesOptions Enumeration
Defines the available flags which affect how files related to the HTML body of the mail message are attached to the message by ImportRelatedFiles(ImportRelatedFilesOptions) method.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum ImportRelatedFilesOptions
<FlagsAttribute>
Public Enumeration ImportRelatedFilesOptions
Members
Member name | Value | Description
None | 0 | No additional options.
ImportFromUris | 1 | The files which are referenced in the HTML message body via URIs will be downloaded from their web locations and attached to the message. If this flag is not set, only local files will be imported while URI references will be left as-is.
Remarks
URI is a synonym of an URL.
See Also

Reference

MailBee.Mime Namespace
MailMessageImportRelatedFiles(ImportRelatedFilesOptions)


MailMerge Class

MailMerge Class
Provides properties and methods for creating customized messages based on a template.
Inheritance Hierarchy
SystemObject
MailBee.MimeMailMerge

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailMerge
Public Class MailMerge

The MailMerge type exposes the following members.

Methods
 | Name | Description
 | AddAttachmentPattern | Adds the attachment pattern to the collection of attachment patterns.
Public method | ClearAttachmentPatterns | Clears the collection of the attachments patterns.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Replace(String, String) | Replaces all occurrences of the specified pattern in the message template with the specified actual value.
 | Replace(String, String, MailMergeTargets) | Replaces all occurrences of the specified case-sensitive pattern in the specified parts of the message with the actual value.
Public method | ReplaceAsync(String, String) | async/await version of Replace(String, String).
Public method | ReplaceAsync(String, String, MailMergeTargets) | async/await version of Replace(String, String, MailMergeTargets).
 | Reset | Resets the merged message.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
MergedMessage | Contains the completed mail message which is a result of mail merge operation.
Top
Remarks
MailMerge class is very flexible and can be used for creating of e-mail messages based on a template and data from any source.

However, if such flexibility is not needed and the source of the data is a database, then it's easier to use Smtp.SendMailMerge method.

Examples
This sample defines a template and generates 3 e-mail messages based on it. The template includes both static fields (for instance, From field remains the same for all e-mails in the series) and dynamic patterns which are replaced with actual values for every e-mail generated. Two attachments are added to each message: one static and one pattern-based.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.Collections;
using System.Collections.Specialized;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Create an object to store the list of e-mail addresses and friendly names...
StringDictionary sd = new StringDictionary();

// ...add populate it with some values.
sd.Add("jdoe@domain.com", "John Doe");
sd.Add("kathy@example.com", "Kathy");
sd.Add("mark@company.com", "Mark");

// Set up an e-mail template.
MailMessage msg = new MailMessage();
msg.To.AsString = @"""%%NAME%%"" <%%EMAIL%%>";
msg.From.Email = "john.smith@site.com";
msg.Subject = "Hello, %%NAME%%.";
msg.BodyPlainText = @"Hello, %%NAME%%. Your e-mail is %%EMAIL%%.";
msg.BodyHtmlText = @"<html>
<body>
Hello, <b>%%NAME%%</b>. Your e-mail is <i>%%EMAIL%%</i>.
Attached File: <font color=""red"">%%FILENAME%%</font>
<br>
<img src=""cid:123456"" alt="".NET"">
</body>
</html>";

// The template also includes the attachment which is common for all e-mails in the series...
msg.Attachments.Add(@"C:\Docs\image17b.gif", "logo.gif", "123456");

// ... and the attachment which is unique for each e-mail.
msg.Merge.AddAttachmentPattern(@"C:\Docs\%%FILENAME%%");

// Create array of actual filenames which will substitute %%FILENAME%% pattern in merged e-mails.
string[] strArrays = {"image1.jpg", "image2.gif", "image3.gif"};

// Perform actual mail merge and save the resulting e-mails to disk.
int i = 1;
foreach (DictionaryEntry de in sd)
{
    msg.Merge.Replace(@"%%NAME%%", (string)de.Value);
    msg.Merge.Replace(@"%%FILENAME%%", strArrays[i-1], MailMergeTargets.BodyHtmlText);
    msg.Merge.Replace(@"%%EMAIL%%", (string)de.Key, MailMergeTargets.Recipients |
        MailMergeTargets.Subject | MailMergeTargets.BodyHtmlText | MailMergeTargets.BodyPlainText);

    msg.Merge.MergedMessage.SaveMessage(string.Format(@"C:\Temp\merge{0}.eml", i));

    msg.Merge.Reset();
    i++;
}
' To use the code below, import these namespaces at the top of your code.
Imports System.Collections.Specialized
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Create an object to store the list of e-mail addresses and friendly names...
Dim sd = New StringDictionary

' ...add populate it with some values.
sd.Add("jdoe@domain.com", "John Doe");
sd.Add("kathy@example.com", "Kathy");
sd.Add("mark@company.com", "Mark");

' Set up an e-mail template.
Dim msg As New MailMessage
msg.To.AsString = """%%NAME%%"" <%%EMAIL%%>"
msg.From.Email = "john.smith@site.com"
msg.Subject = "Hello, %%NAME%%."
msg.BodyPlainText = "Hello, %%NAME%%. Your e-mail is %%EMAIL%%. Visit us (www.afterlogic.com)"
msg.BodyHtmlText = "<html>" & VbCrLf & _
    "<body>" & VbCrLf & _
    "Hello, <b>%%NAME%%</b>. Your e-mail is <i>%%EMAIL%%</i>. Visit us <a href=""http://www.afterlogic.com/"">Afterlogic</a>" & VbCrLf & _
    "Attached File: <font color=""red"">%%FILENAME%%</font>" & VbCrLf & _
    "<br>" & VbCrLf & _
    "<img src=""cid:123456"" alt="".NET"">" & VbCrLf & _
    "</body>" & VbCrLf & _
    "</html>"

' The template also includes the attachment which is common for all e-mails in the series...
msg.Attachments.Add("C:\Docs\image17b.gif", "logo.gif", "123456");

msg.Merge.AddAttachmentPattern("%%FILENAME%%")
Dim i As Integer = 1
Dim strArrays As String() = {"C:\Docs\image1.jpg", "C:\Docs\image2.gif", "C:\Docs\image3.gif"}
For Each de As DictionaryEntry In sd
    msg.Merge.Replace("%%NAME%%", de.Value)
    msg.Merge.Replace("%%FILENAME%%", strArrays(i - 1), MailMergeTargets.BodyHtmlText)
    msg.Merge.Replace("%%EMAIL%%", de.Key, MailMergeTargets.Recipients Or _
     MailMergeTargets.Subject Or MailMergeTargets.BodyHtmlText Or MailMergeTargets.BodyPlainText)

    msg.Merge.MergedMessage.SaveMessage(String.Format("C:\Temp\merge{0}.eml", i))

    msg.Merge.Reset()
    i = i + 1
Next
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeMailMergeTargets


MailMerge Methods

MailMerge Methods

The MailMerge type exposes the following members.

Methods
 | Name | Description
 | AddAttachmentPattern | Adds the attachment pattern to the collection of attachment patterns.
Public method | ClearAttachmentPatterns | Clears the collection of the attachments patterns.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Replace(String, String) | Replaces all occurrences of the specified pattern in the message template with the specified actual value.
 | Replace(String, String, MailMergeTargets) | Replaces all occurrences of the specified case-sensitive pattern in the specified parts of the message with the actual value.
Public method | ReplaceAsync(String, String) | async/await version of Replace(String, String).
Public method | ReplaceAsync(String, String, MailMergeTargets) | async/await version of Replace(String, String, MailMergeTargets).
 | Reset | Resets the merged message.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MailMerge Class
MailBee.Mime Namespace


MailMerge.AddAttachmentPattern Method

MailMergeAddAttachmentPattern Method
Adds the attachment pattern to the collection of attachment patterns.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddAttachmentPattern(
    string filenamePattern
)
Public Sub AddAttachmentPattern (
    filenamePattern As String
)

Parameters

filenamePattern
Type: SystemString
The attachment pattern.
Remarks

The attachment pattern is a string (like !filename!) which denotes a placeholder to be replaced with the actual attachment filename during mail merge operation. When Replace(String, String) method is called with the value of pattern parameter equal to the filename pattern previously added with AddAttachmentPattern(String) method, the file denoted by the path specified in actualValue parameter of Replace(String, String) method will be automatically attached.

It's possible to add multiple attachments with the same pattern. For that, in the value which will replace the pattern you'll need to delimit multiple file paths with ";". Or, you can call AddAttachmentPattern(String) method multiple times to set several different attachment patterns.

Note Note
Pattern of the message template is case-sensitive! For instance, if the pattern is #filename# and the attachment patterns contain #FILENAME# and #filename#, then only #filename# will be replaced with the actual value.
Examples
The example is available in MailMerge class overview.
See Also

Reference

MailMerge Class
MailBee.Mime Namespace
MailMergeClearAttachmentPatterns


MailMerge.ClearAttachmentPatterns Method

MailMergeClearAttachmentPatterns Method
Clears the collection of the attachments patterns.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ClearAttachmentPatterns()
Public Sub ClearAttachmentPatterns
Remarks
Unlike Reset method (which should be called each time you need to merge another portion of data with the same template and produce another e-mail within the same series), ClearAttachmentPatterns should only be called when you want to start another series and define another template.
See Also

Reference

MailMerge Class
MailBee.Mime Namespace
MailMergeAddAttachmentPattern(String)


MailMerge.Replace Method

MailMergeReplace Method
Overload List
Name | Description
Replace(String, String) | Replaces all occurrences of the specified pattern in the message template with the specified actual value.
Replace(String, String, MailMergeTargets) | Replaces all occurrences of the specified case-sensitive pattern in the specified parts of the message with the actual value.
Top
See Also

Reference

MailMerge Class
MailBee.Mime Namespace


MailMerge.Replace Method (String, String)

MailMergeReplace Method (String, String)
Replaces all occurrences of the specified pattern in the message template with the specified actual value.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Replace(
    string pattern,
    string actualValue
)
Public Function Replace (
    pattern As String,
    actualValue As String
) As Integer

Parameters

pattern
Type: SystemString
The pattern to be searched.
actualValue
Type: SystemString
The actual value to replace the found pattern with.

Return Value

Type: Int32
The number of replacements actually made.
Remarks

This method performs search and replace operation in ALL parts of the message. If it's desired to only limit the scope of search and replace operation to certain message only (such as message headers only), use Replace(String, String, MailMergeTargets) overload.

If you previously added an attachment pattern (using method) which contains pattern in its value, pattern will be replaced with the actualValue in the attachment pattern and the resulting value will be used as a path to the file to be attached to the message.

Note Note
Pattern of the message template is case-sensitive. For instance, if the pattern is e-mail and the message body contains E-MAIL and e-mail, then only e-mail will be replaced with the actual value.
Examples
The example is available in MailMerge topic.
See Also

Reference

MailMerge Class
Replace Overload
MailBee.Mime Namespace
MailMergeAddAttachmentPattern(String)
MailMergeAddAttachmentPattern(String)


MailMerge.Replace Method (String, String, MailMergeTargets)

MailMergeReplace Method (String, String, MailMergeTargets)
Replaces all occurrences of the specified case-sensitive pattern in the specified parts of the message with the actual value.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Replace(
    string pattern,
    string actualValue,
    MailMergeTargets targets
)
Public Function Replace (
    pattern As String,
    actualValue As String,
    targets As MailMergeTargets
) As Integer

Parameters

pattern
Type: SystemString
The pattern to be searched.
actualValue
Type: SystemString
The actual value to replace the found pattern with.
targets
Type: MailBee.MimeMailMergeTargets
The elements of the message where the pattern text should be searched and replaced with the actual value.

Return Value

Type: Int32
The number of replacements actually made.
Remarks

This method performs search and replace operation in targets parts of the message.

If you previously added an attachment pattern (using method) which contains pattern in its value, pattern will be replaced with the actualValue in the attachment pattern and the resulting value will be used as a path to the file to be attached to the message.

Note Note
Pattern of the message template is case-sensitive. For instance, if the pattern is e-mail and the message body contains E-MAIL and e-mail, then only e-mail will be replaced with the actual value.
Examples
The example is available in MailMerge topic.
See Also

Reference

MailMerge Class
Replace Overload
MailBee.Mime Namespace
MailMergeAddAttachmentPattern(String)
MailMergeAddAttachmentPattern(String)


MailMerge.ReplaceAsync Method

MailMergeReplaceAsync Method
Overload List
 | Name | Description
Public method | ReplaceAsync(String, String) | async/await version of Replace(String, String).
Public method | ReplaceAsync(String, String, MailMergeTargets) | async/await version of Replace(String, String, MailMergeTargets).
Top
See Also

Reference

MailMerge Class
MailBee.Mime Namespace


MailMerge.ReplaceAsync Method (String, String)

MailMergeReplaceAsync Method (String, String)
async/await version of Replace(String, String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<int> ReplaceAsync(
    string pattern,
    string actualValue
)
Public Function ReplaceAsync (
    pattern As String,
    actualValue As String
) As Task(Of Integer)

Parameters

pattern
Type: SystemString
The pattern to be searched.
actualValue
Type: SystemString
The actual value to replace the found pattern with.

Return Value

Type: Task Int32
A task that represents the asynchronous operation. The value of TResult parameter is the number of replacements actually made.
See Also

Reference

MailMerge Class
ReplaceAsync Overload
MailBee.Mime Namespace


MailMerge.ReplaceAsync Method (String, String, MailMergeTargets)

MailMergeReplaceAsync Method (String, String, MailMergeTargets)
async/await version of Replace(String, String, MailMergeTargets).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<int> ReplaceAsync(
    string pattern,
    string actualValue,
    MailMergeTargets targets
)
Public Function ReplaceAsync (
    pattern As String,
    actualValue As String,
    targets As MailMergeTargets
) As Task(Of Integer)

Parameters

pattern
Type: SystemString
The pattern to be searched.
actualValue
Type: SystemString
The actual value to replace the found pattern with.
targets
Type: MailBee.MimeMailMergeTargets
The elements of the message where the pattern text should be searched and replaced with the actual value.

Return Value

Type: Task Int32
A task that represents the asynchronous operation. The value of TResult parameter is the number of replacements actually made.
See Also

Reference

MailMerge Class
ReplaceAsync Overload
MailBee.Mime Namespace


MailMerge.Reset Method

MailMergeReset Method
Resets the merged message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reset()
Public Sub Reset
Remarks

This method sets MergedMessage property to a null reference (Nothing in Visual Basic). In fact, this method reverts the merged message back to the template.

After you finished merging a portion of actual values with a template and sending the resulting message, call this method if you need to proceed with creating another message based on the same template.

Examples
The example is available in MailMerge topic.
See Also

Reference

MailMerge Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MailMerge Properties

MailMerge Properties

The MailMerge type exposes the following members.

Properties
Name | Description
MergedMessage | Contains the completed mail message which is a result of mail merge operation.
Top
See Also

Reference

MailMerge Class
MailBee.Mime Namespace


MailMerge.MergedMessage Property

MailMergeMergedMessage Property
Contains the completed mail message which is a result of mail merge operation.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MergedMessage { get; }
Public ReadOnly Property MergedMessage As MailMessage
    Get

Property Value

Type: MailMessage
A merged MailMessage object. The default value is a null reference (Nothing in Visual Basic).
Remarks
To make this property return non-null object, you should call Replace(String, String) method (or its overloads) at least once. Reset method call sets MergedMessage value back to a null reference.
Examples
The example is available in MailMerge class overview.
See Also

Reference

MailMerge Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MailMergeTargets Enumeration

MailMergeTargets Enumeration
Defines mail message elements where patterns should be searched and replaced with actual values during mail merge operation.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum MailMergeTargets
<FlagsAttribute>
Public Enumeration MailMergeTargets
Members
Member name | Value | Description
None | 0 | No elements.
BodyPlainText | 1 | The plain-text body of the message.
BodyHtmlText | 2 | The HTML body of the message.
From | 4 | The From field.
ReplyTo | 8 | The ReplyTo field.
Recipients | 16 | The To, Cc, Bcc fields.
Subject | 32 | The Subject field.
Other | 64 | All other parts of the message excluding attachments. Examples are custom headers and text body parts.
All | 127 | All message elements listed above.
Remarks
MailMerge.Replace method performs search and replacement in the parts of the message specified by targets parameter (which has MailMergeTargets type). MailMergeTargets has no effect on attachments. This is because Replace(String, String) method can add attachments only if their patterns have been added through AddAttachmentPattern(String) method.
See Also

Reference

MailBee.Mime Namespace
MailMessageMerge


MailMessage Class

MailMessage Class
Provides properties and methods for constructing and examining a single e-mail message.
Inheritance Hierarchy
SystemObject
MailBee.MimeMailMessage

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailMessage : IDisposable
Public Class MailMessage
    Implements IDisposable

The MailMessage type exposes the following members.

Constructors
 | Name | Description
Public method | MailMessage | Initializes a new instance of the MailMessage class
Top
Methods
 | Name | Description
 | AppendChunk | Adds a block of bytes to the source of the message.
 | AppendPartialMessage | Adds the specified partial message to this message.
 | Clear | Removes the specified elements from the message.
 | Clone | Creates a copy of the message.
Public method | ConvertFromSystemNetMail | Loads the message from System.Net.Mail.MailMessage object.
Public method | ConvertToSystemNetMail | Exports the message to System.Net.Mail.MailMessage object.
 | Deserialize(String) | Loads a message from the specified .XML file.
 | Deserialize(XmlReader) | Loads a message from XML stream using the specified XmlReader object.
Public method | DeserializeAsync(String) | async/await version of Deserialize(String).
Public method | DeserializeAsync(XmlReader) | async/await version of Deserialize(XmlReader).
Public method | Dispose | Removes the temporary folders and files that are associated with the mail message.
 | DomainKeysSign | Signs the current e-mail message with DKIM and classic DomainKeys signatures.
 | DomainKeysVerify | Verifies DKIM and classic DomainKeys signatures of the current e-mail message.
Public method | DomainKeysVerifyAsync | async/await version of DomainKeysVerify.
 | EncodeAllHeaders | Encodes all message headers into the specified encoding.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Finalizes the instance of MailMessage object. (Overrides ObjectFinalize.)
 | ForwardAsAttachment | Forwards a mail message as attached .EML file.
 | GetAllRecipients | Gets the EmailAddressCollection object containing the e-mail addresses of all message recipients.
 | GetEncodedHeaderValue | Encodes the value of the specified header.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetHtmlAndRelatedFilesInMemory | Gets HTML body with references to all inline attachments being replaced with user-defined indexed paths.
 | GetHtmlAndSaveRelatedFiles | Extracts the HTML body of the message, saves the attached inline pictures and other related files to disk, and return the modified HTML body.
 | GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) | Prepares the HTML body of the message for displaying in a web application: saves all embedded objects to a temporary location, replaces their Content-ID's with their virtual paths in the temporary location, and returns the modified HTML body as a string.
Public method | GetHtmlAndSaveRelatedFilesAsync | async/await version of GetHtmlAndSaveRelatedFiles.
Public method | GetHtmlAndSaveRelatedFilesAsync(String, VirtualMappingType, MessageFolderBehavior) | async/await version of GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior).
 | GetHtmlWithBase64EncodedRelatedFiles | Gets the HTML body with all related files being embedded directly in the HTML body as base64 chunks.
 | GetMessageRawData | Gets the source of the message as a byte array.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | ImportRelatedFiles | Adds all the related files (referenced in HTML part of the message) as inline attachments.
Public method | ImportRelatedFilesAsync | async/await version of ImportRelatedFiles(ImportRelatedFilesOptions).
 | IsBodyAvail | Indicates if the body of the specified format is present in the message.
 | LoadBodyText(String, MessageBodyType) | Loads the contents of the specified file into HTML or plain-text body of the message.
 | LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) | Loads the contents of the specified file or web page into HTML or plain-text body of the message, also attaching related objects such as inline images if necessary.
Public method | LoadBodyTextAsync(String, MessageBodyType) | async/await version of LoadBodyText(String, MessageBodyType).
Public method | LoadBodyTextAsync(String, MessageBodyType, Encoding, ImportBodyOptions) | async/await version of LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions).
 | LoadMessage(Byte) | Loads the message from a byte array.
 | LoadMessage(Stream) | Loads the message from a stream.
 | LoadMessage(String) | Loads the message from the specified file.
Public method | LoadMessageAsync(Stream) | async/await version of LoadMessage(Stream).
Public method | LoadMessageAsync(String) | async/await version of LoadMessage(String).
 | MakePlainBodyFromHtmlBody | Creates a plain text body from the existing HTML body of the message.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Reset | Resets all the properties of the MailMessage object to the default values.
 | SaveHtmlAndRelatedFiles | Saves the HTML body of the message and all inline pictures and other inline objects to disk.
Public method | SaveHtmlAndRelatedFilesAsync | async/await version of SaveHtmlAndRelatedFiles(String).
 | SaveMessage(Stream) | Saves a message into the specified stream.
 | SaveMessage(String) | Saves a message into the specified file.
Public method | SaveMessageAsync(Stream) | async/await version of SaveMessage(Stream).
Public method | SaveMessageAsync(String) | async/await version of SaveMessage(String).
 | Serialize(String) | Saves the message into the specified .XML file.
 | Serialize(XmlWriter) | Saves the message into XML stream using the specified XmlWriter object.
Public method | SerializeAsync(String) | async/await version of Serialize(String).
Public method | SerializeAsync(XmlWriter) | async/await version of Serialize(XmlWriter).
 | SetDateFromString | Sets the date of the message creation as a string.
 | SetUniqueMessageID | Sets a new unique value of Message-ID header and returns it.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | Attachments | Gets the AttachmentCollection object containing the attachments of the mail message.
 | Bcc | Gets or sets the list of blind carbon copy (BCC) recipients of the message.
 | BodyHtmlText | Gets or sets the HTML body of the message.
 | BodyParts | Gets all the text bodies of the message.
 | BodyPlainText | Gets or sets the plain-text body of the message.
 | Builder | Gets or sets the options which affect how the mail message is built by MailBee.
 | Cc | Gets or sets the list of carbon copy (CC) recipients of the message.
 | Charset | Gets or sets the name of the charset which was used to compose the message.
 | ConfirmRead | Gets or sets the e-mail address of an entity which should receive the read confirmation message.
 | ConfirmReceipt | Gets or sets the e-mail address of an entity which should receive the delivery confirmation message (when the message gets into mailbox of the server).
 | ContentType | Gets the content type of the message.
 | Date | Gets or sets the date and the time when the mail message was composed.
 | DateReceived | Gets the date and the time when the message was received by the server.
Public property | DateSent | Gets or sets the date and the time when the mail message was sent.
Public property | Filename | Gets the filename of the file this message was loaded from.
 | From | Gets or sets the e-mail address of the message sender.
 | HasAttachments | Indicates if the message has any attachments.
 | Headers | Gets the collection of the message headers.
 | Importance | Gets or sets the importance of the message.
Public property | IndexOnServer | Gets the index of the mail message stored on the mail server.
 | IsEncrypted | Indicates if the message is encrypted.
 | IsEntire | Indicates if the message was received completely.
 | IsSigned | Indicates if the message has a digital signature.
 | LastResult | Gets the code of the last occurred error.
 | MailTransferEncodingHtml | Gets or sets the transfer encoding of the HTML body of the message.
 | MailTransferEncodingPlain | Gets or sets the transfer encoding of the plain-text body of the message.
Public property | MdnReportType | Gets or sets report-type value for Message Disposition Notification (MDN) messages.
 | Merge | Gets the MailMerge object which can be used to perform mail merge using the current e-mail message as a template.
 | MessageID | Gets or sets the Message-ID header of the message.
 | MimePartTree | Gets the root MIME part of the message.
 | Organization | Gets or sets the name of organization to which the sender of the message belongs.
 | Parser | Gets or sets the options which affect how the MailMessage object is parsed.
 | PartCount | Gets the number of parts of the composite message which is split into the several smaller mail messages.
 | PartIndex | Gets the index of the current part in the sequence of parts of a composite message.
 | Priority | Gets or sets the priority of the message.
 | RawHeader | Gets the message header section exactly as it is contained in the message.
 | References | Gets or sets the references of the message.
 | ReplyTo | Gets or sets the list of the e-mail addresses where to send a reply to this message.
 | ReturnPath | Gets the value of Return-Path header.
Public property | Sender | Gets or sets the value of Sender header.
 | Sensitivity | Gets or sets the sensitivity of the message.
 | Size | Gets the size of the message in bytes.
 | SizeOnServer | Gets the actual message size on the mail server.
 | Subject | Gets or sets the subject of the message.
 | ThrowExceptions | Gets or sets whether the MailMessage object will throw exceptions on errors.
 | TimeStamps | Gets the collection of which represents the trace route of the message.
 | To | Gets or sets the e-mail addresses of the primary recipients of the mail message.
 | UidOnServer | Gets Unique-ID (UID) of the message in the mailbox on the server.
 | Version | Gets the current version of MailBee.NET Objects.
 | XMailer | Gets or sets the details about the software which was used to create the message.
Top
Remarks
MailMessage is a standard container for e-mail messages.
  • Pop3 and Imap components return dowloaded e-mail messages as MailMessage or MailMessageCollection objects
  • Imap component can also upload e-mail messages into a folder on the mail server
  • Smtp component sends e-mail messages
  • LoadMessage(String) method loads an e-mail message from an array, stream or an .EML file
  • SaveMessage(String) method saves the message into a stream or an .EML file
  • GetMessageRawData method returns the message source as an array
  • ConvertToSystemNetMail and ConvertFromSystemNetMail(MailMessage) methods allow for easy interoperability with System.Net.Mail.MailMessage class

Moreover MailMessage

  • Gives access to all parts of the message such as headers, bodies, attachments, time stamps (Received headers), etc
  • Has comprehensive facilities for message modification (such as HTML to plain-text conversion, preparing HTML with embedded pictures for dispaying, etc)
  • Offers the full support of international charsets and e-mail addresses (IDN domains)
  • Supports mail merge capabilitites, DomainKeys and DKIM, XML serialization, and much more
Examples
This sample composes a mail message and saves it to disk using two methods: as .EML file and as .XML file.
C#
VB
Copy
using System.Text;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();

        // Set the recipient e-mail from string.
        msg.To.AddFromString("some_user@domain.com");

        // Add more recipient e-mail's along with recipient
        // names and corresponding remarks.
        msg.To.Add("user1@domain.com", "User 1", "Remark");
        msg.To.Add("user2@domain.com", "User 2", "");

        // Set the sender e-mail from string.
        msg.From.Email = "jdoe@domain.com";

        // Set the friendly name of the message sender.
        msg.From.DisplayName = "John Doe";

        // Set the subject of the message.
        msg.Subject = "Hello";

        // Set Carbon Copy (CC) recipient e-mail along with
        // corresponding name and remarks.
        msg.Cc.Add("user3@domain.com", "User 3", "Remark");

        // Set the plain-formatted body of the message.
        msg.BodyPlainText = "Hello, World!";

        // Set the HTML-formatted body of the message.
        msg.BodyHtmlText = @"Hello, <b>World</b>!<br>
            <IMG alt="""" hspace=0 src=""cid:12345"" align=baseline border=0><br>
            <IMG alt="""" hspace=0 src=""cid:67891"" align=baseline border=0>";

        // Specify the charset of the message.
        msg.Charset = "utf-8";

        // Set the Quoted-Printable encoding for plain-formatted body.
        msg.MailTransferEncodingPlain = MailTransferEncoding.QuotedPrintable;

        // Set the Quoted-Printable encoding for HTML-formatted body.
        msg.MailTransferEncodingHtml = MailTransferEncoding.QuotedPrintable;

        // Add three different attachments to the message.
        msg.Attachments.Add(@"C:\Docs\new.gif", "1.gif", "12345");
        msg.Attachments.Add(@"C:\Docs\old.gif", "2.gif", "67891");
        msg.Attachments.Add(@"C:\Docs\2.jpg", "2.jpg");

        // Encode all message headers into Base64 encoding.
        msg.EncodeAllHeaders(Encoding.Default, HeaderEncodingOptions.Base64);

        // Set the unique message identifier.
        msg.SetUniqueMessageID("");

        // Save message to the disk as .eml file.
        msg.SaveMessage(@"C:\Temp\TestMail.eml");

        // Serialize message into .xml file on the disk.
        msg.Serialize(@"C:\Temp\TestMail.xml");
    }
}
Imports System.Text
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim msg As New MailMessage

        ' Set the recipient e-mail from string.
        msg.To.AddFromString("some_user@domain.com")

        ' Add more recipient e-mail's along with recipient
        ' names and corresponding remarks.
        msg.To.Add("user1@domain.com", "User 1", "Remark")
        msg.To.Add("user2@domain.com", "User 2", "")

        ' Set the sender e-mail from string.
        msg.From.Email = "jdoe@domain.com"

        ' Set the friendly name of the message sender.
        msg.From.DisplayName = "John Doe"

        ' Set the subject of the message.
        msg.Subject = "Hello"

        ' Set Carbon Copy (CC) recipient e-mail along with
        ' corresponding name and remarks.
        msg.Cc.Add("user3@domain.com", "User 3", "Remark")

        ' Set the plain-formatted body of the message.
        msg.BodyPlainText = "Hello, World!"

        ' Set the HTML-formatted body of the message.
        msg.BodyHtmlText = "Hello, <b>World</b>!<br>" & _
            "<IMG alt="""" hspace=0 src=""cid:12345"" align=baseline border=0><br>" & _
            "<IMG alt="""" hspace=0 src=""cid:67891"" align=baseline border=0>"

        ' Specify the charset of the message.
        msg.Charset = "utf-8"

        ' Set the Quoted-Printable encoding for plain-formatted body.
        msg.MailTransferEncodingPlain = MailTransferEncoding.QuotedPrintable

        ' Set the Quoted-Printable encoding for HTML-formatted body.
        msg.MailTransferEncodingHtml = MailTransferEncoding.QuotedPrintable

        ' Add three different attachments to the message.
        msg.Attachments.Add("C:\Docs\new.gif", "1.gif", "12345")
        msg.Attachments.Add("C:\Docs\old.gif", "2.gif", "67891")
        msg.Attachments.Add("C:\Docs\2.jpg", "2.jpg")

        ' Encode all message headers into Base64 encoding.
        msg.EncodeAllHeaders(Encoding.Default, HeaderEncodingOptions.Base64)

        ' Set the unique message identifier.
        msg.SetUniqueMessageID("")

        ' Save message to disk as .eml file.
        msg.SaveMessage("C:\Temp\TestMail.eml")

        ' Serialize message into .xml file on disk.
        msg.Serialize("C:\Temp\TestMail.xml")
    End sub
End Module
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeAttachment


MailMessage Constructor

MailMessage Constructor
Initializes a new instance of the MailMessage class

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage()
Public Sub New
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage Methods

MailMessage Methods

The MailMessage type exposes the following members.

Methods
 | Name | Description
 | AppendChunk | Adds a block of bytes to the source of the message.
 | AppendPartialMessage | Adds the specified partial message to this message.
 | Clear | Removes the specified elements from the message.
 | Clone | Creates a copy of the message.
Public method | ConvertFromSystemNetMail | Loads the message from System.Net.Mail.MailMessage object.
Public method | ConvertToSystemNetMail | Exports the message to System.Net.Mail.MailMessage object.
 | Deserialize(String) | Loads a message from the specified .XML file.
 | Deserialize(XmlReader) | Loads a message from XML stream using the specified XmlReader object.
Public method | DeserializeAsync(String) | async/await version of Deserialize(String).
Public method | DeserializeAsync(XmlReader) | async/await version of Deserialize(XmlReader).
Public method | Dispose | Removes the temporary folders and files that are associated with the mail message.
 | DomainKeysSign | Signs the current e-mail message with DKIM and classic DomainKeys signatures.
 | DomainKeysVerify | Verifies DKIM and classic DomainKeys signatures of the current e-mail message.
Public method | DomainKeysVerifyAsync | async/await version of DomainKeysVerify.
 | EncodeAllHeaders | Encodes all message headers into the specified encoding.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Finalizes the instance of MailMessage object. (Overrides ObjectFinalize.)
 | ForwardAsAttachment | Forwards a mail message as attached .EML file.
 | GetAllRecipients | Gets the EmailAddressCollection object containing the e-mail addresses of all message recipients.
 | GetEncodedHeaderValue | Encodes the value of the specified header.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetHtmlAndRelatedFilesInMemory | Gets HTML body with references to all inline attachments being replaced with user-defined indexed paths.
 | GetHtmlAndSaveRelatedFiles | Extracts the HTML body of the message, saves the attached inline pictures and other related files to disk, and return the modified HTML body.
 | GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) | Prepares the HTML body of the message for displaying in a web application: saves all embedded objects to a temporary location, replaces their Content-ID's with their virtual paths in the temporary location, and returns the modified HTML body as a string.
Public method | GetHtmlAndSaveRelatedFilesAsync | async/await version of GetHtmlAndSaveRelatedFiles.
Public method | GetHtmlAndSaveRelatedFilesAsync(String, VirtualMappingType, MessageFolderBehavior) | async/await version of GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior).
 | GetHtmlWithBase64EncodedRelatedFiles | Gets the HTML body with all related files being embedded directly in the HTML body as base64 chunks.
 | GetMessageRawData | Gets the source of the message as a byte array.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | ImportRelatedFiles | Adds all the related files (referenced in HTML part of the message) as inline attachments.
Public method | ImportRelatedFilesAsync | async/await version of ImportRelatedFiles(ImportRelatedFilesOptions).
 | IsBodyAvail | Indicates if the body of the specified format is present in the message.
 | LoadBodyText(String, MessageBodyType) | Loads the contents of the specified file into HTML or plain-text body of the message.
 | LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) | Loads the contents of the specified file or web page into HTML or plain-text body of the message, also attaching related objects such as inline images if necessary.
Public method | LoadBodyTextAsync(String, MessageBodyType) | async/await version of LoadBodyText(String, MessageBodyType).
Public method | LoadBodyTextAsync(String, MessageBodyType, Encoding, ImportBodyOptions) | async/await version of LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions).
 | LoadMessage(Byte) | Loads the message from a byte array.
 | LoadMessage(Stream) | Loads the message from a stream.
 | LoadMessage(String) | Loads the message from the specified file.
Public method | LoadMessageAsync(Stream) | async/await version of LoadMessage(Stream).
Public method | LoadMessageAsync(String) | async/await version of LoadMessage(String).
 | MakePlainBodyFromHtmlBody | Creates a plain text body from the existing HTML body of the message.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Reset | Resets all the properties of the MailMessage object to the default values.
 | SaveHtmlAndRelatedFiles | Saves the HTML body of the message and all inline pictures and other inline objects to disk.
Public method | SaveHtmlAndRelatedFilesAsync | async/await version of SaveHtmlAndRelatedFiles(String).
 | SaveMessage(Stream) | Saves a message into the specified stream.
 | SaveMessage(String) | Saves a message into the specified file.
Public method | SaveMessageAsync(Stream) | async/await version of SaveMessage(Stream).
Public method | SaveMessageAsync(String) | async/await version of SaveMessage(String).
 | Serialize(String) | Saves the message into the specified .XML file.
 | Serialize(XmlWriter) | Saves the message into XML stream using the specified XmlWriter object.
Public method | SerializeAsync(String) | async/await version of Serialize(String).
Public method | SerializeAsync(XmlWriter) | async/await version of Serialize(XmlWriter).
 | SetDateFromString | Sets the date of the message creation as a string.
 | SetUniqueMessageID | Sets a new unique value of Message-ID header and returns it.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.AppendChunk Method

MailMessageAppendChunk Method
Adds a block of bytes to the source of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AppendChunk(
    byte[] nextChunk
)
Public Sub AppendChunk (
    nextChunk As Byte()
)

Parameters

nextChunk
Type: SystemByte
A reference to the byte array containing a portion of message data.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | nextChunk is a null reference (Nothing in Visual Basic).
Remarks

This method can be used to assemble a message from smaller memory blocks (for instance, if the message is being read from the resource which cannot return all the data at once). However, since this method recreates the internal message data buffer on each call, it should be used only if the size of the data is not known until all the data received. If the size of the data is known from the very beginning, it's more effective to create a memory array of the required length, fill it with the data and then pass this array to LoadMessage(Byte) method. Or, if you're using streams, use LoadMessage(Stream) overload.

To assembly a message which naturally comes as a series of smaller e-mail messages (also called partial messages), use AppendPartialMessage(MailMessage) method.

Examples
This sample demonstrates loading 1000 bytes of the message data from a file using a buffer of a fixed length (100 bytes). It's assumed the file is at least 1000 bytes in size.
Note Note

In real world applications, it's easier to load a message from a file/stream/memory using LoadMessage(String) method and its overloads.

Also, real world apps shouldn't rely on the fact that FileStream.Read method of .NET framework always returns the requested number of bytes. They should rather check its return value and repeat reading attempt if the number of bytes read was less than requested. The code snippet in FileStream.Read topic in MSDN shows how this can be done.

C#
VB
Copy
using System;
using System.IO;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();
        string filename = @"C:\Docs\TestMail.eml";

        // Open the file for reading.
        using (FileStream fs = new FileStream(filename, FileMode.Open))
        {
            // Create a 100 bytes buffer.
            byte[] bytes = new byte[100];

            for (int i = 0; i < 10; i++)
            {
                // Read a portion of data (100 bytes) from the file and append it to the message source.
                fs.Read(bytes, i * bytes.Length, bytes.Length);
                msg.AppendChunk(bytes);
            }
        }

        // The message will be parsed at this point (when we access any of its properties).
        Console.WriteLine(msg.Subject);
    }
}
Imports System
Imports System.IO
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim msg = New MailMessage
        Dim filename As String = "C:\Docs\TestMail1.eml"

        Dim fs As FileStream
        Try
            ' Open the file for reading.
            fs = New FileStream(filename, FileMode.Open)

            ' Create a 100 bytes buffer.
            Dim bytes As Byte()
            ReDim bytes(100)

            For i As Integer = 1 To 10
                ' Read a portion of data (100 bytes) from the file and append it to the message source.
                fs.Read(bytes, i * bytes.Length, bytes.Length)
                msg.AppendChunk(bytes)
            Next
        Finally
            If Not fs Is Nothing Then
                fs.Close()
            End If
        End Try

        ' The message will be parsed at this point (when we access any of its properties).
        Console.WriteLine(msg.Subject)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageAppendPartialMessage(MailMessage)


MailMessage.AppendPartialMessage Method

MailMessageAppendPartialMessage Method
Adds the specified partial message to this message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AppendPartialMessage(
    MailMessage nextPart
)
Public Function AppendPartialMessage (
    nextPart As MailMessage
) As Boolean

Parameters

nextPart
Type: MailBee.MimeMailMessage
A portion of the message as another MailMessage object.

Return Value

Type: Boolean
true if the partial message which was appended was the last one required; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | nextPart is a null reference (Nothing in Visual Basic) or not a partial message.
MailBeeInvalidStateException | The message is not partial, so another partial message can't be added to it.
Remarks

Some mail client programs can split large messages into a number of smaller messages before sending and then send these smaller e-mails separately. This technique was used to overcome limitations of maximum size of a message which existed on some mail servers. Nowadays, this practice is not used but MailBee is still capable of parsing such messages. To assembly a message from its parts (they have message/partial in their ContentType), you should get the first part (having PartIndex set to 1), and append the remaining messages in the correct order (with PartIndex set to 2, 3, etc) using AppendPartialMessage(MailMessage) until it returns true. AppendPartialMessage(MailMessage) returns true when you append a message having PartIndex equal to PartCount.

Use PartCount property to determine if the mail message is split (and so it's needed to get the remaining parts and join them with AppendPartialMessage(MailMessage) method).

Use PartIndex property to obtain the index of the message so that you would be able to pass the messages to be appended by AppendPartialMessage(MailMessage) method in proper order (from 1 to PartCount).

Examples
This sample assemblies the message from 4 partial messages. It loads the first portion and then calls AppendPartialMessage(MailMessage) for the remaining 3 portions.
C#
VB
Copy
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage newMsg = new MailMessage();
        MailMessage partialMsg = new MailMessage();
        newMsg.LoadMessage(@"C:\Docs\splitmail\1of4.eml");

        // Append 3 partial messages that are loaded from disk.
        for (int i = 2; i <= 4; i++)
        {
            partialMsg.LoadMessage(string.Format(@"C:\Docs\splitmail\{0}of4.eml", i));
            newMsg.AppendPartialMessage(partialMsg);
        }

        // Save the entire message to disk.
        newMsg.SaveMessage(@"C:\Temp\entire.eml");
    }
}
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim newMsg = New MailMessage
        Dim partialMsg = New MailMessage
        newMsg.LoadMessage("C:\Docs\splitmail\1of4.eml")

        ' Append 3 partial messages that are loaded from disk.
        For i As Integer = 2 To 4
            partialMsg.LoadMessage(String.Format("C:\Docs\splitmail\{0}of4.eml", i))
            newMsg.AppendPartialMessage(partialMsg)
        Next

        ' Save the entire message to disk.
        newMsg.SaveMessage("C:\Temp\entire.eml")
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessagePartIndex
MailMessagePartCount
MailMessageIsEntire


MailMessage.Clear Method

MailMessageClear Method
Removes the specified elements from the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear(
    MessageElements elements
)
Public Sub Clear (
    elements As MessageElements
)

Parameters

elements
Type: MailBee.MimeMessageElements
A set of MessageElements flags specifying which elements should be removed from the message.
Remarks

To clear the entire message (i.e. to reset all its properties to default values), the developer should use Reset method.

To clear raw body of the message, you can use Msg.Clear(MessageElements.RawBody) call. This is useful if you already received an e-mail and parsed it. If you have no plans to further access the raw data of the e-mail (e.g. write the e-mail into .EML file), you do not need the raw body data (which might be very large), and can free it. However, if you then call and method or property which operates on the raw body (such as Size property), the message will be rebuilt and the raw body regenerated. Be sure to call all such properties and methods BEFORE clearing the raw body.

Another purpose of Msg.Clear(MessageElements.RawBody) is after sending a very large e-mail. For instance, you're sending multiple very large e-mails and want to have as much free memory as possible before every e-mail gets built to avoid out-of-memory issues. You can use Reset method and then call Collect(Int32) (GC.Collect) but this will also remove all the attachments and other parts of the message. In case if you want to send the same attachments in multiple e-mails, this would degrade performance. With Msg.Clear(MessageElements.RawBody) you can preserve the attachments already loaded and free only the generated raw message data.

Examples
This sample downloads the message from the specified POP3 account, removes all message attachments and recipients (other data is not removed), and saves this message to disk.
C#
VB
Copy
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("pop.mail.com", "kathy", "password", 1);

        // Remove all attachments and recipients from the message and save this message to disk.
        msg.Clear(MessageElements.Attachments | MessageElements.Recipients);
        msg.SaveMessage(@"C:\Temp\msg.eml");
    }
}
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop.mail.com", "kathy", "password", 1)

        ' Remove all attachments and recipients from the message and save this message to disk.
        msg.Clear(MessageElements.Attachments Or MessageElements.Recipients)
        msg.SaveMessage("C:\Temp\msg.eml")
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageReset


MailMessage.Clone Method

MailMessageClone Method
Creates a copy of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Clone()
Public Function Clone As MailMessage

Return Value

Type: MailMessage
A MailMessage object which represents the cloned message.
Remarks
The deep clone is performed, that means the fully independent copy of the message is created and there are no shared objects between the original message and its copy.
Examples
This sample demostrates that the message copy created by this method has its own copies of all internal objects. For instance, their Attachments collections are another objects, not just two references to the same object.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        MailMessage newMsg = msg;
        MailMessage clonedMsg = msg.Clone();

        // Check if the attachments of two messages are equal
        // and display the corresponding notification.
        if (msg.Attachments == newMsg.Attachments)
        {
            Console.WriteLine("Equals");
        }
        else
        {
            Console.WriteLine("Not equals");
        }

        // Check if the attachments of two messages are equal
        // and display the corresponding notification.
        if (msg.Attachments == clonedMsg.Attachments)
        {
            Console.WriteLine("Equals");
        }
        else
        {
            Console.WriteLine("Not equals");
        }
    }
}

// Output:
// Equals
// Not equals
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        Dim newMsg = msg
        Dim cloneMsg = msg.Clone()

        ' Check if the attachments of two messages are equal
        ' and display the corresponding notification.
        If msg.Attachments Is newMsg.Attachments Then
            Console.WriteLine("Equals")
        Else
            Console.WriteLine("Not equals")
        End If

        ' Check if the attachments of two messages are equal
        ' and display the corresponding notification.
        If msg.Attachments Is cloneMsg.Attachments Then
            Console.WriteLine("Equals")
        Else
            Console.WriteLine("Not equals")
        End If
    End Sub
End Module

' Output:
' Equals
' Not equals
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.ConvertFromSystemNetMail Method

MailMessageConvertFromSystemNetMail Method
Loads the message from System.Net.Mail.MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ConvertFromSystemNetMail(
    MailMessage msg
)
Public Sub ConvertFromSystemNetMail (
    msg As MailMessage
)

Parameters

msg
Type: System.Net.MailMailMessage
A System.Net.Mail.MailMessage object to load the message from.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.ConvertToSystemNetMail Method

MailMessageConvertToSystemNetMail Method
Exports the message to System.Net.Mail.MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage ConvertToSystemNetMail()
Public Function ConvertToSystemNetMail As MailMessage

Return Value

Type: MailMessage
A System.Net.Mail.MailMessage object representing the current mail message.
Exceptions
Exception | Condition
ArgumentException | System.Net.Mail.MailMessage object has failed to parse some fields of the mail message. This exception is thrown by System.Net.Mail.MailMessage object, not by MailBee.
Remarks
The conversion may fail in case of unusual header values (such as X400 e-mail addresses) because System.Net.Mail.MailMessage class does not support them. You can read such a mail message with MailBee but not with System.Net.Mail.MailMessage. Thus, if your mail message contains elements which are not supported by System.Net.Mail.MailMessage, you should remove or correct them prior to calling this method.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Deserialize Method

MailMessageDeserialize Method
Loads the message from the specified .XML file or from XML stream.
Overload List
Name | Description
Deserialize(String) | Loads a message from the specified .XML file.
Deserialize(XmlReader) | Loads a message from XML stream using the specified XmlReader object.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Deserialize Method (String)

MailMessageDeserialize Method (String)
Loads a message from the specified .XML file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Deserialize(
    string filename
)
Public Function Deserialize (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
A string containing the name of the .XML file.

Return Value

Type: Boolean
true if the message was successfully loaded from .XML file; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks
This method can load a message which was previously saved using Serialize(String) method.
Examples
This sample loads the message from .EML file, saves it to .XML file, and loads this message back from .XML file.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Display the subject of this message.
        Console.WriteLine(msg.Subject);

        // Save the message to .XML file.
        msg.Serialize(@"C:\Temp\msg.xml");

        // Load the message from .XML file and display
        // the subject of this message.
        MailMessage newMsg = new MailMessage();
        newMsg.Deserialize(@"C:\Temp\msg.xml");
        Console.WriteLine(newMsg.Subject);
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Display the subject of this message.
        Console.WriteLine(msg.Subject)

        ' Save the message to .XML file.
        msg.Serialize("C:\Temp\msg.xml")

        ' Load the message from .XML file and display
        ' the subject of this message.
        Dim newMsg As New MailMessage
        newMsg.Deserialize("C:\Temp\msg.xml")
        Console.WriteLine(newMsg.Subject)
    End Sub
End Module
See Also

Reference

MailMessage Class
Deserialize Overload
MailBee.Mime Namespace


MailMessage.Deserialize Method (XmlReader)

MailMessageDeserialize Method (XmlReader)
Loads a message from XML stream using the specified XmlReader object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Deserialize(
    XmlReader xmlReader
)
Public Function Deserialize (
    xmlReader As XmlReader
) As Boolean

Parameters

xmlReader
Type: System.XmlXmlReader
An XmlReader object.

Return Value

Type: Boolean
true if the message was successfully loaded from the XML stream; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | xmlReader is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred and the ThrowExceptions property is true.
Remarks
This method can loada a message which was previously serialized using Serialize(XmlWriter) method. Be sure to disable white-space handling when using this method.
Examples
This sample loads the message from .EML file, saves it into .XML file, and then loads this message back from the .XML file.
C#
VB
Copy
using System;
using System.Xml;
using System.IO;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\msg.eml");

        // Display the subject of the message and
        // save this message to .XML file.
        Console.WriteLine(msg.Subject);
        msg.Serialize(@"C:\Temp\msg.xml");

        XmlTextReader reader = null;
        try
        {
            // Open .XML file for reading.
            reader = new XmlTextReader(File.OpenRead(@"C:\Temp\msg.xml"));
            reader.WhitespaceHandling = WhitespaceHandling.None;

            // Load the message from .XML file.
            MailMessage newMsg = new MailMessage();
            newMsg.Deserialize(reader);

            // Display the subject of the message.
            Console.WriteLine(newMsg.Subject);
        }
        finally
        {
            if (reader != null) reader.Close();
        }
    }
}
Imports System
Imports System.IO
Imports System.Xml
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\msg.eml")

        ' Display the subject of the message and
        ' save this message to .XML file.
        Console.WriteLine(msg.Subject)
        msg.Serialize("C:\Temp\msg.xml")

        Dim reader As XmlTextReader = Nothing
        Try
            ' Open .xml file for reading.
            reader = New XmlTextReader(File.OpenRead("C:\Temp\msg.xml"))
            reader.WhitespaceHandling = WhitespaceHandling.None

            ' Load the message from .XML file.
            Dim newMsg As New MailMessage
            newMsg.Deserialize(reader)

            ' Display the subject of the message.
            Console.WriteLine(newMsg.Subject)
        Finally
            If Not reader Is Nothing Then reader.Close()
        End Try
    End Sub
End Module
See Also

Reference

MailMessage Class
Deserialize Overload
MailBee.Mime Namespace


MailMessage.DeserializeAsync Method

MailMessageDeserializeAsync Method
Overload List
 | Name | Description
Public method | DeserializeAsync(String) | async/await version of Deserialize(String).
Public method | DeserializeAsync(XmlReader) | async/await version of Deserialize(XmlReader).
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.DeserializeAsync Method (String)

MailMessageDeserializeAsync Method (String)
async/await version of Deserialize(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeserializeAsync(
    string filename
)
Public Function DeserializeAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
A string containing the name of the .XML file.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully loaded from .XML file; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
DeserializeAsync Overload
MailBee.Mime Namespace


MailMessage.DeserializeAsync Method (XmlReader)

MailMessageDeserializeAsync Method (XmlReader)
async/await version of Deserialize(XmlReader).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeserializeAsync(
    XmlReader xmlReader
)
Public Function DeserializeAsync (
    xmlReader As XmlReader
) As Task(Of Boolean)

Parameters

xmlReader
Type: System.XmlXmlReader
An XmlReader object.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully loaded from the XML stream; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | xmlReader is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred and the ThrowExceptions property is true.
Remarks
Be sure to enable Async when creating XmlReader instance.
See Also

Reference

MailMessage Class
DeserializeAsync Overload
MailBee.Mime Namespace


MailMessage.Dispose Method

MailMessageDispose Method
Removes the temporary folders and files that are associated with the mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
If the CreateAndDelete option was turned on when the GetHtmlAndSaveRelatedFiles method was used, all temporary folders and files associated with the mail message will automatically be removed when Dispose method gets called. Otherwise, nothing will happen.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.DomainKeysSign Method

MailMessageDomainKeysSign Method
Signs the current e-mail message with DKIM and classic DomainKeys signatures.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void DomainKeysSign(
    bool isWebApp,
    string[] headersToSign,
    string privateKeyStr,
    bool isFilename,
    string selector,
    DomainKeysTypes dkTypes
)
Public Sub DomainKeysSign (
    isWebApp As Boolean,
    headersToSign As String(),
    privateKeyStr As String,
    isFilename As Boolean,
    selector As String,
    dkTypes As DomainKeysTypes
)

Parameters

isWebApp
Type: SystemBoolean
Must be true for ASP.NET applications, false otherwise.
headersToSign
Type: SystemString
The array of the names of the headers to be included in the signature, or a null reference (Nothing in Visual Basic) if all the message headers should be included in the signature.
privateKeyStr
Type: SystemString
The contents or the filename of the DomainKeys/DKIM private key.
isFilename
Type: SystemBoolean
If true, privateKeyStr denotes the private key filename; otherwise, the contents.
selector
Type: SystemString
The prefix of the sub-domain serving DomainKeys/DKIM for the sender domain.
dkTypes
Type: MailBee.SecurityDomainKeysTypes
Specifies which signatures to create (classic DK, newer DKIM, or both).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | privateKeyStr or selector is a null reference (Nothing in Visual Basic) or the message to be signed does not include the header specifying the sender (Sender or From header) or headersToSign array (if not null) does not list the name of that header or the sender's e-mail address domain is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If you need more advanced level of DomainKeys/DKIM signing or additional information on private keys, certificates and so on, refer to DomainKeys class.

Moreover, in ideal case it should be your your mail server's job to sign outgoing e-mails with DomainKeys/DKIM signatures. Use MailBee only if you cannot enable this feature on your mail server.

To make MailBee automatically DK/DKIM sign all outgoing e-mail messages created from this MailMessage instance, call SetDomainKeysSignOnSend(Boolean, Boolean, String, String, Boolean, String, DomainKeysTypes) method of Builder object.

Note Note
Be sure to enable FipsMode if the current system is FIPS-compliant.
Examples
This sample composes a simple e-mail, signs it with DomainKeys and DKIM signatures and sends it out. We assume the private certificate is in "C:\Temp\rsa512.private" file and the domain selector is "dk".
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;
using MailBee.Security;

class Sample
{
    static void Main(string[] args)
    {
        // Initialize mailer.
        Smtp mailer = new Smtp();

        // Set the message properties.
        mailer.Message.From.Email = "john.doe@company.com";
        mailer.Message.To.Add("jane.doe@example.com");
        mailer.Message.Subject = "Hello";
        mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?";

        // Sign the message with DomainKeys and DKIM.
        mailer.Message.DomainKeysSign(false, null, @"C:\Temp\rsa512.private", true, "dk", DomainKeysTypes.Both);

        // Send the message via SMTP server (authentication is used in this sample).
        mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret");
        mailer.Send();
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports MailBee.Security

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Initialize mailer.
        Dim mailer As Smtp = New Smtp()

        ' Set the message properties.
        mailer.Message.From.Email = "john.doe@company.com"
        mailer.Message.To.Add("jane.doe@example.com"")
        mailer.Message.Subject = "Hello"
        mailer.Message.BodyPlainText = "Hello, Jane, can we meet today?"

        ' Sign the message with DomainKeys and DKIM.
        mailer.Message.DomainKeysSign(False, Nothing, "C:\Temp\rsa512.private", True, "dk", DomainKeysTypes.Both)

        ' Send the message via SMTP server (authentication is used in this sample).
        mailer.SmtpServers.Add("mail.company.com", "john.doe@company.com", "secret")
        mailer.Send()
    End Sub
End Class
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.SecurityDomainKeys


MailMessage.DomainKeysVerify Method

MailMessageDomainKeysVerify Method
Verifies DKIM and classic DomainKeys signatures of the current e-mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DomainKeysVerifyResult DomainKeysVerify()
Public Function DomainKeysVerify As DomainKeysVerifyResult

Return Value

Type: DomainKeysVerifyResult
The result of the verification.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If the message contains only one signature (e.g. only DomainKeys or only DKIM), this method will still succeed (provided that this signature is valid).

If you need more advanced level of DomainKeys/DKIM verification (for instance, check multiple DKIM signatures in the same message), use DomainKeys class.

Note Note
If the current system is FIPS-compliant and runs .NET 2.0/3.5 and the message contains only DKIM signature created using SHA256 algorithm, the method will return Sha256NotSupported or throw an exception if ThrowExceptions is enabled. This can only occur with older .NET versions (before 4.0) because there was no FIPS-certified SHA256 implementation at that time. On a FIPS system, use MailBee.NET.dll for .NET 4.0+ to avoid these issues. See FipsMode and DomainKeysVerifyResult topics for details.

This method needs to make queries to a DNS server. For that, it executes Autodetect method. On some platforms like Xamarin autodetection may not work. You can manually populate DnsServers collection to workaround this.

Examples
This example displays the status of DomainKeys/DKIM signature of the last e-mail in the inbox.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;
using MailBee.Pop3Mail;

class Sample
{
    static void Main(string[] args)
    {
        // Download the last e-mail in inbox.
        MailMessage msg = Pop3.QuickDownloadMessage(
            "mail.company.com", "alex@company.com", "secret", -1);

        // Display the result of DomainKeys/DKIM verification.
        Console.WriteLine(msg.DomainKeysVerify().ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security
Imports MailBee.Pop3Mail

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Download the last e-mail in inbox.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage( _
            "mail.company.com", "alex@company.com", "secret", -1)

        ' Display the result of DomainKeys/DKIM verification.
        Console.WriteLine(msg.DomainKeysVerify().ToString())
    End Sub
End Class
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.SecurityDomainKeys


MailMessage.DomainKeysVerifyAsync Method

MailMessageDomainKeysVerifyAsync Method
async/await version of DomainKeysVerify.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<DomainKeysVerifyResult> DomainKeysVerifyAsync()
Public Function DomainKeysVerifyAsync As Task(Of DomainKeysVerifyResult)

Return Value

Type: Task DomainKeysVerifyResult
A task that represents the asynchronous operation. The value of TResult parameter is the result of the verification.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.EncodeAllHeaders Method

MailMessageEncodeAllHeaders Method
Encodes all message headers into the specified encoding.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void EncodeAllHeaders(
    Encoding targetEncoding,
    HeaderEncodingOptions options
)
Public Sub EncodeAllHeaders (
    targetEncoding As Encoding,
    options As HeaderEncodingOptions
)

Parameters

targetEncoding
Type: System.TextEncoding
The charset which is used to encode the value of the specified header.
options
Type: MailBee.MimeHeaderEncodingOptions
The additional options which affect how the message headers are encoded.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | targetEncoding is a null reference (Nothing in Visual Basic).
Remarks

The developer should use this method before saving or sending an e-mail message if any message headers or attachment names contain international characters.

The developer can also encode custom header names using GetEncodedHeaderValue(String, String, Encoding, HeaderEncodingOptions) method.

Examples
This sample loads the message from .EML file, encodes it, and saves this message to disk.
C#
VB
Copy
// To use the code below, import the following namespaces at the top of your code.
using System.Text;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\source.eml");
msg.EncodeAllHeaders(Encoding.UTF8, HeaderEncodingOptions.Base64);
msg.SaveMessage(@"C:\Temp\result.eml");
' To use the code below, import the following namespaces at the top of your code.
Imports System.Text
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\source.eml")
msg.EncodeAllHeaders(Encoding.UTF8, HeaderEncodingOptions.Base64)
msg.SaveMessage("C:\Temp\result.eml")
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.MimeHeaderEncodingOptions


MailMessage.Finalize Method

MailMessageFinalize Method
Finalizes the instance of MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected override void Finalize()
Protected Overrides Sub Finalize

Implements

ObjectFinalize
Remarks
The developer may call Dispose method to finalize an instance of MailMessage object manually.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.ForwardAsAttachment Method

MailMessageForwardAsAttachment Method
Forwards a mail message as attached .EML file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage ForwardAsAttachment()
Public Function ForwardAsAttachment As MailMessage

Return Value

Type: MailMessage
A new MailMessage object containing the message as attached .EML file.
Remarks
This method constructs a new e-mail message and adds original message as an attachment, all other fields of the new message remain empty (such as Subject, Body, To, Cc and Bcc fields, etc).
Examples
This sample loads the message from .EML file, forwards it as attachment and sends the resulting message out.
C#
VB
Copy
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\msg.eml");

        // Create a new message having the forwarded message as attachment.
        MailMessage newMsg = msg.ForwardAsAttachment();

        // Set up other fields of the envelope message.
        newMsg.From.AsString = "John Doe <jdoe@domain.com>";
        newMsg.To.AsString = "Alice <al@company.com>";
        newMsg.Subject = "Forwarded message";
        newMsg.BodyPlainText = "The message is attached.";

        // Send it.
        Smtp.QuickSend(newMsg);
    }
}
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\msg.eml")

        ' Create a new message having the forwarded message as attachment.
        Dim newMsg As MailMessage = msg.ForwardAsAttachment()

        ' Set up other fields of the envelope message.
        newMsg.From.AsString = "John Doe <jdoe@domain.com>"
        newMsg.To.AsString = "Alice <al@company.com>"
        newMsg.Subject = "Forwarded message"
        newMsg.BodyPlainText = "The message is attached."

        ' Send it.
        Smtp.QuickSend(newMsg)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.GetAllRecipients Method

MailMessageGetAllRecipients Method
Gets the EmailAddressCollection object containing the e-mail addresses of all message recipients.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection GetAllRecipients()
Public Function GetAllRecipients As EmailAddressCollection

Return Value

Type: EmailAddressCollection
An EmailAddressCollection object containing the e-mail addresses of all message recipients.
Remarks
The entire collection of the message recipients consists of the e-mail addresses that are contained in the To, Cc and Bcc fields.
Examples
This sample loads the message from .EML file and displays the e-mail addresses of all message recipients.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Display the e-mail address of each message recipient.
        Console.WriteLine("The message has the following recipient(s):");
        foreach (EmailAddress adr in msg.GetAllRecipients())
        {
            Console.WriteLine(adr.Email);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Display the e-mail address of each message recipient.
        Console.WriteLine("The message has the following recipient(s):")
        For Each adr As EmailAddress In msg.GetAllRecipients()
            Console.WriteLine(adr.Email)
        Next
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.GetEncodedHeaderValue Method

MailMessageGetEncodedHeaderValue Method
Encodes the value of the specified header.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string GetEncodedHeaderValue(
    string headerName,
    string headerValue,
    Encoding targetEncoding,
    HeaderEncodingOptions options
)
Public Shared Function GetEncodedHeaderValue (
    headerName As String,
    headerValue As String,
    targetEncoding As Encoding,
    options As HeaderEncodingOptions
) As String

Parameters

headerName
Type: SystemString
The name of the header.
headerValue
Type: SystemString
The value of the header.
targetEncoding
Type: System.TextEncoding
The charset which is used to encode the value of the specified header.
options
Type: MailBee.MimeHeaderEncodingOptions
The additional options which affect how the header is encoded.

Return Value

Type: String
A string containing the encoded value of the header.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | headerName or headerValue or targetEncoding is a null reference (Nothing in Visual Basic).
Examples
This sample encodes Subject header into UTF-8 (Quoted-Printable version) and save the message into a file.
C#
VB
Copy
// To use the code below, import the following namespaces at the top of your code.
using System.Text;
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();
msg.Subject = MailMessage.GetEncodedHeaderValue("Subject", "Any text here", Encoding.UTF8, HeaderEncodingOptions.ForceEncoding | HeaderEncodingOptions.Base64);
msg.SaveMessage(@"C:\Temp\msg.eml");
' To use the code below, import the following namespaces at the top of your code.
Imports System.Text
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage
msg.Subject = MailMessage.GetEncodedHeaderValue("Subject", "Any text here", Encoding.UTF8, HeaderEncodingOptions.ForceEncoding Or HeaderEncodingOptions.Base64)
msg.SaveMessage("C:\Temp\msg.eml")
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.MimeHeaderEncodingOptions


MailMessage.GetHtmlAndRelatedFilesInMemory Method

MailMessageGetHtmlAndRelatedFilesInMemory Method
Gets HTML body with references to all inline attachments being replaced with user-defined indexed paths.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetHtmlAndRelatedFilesInMemory(
    string virtualPathPrefix
)
Public Function GetHtmlAndRelatedFilesInMemory (
    virtualPathPrefix As String
) As String

Parameters

virtualPathPrefix
Type: SystemString
The prefix to prepend to each inline attachment index.

Return Value

Type: String
The value of BodyHtmlText property with inline attachment CIDs replaced with user-defined paths.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | virtualPathPrefix is a null reference (Nothing in Visual Basic).
Remarks

This method is useful if you want to store inline attachments on an external storage or in database (i.e. not on the local filesystem). It does not save anything to disk, just replaces content-id references in the HTML body with a provided path and auto-incrementing index. However, for each inline attachment in Attachments collection, its SavedAs value is still set (you can use it to find out which value was assigned to each particular inline attachment). Non-inline attachments are not touched and their SavedAs remains an empty string.

You can then access binary content of each inline attachment with GetData method.

This method is a shortcut for GetHtmlAndSaveRelatedFiles(virtualPathPrefix, VirtualMappingType.StaticInMemory, MessageFolderBehavior.DoNotCreate).

Examples
This sample loads an e-mail from a file (you can load it from a mail server or elsewhere), replaces CIDs and then processes inline attachments. It's assumed you'll provide your own implementation of this processing (e.g. uploading files to a cloud storage or CDN).
C#
VB
Copy
using System;
using MailBee.Mime;

class Sample
{
    static void UploadToExternalStorage(string webPath, byte[] bytes)
    {
        // This method must upload 'bytes' to some location which is also visible via web as 'webPath'.
    }

    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\test.eml");

        // You'll then pass 'body' value to some kind of a browser or webview control.
        // 'body' will have links like <IMG SRC="cid:my_first_img"> and <IMG SRC="cid:my_second_img">
        // look like <IMG SRC="https://domain.com/attach_1"> and <IMG SRC="https://domain.com/attach_2">
        string body = msg.GetHtmlAndRelatedFilesInMemory("https://domain.com/attach_");

        foreach (Attachment attach in msg.Attachments)
        {
            if (!string.IsNullOrEmpty(attach.SavedAs))
            {
                string webPath = attach.SavedAs; // e.g. https://domain.com/attach_1
                byte[] bytes = attach.GetData();

                UploadToExternalStorage(webPath, bytes);
            }
        }
    }
}
Imports System
Imports MailBee.Mime

Class Sample
    Shared Sub UploadToExternalStorage(ByVal webPath As String, ByVal bytes As Byte())
        ' This method must upload 'bytes' to some location which is also visible via web as 'webPath'.
    End Sub

    Shared Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage()
        msg.LoadMessage("C:\Temp\test.eml")

        ' You'll then pass 'body' value to some kind of a browser or webview control.
        ' 'body' will have links like <IMG SRC="cid:my_first_img"> and <IMG SRC="cid:my_second_img">
        ' look like <IMG SRC="https://domain.com/attach_1"> and <IMG SRC="https://domain.com/attach_2">
        Dim body As String = msg.GetHtmlAndRelatedFilesInMemory("https://domain.com/attach_")

        For Each attach As Attachment In msg.Attachments
            If Not String.IsNullOrEmpty(attach.SavedAs) Then
                Dim webPath As String = attach.SavedAs
                ' e.g. https://domain.com/attach_1
                Dim bytes As Byte() = attach.GetData()

                UploadToExternalStorage(webPath, bytes)
            End If
        Next
    End Sub
End Class
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageGetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior)


MailMessage.GetHtmlAndSaveRelatedFiles Method

MailMessageGetHtmlAndSaveRelatedFiles Method
Extracts the HTML body of the message and saves the attached inline pictures and other related files to disk, replaces their Content-ID's with file paths in the temporary location where they were saved, and returns the modified HTML body as a string.
Overload List
Name | Description
GetHtmlAndSaveRelatedFiles | Extracts the HTML body of the message, saves the attached inline pictures and other related files to disk, and return the modified HTML body.
GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) | Prepares the HTML body of the message for displaying in a web application: saves all embedded objects to a temporary location, replaces their Content-ID's with their virtual paths in the temporary location, and returns the modified HTML body as a string.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.GetHtmlAndSaveRelatedFiles Method

MailMessageGetHtmlAndSaveRelatedFiles Method
Extracts the HTML body of the message, saves the attached inline pictures and other related files to disk, and return the modified HTML body.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetHtmlAndSaveRelatedFiles()
Public Function GetHtmlAndSaveRelatedFiles As String

Return Value

Type: String
A string containing the HTML body which is altered in such a way so that all Content-ID references (cid:) are replaced with paths to the related files as they were saved by this method.
Remarks

The inline objects referenced in the HTML body of the message (i.e. embedded objects) are saved into a sub-folder in a folder denoted by MailMessage.Parser.WorkingFolder property. The links to the embedded objects in the returned HTML data are corrected automatically. The value of BodyHtmlText property is left intact.

This overload creates a message folder in MailMessage.Parser.WorkingFolder but does not delete it when this MailMessage object gets disposed. If this is not what you want, you can use GetHtmlAndSaveRelatedFiles(string, VirtualMappingType, MessageFolderBehavior) overload to specify another MessageFolderBehavior mode OR just remove the message folder when it's no longer needed. For the latter, you need to know the filepath of the message folder. To get it, call MailMessage.Parser.GetMessageFolder method after the message folder has been created during GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method call.

If you're saving the resulting HTML file NOT in the current folder, it's strongly recommended to explicitly set MailMessage.Parser.WorkingFolder prior to calling this method. Otherwise, you won't get embedded images displayed as relative paths in the saved HTML file and on the filesystem won't match. Or, just use SaveHtmlAndRelatedFiles(String) method.

Note Note
You may consider much simpler way of showing HTML e-mails with embedded images by direct base64 embedding of these images into the HTML. Use GetHtmlWithBase64EncodedRelatedFiles method for that.
Examples
This sample creates an HTML file from the e-mail message. The related files will also be saved into the same location.
Note Note
You can also use SaveHtmlAndRelatedFiles(String) method to save messages as HTML pages.
C#
VB
Copy
using System.IO;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Set the folder where all related files should be saved.
        msg.Parser.WorkingFolder = @"C:\Temp";

        // Generate an HTML file.
        using (StreamWriter sw = new StreamWriter(@"C:\Temp\web_page.htm", false))
        {
            sw.Write(msg.GetHtmlAndSaveRelatedFiles());
        }
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Set the folder where all related files should be saved.
        msg.Parser.WorkingFolder = "C:\Temp"

        ' Generate an HTML file.
        Dim sw As StreamWriter
        Try
            sw = New StreamWriter("C:\Temp\web_page.htm", False)
            sw.Write(msg.GetHtmlAndSaveRelatedFiles())
        Finally
            If Not sw Is Nothing Then
                sw.Close()
            End If
        End Try
    End Sub
End Module
See Also

Reference

MailMessage Class
GetHtmlAndSaveRelatedFiles Overload
MailBee.Mime Namespace
MailMessageGetHtmlWithBase64EncodedRelatedFiles


MailMessage.GetHtmlAndSaveRelatedFiles Method (String, VirtualMappingType, MessageFolderBehavior)

MailMessageGetHtmlAndSaveRelatedFiles Method (String, VirtualMappingType, MessageFolderBehavior)
Prepares the HTML body of the message for displaying in a web application: saves all embedded objects to a temporary location, replaces their Content-ID's with their virtual paths in the temporary location, and returns the modified HTML body as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetHtmlAndSaveRelatedFiles(
    string virtualPath,
    VirtualMappingType mappingType,
    MessageFolderBehavior folderMode
)
Public Function GetHtmlAndSaveRelatedFiles (
    virtualPath As String,
    mappingType As VirtualMappingType,
    folderMode As MessageFolderBehavior
) As String

Parameters

virtualPath
Type: SystemString
The virtual path to the MailMessage.Parser.WorkingFolder of the message. If mappingType is NonWeb, this parameter value is ignored, and the developer can leave it a null reference (Nothing in Visual Basic).
mappingType
Type: MailBee.MimeVirtualMappingType
The mode of mapping physical paths to virtual paths.
folderMode
Type: MailBee.MimeMessageFolderBehavior
Specifies whether to create and use a unique message folder in the MailMessage.Parser.WorkingFolder. Ignored when mappingType value is Base64 or StaticInMemory.

Return Value

Type: String
A string containing the HTML body which is altered in such a way so that all Content-ID references (cid:) are replaced with paths to the related files as they were saved by this method.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | virtualPath is a null reference (Nothing in Visual Basic) and mappingType is not NonWeb.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method can be used by the web application developer to display an HTML-formatted mail message with embedded pictures in the browser. In addition to the basic functionality provided by GetHtmlAndSaveRelatedFiles overload, this method is also capable of:
  1. Using virtual paths instead of physical paths when referencing embedded objects in HTML body. This is important for web applications where files are saved to disk using physical paths but referenced in HTML body using virtual paths.
  2. Creating a unique message folder in MailMessage.Parser.WorkingFolder and storing all message files there instead of placing all the files into MailMessage.Parser.WorkingFolder itself. This is important when multiple clients can use the system simultaneously and thus multiple messages can be stored in MailMessage.Parser.WorkingFolder at the same time. The name of this folder is an SHA1 digest of MessageID of the message. Since Message-ID's are unique, any particular message folder name is unique as well. Having unique subfolder for each message guarantees there will be no any collisions in multi-user environment.
    Note Note
    If folderMode is CreateOnly, the unique folder will be created and filled with the message files, but not deleted after the MailMessage object destruction. This is useful in web applications where all objects get automatically deleted once a response to the client has been generated. In this case, the message files/folder must retain after MailMessage destruction, and should only be deleted when the user has finished viewing the message (the user requested another page or the current session timed out). To remember which temporary folder to delete later, the application should save the names of the created unique folder in Session, database, or any other store which retains its data between round-trips to the server. To get this name, the developer can call MailMessage.Parser.GetMessageFolder method after the unique folder has been created during GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method call.
  3. Direct base64 embedding of images into the HTML body. This is the simplest method because you don't have to worry about temporary folderss, virtual paths and so on. Set mappingType to Base64 to activate this mode (other parameters will be ignored) or just use GetHtmlWithBase64EncodedRelatedFiles method instead.

mappingType specifies how physical paths to embedded pictures (and other inline attachments related in an HTML body and saved into temporary location by this method) are mapped into URI's placed into SRC elements of corresponding HTML tags.

For instance, if there is an HTML message with the following properties:

  • the HTML body contains <IMG SRC="cid:pic1">
  • the message contains the inline attachment picture.gif with ContentID (CID) pic1
  • the WorkingFolder is C:\Inetpub\wwwroot
  • the MessageID is <576201c5f939$0bfb96cb$19d717af@domain.com>
then GetHtmlAndSaveRelatedFiles("http://www.domain.com/", mappingType, MessageFolderBehavior.DoNotCreate) method call will replace cid:pic1 with the following value:
mappingType | IMG SRC value
NonWeb | C:\Inetpub\wwwroot\picture.gif
Static | http://www.domain.com/picture.gif
Dynamic | See description below
StaticInMemory | http://www.domain.com/1 (2, 3, etc)

If mappingType is Dynamic, the virtualPath parameter must point to a downloader page. Downloader page is a dynamic web page (such as an ASP.NET script) which should accept message_id and file_id parameters, grab file_id file in message_id folder and send its binary contents to the client. This allows the developer to save all inline attachments in the folder which is not directly visible from the web, and use the downloader script to push the file contents to the client. The downloader script can also check user credentials or SessionID to validate the user and do not return the attachment content if the user does not pass the authentication or session check.

message_id folder is the name of a unique message folder where all the files of the mail message are saved. If folderMode is DoNotCreate, the message files are saved directly in WorkingFolder, and message_id is an empty string.

file_id is a Filename of the inline attachment being referenced.

Thus, in Dynamic mode, MailBee replaces Content-ID (CID) with:
virtualPath + "message_id=" + SHA1Digest(Message-ID) + "&file_id=" + InlineAttachmentFilename.

For instance, GetHtmlAndSaveRelatedFiles("http://www.domain.com/download.aspx?session_id=12345&", VirtualMappingType.Dynamic, MessageFolderBehavior.CreateOnly) method call will replace cid:pic1 with http://www.domain.com/download.aspx?session_id=12345&message_id=D41D8CD98F00B204E9800998ECF8427E&file_id=picture.gif.

For more info on , refer to method.

Examples
This sample saves the email message as HTML file along with its related files (if any).
Note Note

You can also use SaveHtmlAndRelatedFiles(String) method to save messages as HTML pages.

URI is a synonym of an URL.

C#
VB
Copy
using System.IO;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Set the folder where all related files should be saved.
        msg.Parser.WorkingFolder = @"C:\Temp";

        // Generate a web page at the specified location.
        using (StreamWriter sw = new StreamWriter(@"C:\Temp\web_page.htm", false))
        {
            sw.Write(msg.GetHtmlAndSaveRelatedFiles(@"C:\Temp",
                VirtualMappingType.NonWeb, MessageFolderBehavior.CreateAndDelete));
        }
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Set the folder where all related files should be saved.
        msg.Parser.WorkingFolder = "C:\Temp"

        ' Generate a web page at the specified location.
        Dim sw As StreamWriter
        Try
            sw = New StreamWriter("C:\Temp\web_page.htm", False)
            sw.Write(msg.GetHtmlAndSaveRelatedFiles("C:\Temp", _
                VirtualMappingType.NonWeb, MessageFolderBehavior.CreateAndDelete))
        Finally
            If Not sw Is Nothing Then
                sw.Close()
            End If
        End Try
    End Sub
End Module
See Also

Reference

MailMessage Class
GetHtmlAndSaveRelatedFiles Overload
MailBee.Mime Namespace
MailMessageSaveHtmlAndRelatedFiles(String)
MailMessageGetHtmlWithBase64EncodedRelatedFiles
MessageParserConfigPlainToHtmlMode
MessageParserConfigWorkingFolder
VirtualMappingTypeStaticInMemory
MailMessageGetHtmlAndRelatedFilesInMemory(String)


MailMessage.GetHtmlAndSaveRelatedFilesAsync Method

MailMessageGetHtmlAndSaveRelatedFilesAsync Method
Overload List
 | Name | Description
Public method | GetHtmlAndSaveRelatedFilesAsync | async/await version of GetHtmlAndSaveRelatedFiles.
Public method | GetHtmlAndSaveRelatedFilesAsync(String, VirtualMappingType, MessageFolderBehavior) | async/await version of GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior).
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.GetHtmlAndSaveRelatedFilesAsync Method

MailMessageGetHtmlAndSaveRelatedFilesAsync Method
async/await version of GetHtmlAndSaveRelatedFiles.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string> GetHtmlAndSaveRelatedFilesAsync()
Public Function GetHtmlAndSaveRelatedFilesAsync As Task(Of String)

Return Value

Type: Task String
A task that represents the asynchronous operation. The value of TResult parameter is a string containing the HTML body which is altered in such a way so that all Content-ID references (cid:) are replaced with paths to the related files as they were saved by this method.
See Also

Reference

MailMessage Class
GetHtmlAndSaveRelatedFilesAsync Overload
MailBee.Mime Namespace


MailMessage.GetHtmlAndSaveRelatedFilesAsync Method (String, VirtualMappingType, MessageFolderBehavior)

MailMessageGetHtmlAndSaveRelatedFilesAsync Method (String, VirtualMappingType, MessageFolderBehavior)
async/await version of GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string> GetHtmlAndSaveRelatedFilesAsync(
    string virtualPath,
    VirtualMappingType mappingType,
    MessageFolderBehavior folderMode
)
Public Function GetHtmlAndSaveRelatedFilesAsync (
    virtualPath As String,
    mappingType As VirtualMappingType,
    folderMode As MessageFolderBehavior
) As Task(Of String)

Parameters

virtualPath
Type: SystemString
The virtual path to the MailMessage.Parser.WorkingFolder of the message. If mappingType is NonWeb, this parameter value is ignored, and the developer can leave it a null reference (Nothing in Visual Basic).
mappingType
Type: MailBee.MimeVirtualMappingType
The mode of mapping physical paths to virtual paths.
folderMode
Type: MailBee.MimeMessageFolderBehavior
Specifies whether to create and use a unique message folder in the MailMessage.Parser.WorkingFolder.

Return Value

Type: Task String
A task that represents the asynchronous operation. The value of TResult parameter is a string containing the HTML body which is altered in such a way so that all Content-ID references (cid:) are replaced with paths to the related files as they were saved by this method.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | virtualPath is a null reference (Nothing in Visual Basic) and mappingType is not NonWeb.
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
GetHtmlAndSaveRelatedFilesAsync Overload
MailBee.Mime Namespace


MailMessage.GetHtmlWithBase64EncodedRelatedFiles Method

MailMessageGetHtmlWithBase64EncodedRelatedFiles Method
Gets the HTML body with all related files being embedded directly in the HTML body as base64 chunks.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetHtmlWithBase64EncodedRelatedFiles()
Public Function GetHtmlWithBase64EncodedRelatedFiles As String

Return Value

Type: String
A string containing the HTML body which is altered in such a way so that all Content-ID references (cid:) are replaced with base64 chunks with the contents of the related files.
Remarks

This method does not save anything to disk and no I/O activity of any kind occurs (hence no async version). It's easier to use it than methods which save related file to disk. The drawback is when the message has very large images (the resulting HTML string can grow large as well). In practice, this is usually not a concern so using this method is recommended whenever possible.

Examples
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using System;
using MailBee;
using MailBee.Mime;
using MailBee.ImapMail;

// The actual code (put it into a method of your class).
Imap imp = new Imap();

// Log if useful for debugging.
imp.Log.Enabled = true;
imp.Log.Filename = @"C:\Temp\log.txt";
imp.Log.Clear();

imp.Connect("mail.domain.com");
imp.Login("test@domain.com", "secret");
imp.SelectFolder("Inbox");

// Download the last e-mail in Inbox.
MailMessage msg = imp.DownloadEntireMessage(imp.MessageCount, false);
string html = msg.GetHtmlWithBase64EncodedRelatedFiles();
imp.Disconnect();
// You can now load 'html' in WebBrowser control, etc.
' To use the code below, import MailBee namespaces at the top of your code.
Imports System;
Imports MailBee;
Imports MailBee.Mime;
Imports MailBee.ImapMail;

' The actual code (put it into a method of your class).
Dim imp As New Imap()

' Log if useful for debugging.
imp.Log.Enabled = True
imp.Log.Filename = "C:\Temp\log.txt"
imp.Log.Clear()

imp.Connect("mail.domain.com")
imp.Login("test@domain.com", "secret")
imp.SelectFolder("Inbox")

' Download the last e-mail in Inbox.
Dim msg As MailMessage = imp.DownloadEntireMessage(imp.MessageCount, False)
Dim html As String = msg.GetHtmlWithBase64EncodedRelatedFiles()
imp.Disconnect()

' You can now load 'html' in WebBrowser control, etc.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.GetMessageRawData Method

MailMessageGetMessageRawData Method
Gets the source of the message as a byte array.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] GetMessageRawData()
Public Function GetMessageRawData As Byte()

Return Value

Type: Byte
A byte array representing the MIME source of the message.
Remarks
To get only a header section of the message, use RawHeader property. To save the message to disk or into a stream, use SaveMessage(String) method.
Examples
This sample saves the MIME source of the message into .EML file for demonstration purposes only. Real-world applications should use SaveMessage(String) method for this.
C#
VB
Copy
using System.IO;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("mail.company.com", "jdoe", "password", 1);

        // Save message as .EML file.
        using (BinaryWriter bw = new BinaryWriter(File.Open(@"C:\Temp\msg.eml",
            FileMode.Create)))
        {
            bw.Write(msg.GetMessageRawData());
        }
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("mail.company.com", "jdoe", "password", 1)

        ' Save message as .EML file.
        Dim bw As BinaryWriter
        Try
            bw = New BinaryWriter(File.Open("C:\Temp\msg.eml", FileMode.Create))
            bw.Write(msg.GetMessageRawData())
        Finally
            If Not bw Is Nothing Then
                bw.Close()
            End If
        End Try
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.ImportRelatedFiles Method

MailMessageImportRelatedFiles Method
Adds all the related files (referenced in HTML part of the message) as inline attachments.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ImportRelatedFiles(
    ImportRelatedFilesOptions options
)
Public Function ImportRelatedFiles (
    options As ImportRelatedFilesOptions
) As Boolean

Parameters

options
Type: MailBee.MimeImportRelatedFilesOptions
The additional options which affect how the files related to the HTML body are added to the message.

Return Value

Type: Boolean
true if the related files were successfully added as inline attachments; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

All links to the related files (external documents which are referenced in BodyHtmlText) are replaced with Content-IDs generated for these files when they were attached.

To detect which URIs in the HTML body reference resources which can be added as related files to the message, MailBee examines each URI and checks if it's a web resource or local file system resource. Web resources are ignored unless ImportFromUris option is specified. If the URI contains absolute path on the filesystem, this path is used to load the file. If the URI contains relative path, MailBee by gets the file from MailMessage.Builder.RelatedFilesFolder location. If MailBee was unable to find a resource based on the denoted by the given URIs, such URI is left intact and the inline attachment for that URI is not added.

OnReplaceUriWithCid delegate provides an additional control on which referenced resources get imported and which are not.

Examples
This sample generates a new mail message from HTML file and sends it.
C#
VB
Copy
using System.IO;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the HTML content from the specified file.
        string textHtml = string.Empty;
        using (StreamReader sr = new StreamReader(@"C:\Temp\web_page.htm"))
        {
            textHtml = sr.ReadToEnd();
        }

        // Create a new message and set HTML body of this message.
        MailMessage msg = new MailMessage();
        msg.BodyHtmlText = textHtml;

        // Import all related files from URIs and then send the message.
        msg.ImportRelatedFiles(ImportRelatedFilesOptions.ImportFromUris);
        Smtp.QuickSend(msg);
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the HTML content from the specified file.
        Dim textHtml As String = String.Empty
        Dim sr As StreamReader
        Try
            sr = New StreamReader("C:\Temp\web_page.htm")
            textHtml = sr.ReadToEnd()
        Finally
            If Not sr Is Nothing Then
                sr.Close()
            End If
        End Try

        ' Create a new message and set HTML body of this message.
        Dim msg As New MailMessage
        msg.BodyHtmlText = textHtml

        ' Import all related files from URIs and then send the message.
        msg.ImportRelatedFiles(ImportRelatedFilesOptions.ImportFromUris)
        Smtp.QuickSend(msg)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.MimeImportRelatedFilesOptions
MailMessageLoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions)


MailMessage.ImportRelatedFilesAsync Method

MailMessageImportRelatedFilesAsync Method
async/await version of ImportRelatedFiles(ImportRelatedFilesOptions).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ImportRelatedFilesAsync(
    ImportRelatedFilesOptions options
)
Public Function ImportRelatedFilesAsync (
    options As ImportRelatedFilesOptions
) As Task(Of Boolean)

Parameters

options
Type: MailBee.MimeImportRelatedFilesOptions
The additional options which affect how the files related to the HTML body are added to the message.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the related files were successfully added as inline attachments; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.IsBodyAvail Method

MailMessageIsBodyAvail Method
Indicates if the body of the specified format is present in the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBodyAvail(
    string bodyFormat,
    bool originalBodyOnly
)
Public Function IsBodyAvail (
    bodyFormat As String,
    originalBodyOnly As Boolean
) As Boolean

Parameters

bodyFormat
Type: SystemString
The content type of the body to be searched (e.g. text/plain).
originalBodyOnly
Type: SystemBoolean
Indicates if only the original parts of the message should be processed.

Return Value

Type: Boolean
true if the body of specified format is present in the message; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | bodyFormat is a null reference (Nothing in Visual Basic).
Remarks

A message may contain original MIME parts (they had already been present in the existing message when it was parsed) and MIME parts added by MailBee (for instance, they may appear when the existing message gets parsed by MailBee and MailBee automatically creates plain-text part if only HTML part is available in the message).

To access text bodies of the message, you can use BodyPlainText, BodyHtmlText, and BodyParts properties.

To make the plain-text body be automatically created from the HTML body if the plain-text body is missing, set HtmlToPlainMode property to IfNoPlain value. See BodyPlainText and BodyHtmlText topics for more information.

Examples
This sample loads the message from .EML file and checks if it has an XML body.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
if (msg.IsBodyAvail("text/xml", false))
{
    Console.WriteLine("Message does contain XML body.");
}
else
{
    Console.WriteLine("Message does not contain XML body.");
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
If msg.IsBodyAvail("text/html", False) Then
    Console.WriteLine("Message does contain XML body.")
Else
    Console.WriteLine("Message does not contain XML body.")
End If
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageBodyParts
MailMessageParser


MailMessage.LoadBodyText Method

MailMessageLoadBodyText Method
Loads the contents of the specified file (or URI) into HTML or plain-text body.
Overload List
Name | Description
LoadBodyText(String, MessageBodyType) | Loads the contents of the specified file into HTML or plain-text body of the message.
LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) | Loads the contents of the specified file or web page into HTML or plain-text body of the message, also attaching related objects such as inline images if necessary.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.LoadBodyText Method (String, MessageBodyType)

MailMessageLoadBodyText Method (String, MessageBodyType)
Loads the contents of the specified file into HTML or plain-text body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LoadBodyText(
    string filename,
    MessageBodyType bodyType
)
Public Function LoadBodyText (
    filename As String,
    bodyType As MessageBodyType
) As Boolean

Parameters

filename
Type: SystemString
The absolute or relative path to the file containing the text to be imported.
bodyType
Type: MailBee.MimeMessageBodyType
Denotes whether to load the data into HTML body or into plain-text body.

Return Value

Type: Boolean
true if the text was successfully imported; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks
This method does not automatically attach pictures and other files referenced in the HTML content being imported. Use ImportRelatedFiles(ImportRelatedFilesOptions) method or LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) for this. The latter can also be used to load HTML body from a web location rather than from local filesystem.
Examples
This sample creates a new message and loads HTML body from .HTM file.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();
msg.LoadBodyText(@"C:\Temp\web_page.htm", MessageBodyType.Html);
msg.SaveMessage(@"C:\Temp\msg.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage
msg.LoadBodyText("C:\Temp\web_page.htm", MessageBodyType.Html)
msg.SaveMessage("C:\Temp\msg.eml")
See Also

Reference

MailMessage Class
LoadBodyText Overload
MailBee.Mime Namespace
MailMessageImportRelatedFiles(ImportRelatedFilesOptions)
MailMessageBuilder


MailMessage.LoadBodyText Method (String, MessageBodyType, Encoding, ImportBodyOptions)

MailMessageLoadBodyText Method (String, MessageBodyType, Encoding, ImportBodyOptions)
Loads the contents of the specified file or web page into HTML or plain-text body of the message, also attaching related objects such as inline images if necessary.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LoadBodyText(
    string path,
    MessageBodyType bodyType,
    Encoding sourceEncoding,
    ImportBodyOptions options
)
Public Function LoadBodyText (
    path As String,
    bodyType As MessageBodyType,
    sourceEncoding As Encoding,
    options As ImportBodyOptions
) As Boolean

Parameters

path
Type: SystemString
The path to the file containing the text to be loaded into the message body. This path can be an URI (such as web page URL or file path specified as file:///) if options value includes PathIsUri flag.
bodyType
Type: MailBee.MimeMessageBodyType
Denotes whether to load the data into HTML body or into plain-text body.
sourceEncoding
Type: System.TextEncoding
The charset of the data in the file being loaded. If a null reference (Nothing in Visual Basic), DefaultEncoding will be assumed (unless the charset information is available in META tag of the HTML data being loaded).
options
Type: MailBee.MimeImportBodyOptions
A set of flags which affect how the data is loaded from the file into the message body and whether (and how) the related objects should be attached.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | path is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeWebException | A downloading error occurred and ThrowExceptions is true.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks

When bodyType is Plain, this method loads the data into BodyPlainText.

When bodyType is Html, this method loads the data into BodyHtmlText and optionally adds all related files (objects referenced in the HTML body) as inline attachments. Automatic attaching of related files can be enabled with ImportRelatedFiles flag specified in options parameter.

To embed related files if the HTML body is not available as a file (for instance, if it's taken from database or created in memory), use ImportRelatedFiles(ImportRelatedFilesOptions) method. The current method simply loads the data from the file (or URL) and then calls ImportRelatedFiles(ImportRelatedFilesOptions). ImportRelatedFiles(ImportRelatedFilesOptions) topic also describes advanced topics of embedding related files into the message.

OnReplaceUriWithCid delegate provides an additional control on which referenced resources get imported and which are not.

Examples
This sample creates a new message, loads HTML body from .HTM file, and adds all files referenced in this body as attachments. Although the .HTM file itself it taken from disk (not from web location), we use ImportRelatedFilesFromUris flag to make related files be attached to the message even if they are not on the local filesystem but on the web. For instance, if the .HTM file being loaded contains <IMG SRC="http://www.company.com/logo.gif">, the resulting HTML body will have this text replaced with something like <IMG SRC="cid:de78fa3042283932f4e2"> and the logo.gif file will be embedded as inline attachment into the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();

msg.LoadBodyText(@"C:\Temp\report.htm", MessageBodyType.Html, System.Text.Encoding.Default,
    ImportBodyOptions.ImportRelatedFiles | ImportBodyOptions.ImportRelatedFilesFromUris);

msg.SaveMessage(@"C:\Temp\msg.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage

msg.LoadBodyText("C:\Temp\report.htm", MessageBodyType.Html, System.Text.Encoding.Default, _
    ImportBodyOptions.ImportRelatedFiles Or ImportBodyOptions.ImportRelatedFilesFromUris)

msg.SaveMessage("C:\Temp\msg.eml")
See Also

Reference

MailMessage Class
LoadBodyText Overload
MailBee.Mime Namespace
MailMessageImportRelatedFiles(ImportRelatedFilesOptions)
MailMessageBuilder


MailMessage.LoadBodyTextAsync Method

MailMessageLoadBodyTextAsync Method
Overload List
 | Name | Description
Public method | LoadBodyTextAsync(String, MessageBodyType) | async/await version of LoadBodyText(String, MessageBodyType).
Public method | LoadBodyTextAsync(String, MessageBodyType, Encoding, ImportBodyOptions) | async/await version of LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions).
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.LoadBodyTextAsync Method (String, MessageBodyType)

MailMessageLoadBodyTextAsync Method (String, MessageBodyType)
async/await version of LoadBodyText(String, MessageBodyType).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoadBodyTextAsync(
    string filename,
    MessageBodyType bodyType
)
Public Function LoadBodyTextAsync (
    filename As String,
    bodyType As MessageBodyType
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The absolute or relative path to the file containing the text to be imported.
bodyType
Type: MailBee.MimeMessageBodyType
Denotes whether to load the data into HTML body or into plain-text body.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the text was successfully imported; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
LoadBodyTextAsync Overload
MailBee.Mime Namespace


MailMessage.LoadBodyTextAsync Method (String, MessageBodyType, Encoding, ImportBodyOptions)

MailMessageLoadBodyTextAsync Method (String, MessageBodyType, Encoding, ImportBodyOptions)
async/await version of LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoadBodyTextAsync(
    string path,
    MessageBodyType bodyType,
    Encoding sourceEncoding,
    ImportBodyOptions options
)
Public Function LoadBodyTextAsync (
    path As String,
    bodyType As MessageBodyType,
    sourceEncoding As Encoding,
    options As ImportBodyOptions
) As Task(Of Boolean)

Parameters

path
Type: SystemString
The path to the file containing the text to be loaded into the message body. This path can be an URI (such as web page URL or file path specified as file:///) if options value includes PathIsUri flag.
bodyType
Type: MailBee.MimeMessageBodyType
Denotes whether to load the data into HTML body or into plain-text body.
sourceEncoding
Type: System.TextEncoding
The charset of the data in the file being loaded. If a null reference (Nothing in Visual Basic), DefaultEncoding will be assumed (unless the charset information is available in META tag of the HTML data being loaded).
options
Type: MailBee.MimeImportBodyOptions
A set of flags which affect how the data is loaded from the file into the message body and whether (and how) the related objects should be attached.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | path is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeWebException | A downloading error occurred and ThrowExceptions is true.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
LoadBodyTextAsync Overload
MailBee.Mime Namespace


MailMessage.LoadMessage Method

MailMessageLoadMessage Method
Loads the message from a byte array, a stream, or a file.
Overload List
Name | Description
LoadMessage(Byte) | Loads the message from a byte array.
LoadMessage(Stream) | Loads the message from a stream.
LoadMessage(String) | Loads the message from the specified file.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.LoadMessage Method (Byte[])

MailMessageLoadMessage Method (Byte)
Loads the message from a byte array.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LoadMessage(
    byte[] rawData
)
Public Function LoadMessage (
    rawData As Byte()
) As Boolean

Parameters

rawData
Type: SystemByte
The byte array containing the MIME source of the message.

Return Value

Type: Boolean
true if the message was successfully loaded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | rawData is a null reference (Nothing in Visual Basic).
MailBeeDataParsingException | Outlook .MSG file is being loaded instead of MIME (.EML) and ThrowExceptions is true.
Remarks

The MIME source of the message is the contents of .EML file (which you can import with LoadMessage(String) method).

To get an existing message as a byte array, use GetMessageRawData method.

Note Note
This method can change the contents of the source byte array. This may only occur in extremely rare case when line endings in there are single CR characters rather than CRLF pairs (correct endings) or single LF characters (incorrect but widely used). In this case, MailBee normalizes the data by replacing single CRs with LFs (not changing the length of the array). If for some reason you want to preserve the source data intact, make a copy of the source array before passing it to this method. To avoid unnecessary memory consumption, you can first check if the message data indeed contains CR line endings, and make a copy of the data only in this rare case.
Examples
This sample loads the message from a byte array and displays the subject of the message. Reading from a stream is used for demonstration purposes only. In real-world apps, it's easier to use LoadMessage(String) method to load a message from a file.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
byte[] msgBytes = null;
using (BinaryReader br = new BinaryReader(File.OpenRead(@"C:\Docs\TestMail.eml")))
{
    FileInfo fi = new FileInfo(@"C:\Docs\TestMail.eml");
    msgBytes = br.ReadBytes((int)fi.Length);
}
MailMessage msg = new MailMessage();
msg.LoadMessage(msgBytes);
Console.WriteLine(msg.Subject);
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msgBytes As Byte() = Nothing

Dim br As BinaryReader
Try
    br = New BinaryReader(File.OpenRead("C:\Docs\TestMail.eml"))
    Dim fi As New FileInfo("C:\Docs\TestMail.eml")
    msgBytes = br.ReadBytes(fi.Length)
Finally
    If Not br Is Nothing Then
        br.Close()
    End If
End Try

Dim msg As New MailMessage
msg.LoadMessage(msgBytes)
Console.WriteLine(msg.Subject)
See Also

Reference

MailMessage Class
LoadMessage Overload
MailBee.Mime Namespace
MailMessageGetMessageRawData


MailMessage.LoadMessage Method (Stream)

MailMessageLoadMessage Method (Stream)
Loads the message from a stream.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LoadMessage(
    Stream stream
)
Public Function LoadMessage (
    stream As Stream
) As Boolean

Parameters

stream
Type: System.IOStream
The stream containing the MIME source of the message.

Return Value

Type: Boolean
true if the message was successfully loaded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | stream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred and ThrowExceptions is true.
MailBeeDataParsingException | Outlook .MSG file is being loaded instead of MIME (.EML) and ThrowExceptions is true.
Remarks
To save a message into a stream, use SaveMessage(Stream) method.
Examples
This sample loads the message from the stream and displays the subject of the message.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
using (FileStream fs = new FileStream(@"C:\Docs\TestMail.eml", FileMode.Open))
{
    MailMessage msg = new MailMessage();
    msg.LoadMessage(fs);

    Console.WriteLine(msg.Subject);
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
Dim fs As FileStream
Try
    fs = New FileStream("C:\Docs\TestMail.eml", FileMode.Open)
    msg.LoadMessage(fs)
    Console.WriteLine(msg.Subject)
Finally
    If Not fs Is Nothing Then
        fs.Close()
    End If
End Try
See Also

Reference

MailMessage Class
LoadMessage Overload
MailBee.Mime Namespace
MailMessageSaveMessage(Stream)


MailMessage.LoadMessage Method (String)

MailMessageLoadMessage Method (String)
Loads the message from the specified file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LoadMessage(
    string filename
)
Public Function LoadMessage (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The path to the file containing the message in MIME format. The common extension of MIME files is .EML.

Return Value

Type: Boolean
true if the message was successfully loaded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
MailBeeDataParsingException | Outlook .MSG file is being loaded instead of MIME (.EML) and ThrowExceptions is true.
Remarks
To save a message into a file, use SaveMessage(String) method.
Examples
This sample loads the message from .EML file and displays the subject of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

Console.WriteLine(msg.Subject);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

Console.WriteLine(msg.Subject)
See Also

Reference

MailMessage Class
LoadMessage Overload
MailBee.Mime Namespace
MailMessageSaveMessage(String)


MailMessage.LoadMessageAsync Method

MailMessageLoadMessageAsync Method
Overload List
 | Name | Description
Public method | LoadMessageAsync(Stream) | async/await version of LoadMessage(Stream).
Public method | LoadMessageAsync(String) | async/await version of LoadMessage(String).
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.LoadMessageAsync Method (Stream)

MailMessageLoadMessageAsync Method (Stream)
async/await version of LoadMessage(Stream).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoadMessageAsync(
    Stream stream
)
Public Function LoadMessageAsync (
    stream As Stream
) As Task(Of Boolean)

Parameters

stream
Type: System.IOStream
The stream containing the MIME source of the message.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully loaded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | stream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred and ThrowExceptions is true.
MailBeeDataParsingException | Outlook .MSG file is being loaded instead of MIME (.EML) and ThrowExceptions is true.
See Also

Reference

MailMessage Class
LoadMessageAsync Overload
MailBee.Mime Namespace


MailMessage.LoadMessageAsync Method (String)

MailMessageLoadMessageAsync Method (String)
async/await version of LoadMessage(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoadMessageAsync(
    string filename
)
Public Function LoadMessageAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The path to the file containing the message in MIME format. The common extension of MIME files is .EML.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully loaded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
MailBeeDataParsingException | Outlook .MSG file is being loaded instead of MIME (.EML) and ThrowExceptions is true.
See Also

Reference

MailMessage Class
LoadMessageAsync Overload
MailBee.Mime Namespace


MailMessage.MakePlainBodyFromHtmlBody Method

MailMessageMakePlainBodyFromHtmlBody Method
Creates a plain text body from the existing HTML body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MakePlainBodyFromHtmlBody()
Public Function MakePlainBodyFromHtmlBody As Boolean

Return Value

Type: Boolean
true if the plain-text body was successfully generated from the HTML body; false if the message did not have an HTML body.
Remarks

This method overwrites the original value of BodyPlainText property if any. BodyHtmlText is left intact (i.e. this method does not replace HTML body with plain-text body, it rather adds alternative plain-text version of the HTML body to the message).

To make plain-text body be generated automatically when the message contains only HTML body, set msg.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain prior to sending the message (assuming msg is MailMessage instance).

If you are parsing an existing message (received from the mail server, loaded from file, etc) rather than composing a new one, set msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain instead.

Examples
This sample creates the HTML body of the message from .HTM file and converts it into the plain text body. Reading from stream and using MakePlainBodyFromHtmlBody is for demonstration purposes only. In real world apps, it's easier to use LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method to load the file and MailMessage.Builder.HtmlToPlainMode property to enable automatic creating plain-text version of the HTML body.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
using (StreamReader sr = new StreamReader(@"C:\Temp\doc.htm"))
{
    MailMessage msg = new MailMessage();
    msg.BodyHtmlText = sr.ReadToEnd();
    msg.MakePlainBodyFromHtmlBody();

    Console.WriteLine(msg.BodyPlainText);
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
Dim sr As StreamReader
Try
    sr = New StreamReader("C:\Temp\doc.htm")
    msg.BodyHtmlText = sr.ReadToEnd()
    msg.MakePlainBodyFromHtmlBody()

    Console.WriteLine(msg.BodyPlainText)
Finally
    If Not sr Is Nothing Then
        sr.Close()
    End If
End Try
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageBuilder


MailMessage.Reset Method

MailMessageReset Method
Resets all the properties of the MailMessage object to the default values.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reset()
Public Sub Reset
Remarks

This method allows processing multiple messages without re-creating MailMessage object for every message.

All information contained in the fields of the MailMessage object will be lost after using this method. Also, this method will delete any temporary files which could have been earlier created for this MailMessage object: although MailBee parses messages in memory, the developer may explicitly request automatic saving of the message as HTML file with MailMessage.Parser.AutoSaveHtmlMode property or using GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method. Such temporary files are deleted by the object destructor and by Reset and Dispose methods.

Examples
This sample loads the message from .EML file, shows its subject, resets the message and displays the subject again (it will be empty value second time).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
Console.WriteLine(msg.Subject);
msg.Reset();
Console.WriteLine(msg.Subject);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Console.WriteLine(msg.Subject)
msg.Reset()
Console.WriteLine(msg.Subject)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageClear(MessageElements)


MailMessage.SaveHtmlAndRelatedFiles Method

MailMessageSaveHtmlAndRelatedFiles Method
Saves the HTML body of the message and all inline pictures and other inline objects to disk.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveHtmlAndRelatedFiles(
    string filename
)
Public Function SaveHtmlAndRelatedFiles (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The HTML file to be written to.

Return Value

Type: Boolean
true if the body was successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks

All links to the embedded objects (pictures, CSS tables, etc) contained in the generated HTML file are automatically corrected to match the filenames assigned to these files when they were saved to disk.

By default, embedded objects are saved in the same folder where the HTML file resides. To store related files in another folder, set msg.Parser.WorkingFolder property prior to calling any method which can save related files.

Seting msg.Parser.WorkingFolder property value to some absolute path is mandatory in case if the HMTL in the e-mail message contains BASE tag (relative paths in URLs won't work correctly when BASE tag is present). Luckily, BASE tag is commonly not used in e-mail nowadays.

You can also tell MailBee to automatically save the message as HTML file to disk when the message gets parsed by setting msg.Parser.AutoSaveHtmlMode = HtmlMessageAutoSaving.SaveMessageHtmAndRelatedFiles (assuming msg is MailMessage instance). Another option is using GetHtmlAndSaveRelatedFiles method and its overloads.

If you're getting non-Latin characters not being displayed correctly in resulting HTML files, consider setting WriteUtf8ByteOrderMark to true (like in the sample code below).

Note Note
You may consider much simpler way of showing HTML e-mails with embedded images by direct base64 embedding of these images into the HTML. Use GetHtmlWithBase64EncodedRelatedFiles method for that. You can then save its result into an HTML file.
Examples
This sample loads the message from .EML file and generates HTML file containing the HTML body of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.WriteUtf8ByteOrderMark = true;
msg.SaveHtmlAndRelatedFiles(@"C:\Temp\doc.htm");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.WriteUtf8ByteOrderMark = True
msg.SaveHtmlAndRelatedFiles("C:\Temp\doc.htm")
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageGetHtmlAndSaveRelatedFiles


MailMessage.SaveHtmlAndRelatedFilesAsync Method

MailMessageSaveHtmlAndRelatedFilesAsync Method
async/await version of SaveHtmlAndRelatedFiles(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveHtmlAndRelatedFilesAsync(
    string filename
)
Public Function SaveHtmlAndRelatedFilesAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The HTML file to be written to.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the body was successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.SaveMessage Method

MailMessageSaveMessage Method
Saves a message into the specified file or stream.
Overload List
Name | Description
SaveMessage(Stream) | Saves a message into the specified stream.
SaveMessage(String) | Saves a message into the specified file.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.SaveMessage Method (Stream)

MailMessageSaveMessage Method (Stream)
Saves a message into the specified stream.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveMessage(
    Stream stream
)
Public Function SaveMessage (
    stream As Stream
) As Boolean

Parameters

stream
Type: System.IOStream
The stream where the message should be saved.

Return Value

Type: Boolean
true if the message was successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | stream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | The given stream does not support writing or stream I/O error occurred, and ThrowExceptions is true.
Remarks

The stream should already be opened for reading before this method can be called.

The developer can use LoadMessage(Stream) method to load the previously saved message.

If you need to produce a stream in .MSG format (which can then be opened in MS Outlook), use methods of MsgConvert class.

Examples
This sample loads the message from .EML file and saves it into the stream.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
using (FileStream fs = new FileStream(@"C:\Temp\msg.eml", FileMode.CreateNew))
{
    msg.SaveMessage(fs);
}
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Dim fs As FileStream
Try
    fs = New FileStream("C:\Temp\msg.eml", FileMode.CreateNew)
    msg.SaveMessage(fs)
Finally
    If Not fs Is Nothing Then
        fs.Close()
    End If
End Try
See Also

Reference

MailMessage Class
SaveMessage Overload
MailBee.Mime Namespace
MailMessageLoadMessage(String)


MailMessage.SaveMessage Method (String)

MailMessageSaveMessage Method (String)
Saves a message into the specified file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveMessage(
    string filename
)
Public Function SaveMessage (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The name of the file where it should be saved.

Return Value

Type: Boolean
true if the message was successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks

The common file extension of e-mails in MIME format is .EML. If you need to produce an .MSG file which can be opened by MS Outlook, use methods of MsgConvert class.

The developer can use LoadMessage(String) method to load the previously saved message.

Examples
The example is available in MailMessage class overview.
See Also

Reference

MailMessage Class
SaveMessage Overload
MailBee.Mime Namespace
MailMessageLoadMessage(String)


MailMessage.SaveMessageAsync Method

MailMessageSaveMessageAsync Method
Overload List
 | Name | Description
Public method | SaveMessageAsync(Stream) | async/await version of SaveMessage(Stream).
Public method | SaveMessageAsync(String) | async/await version of SaveMessage(String).
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.SaveMessageAsync Method (Stream)

MailMessageSaveMessageAsync Method (Stream)
async/await version of SaveMessage(Stream).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveMessageAsync(
    Stream stream
)
Public Function SaveMessageAsync (
    stream As Stream
) As Task(Of Boolean)

Parameters

stream
Type: System.IOStream
The stream where the message should be saved.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | stream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | The given stream does not support writing or stream I/O error occurred, and ThrowExceptions is true.
See Also

Reference

MailMessage Class
SaveMessageAsync Overload
MailBee.Mime Namespace


MailMessage.SaveMessageAsync Method (String)

MailMessageSaveMessageAsync Method (String)
async/await version of SaveMessage(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveMessageAsync(
    string filename
)
Public Function SaveMessageAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The name of the file where it should be saved.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully saved; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
SaveMessageAsync Overload
MailBee.Mime Namespace


MailMessage.Serialize Method

MailMessageSerialize Method
Saves the message into the specified .XML file or XML stream.
Overload List
Name | Description
Serialize(String) | Saves the message into the specified .XML file.
Serialize(XmlWriter) | Saves the message into XML stream using the specified XmlWriter object.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Serialize Method (String)

MailMessageSerialize Method (String)
Saves the message into the specified .XML file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Serialize(
    string filename
)
Public Function Serialize (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The path to the .XML file to be saved.

Return Value

Type: Boolean
true if the message was successfully saved to .XML file; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks
The saved message can be loaded back with Deserialize(String) method.
Examples
The example is available in Deserialize(XmlReader) method documentation.
See Also

Reference

MailMessage Class
Serialize Overload
MailBee.Mime Namespace
MailMessageDeserialize(XmlReader)


MailMessage.Serialize Method (XmlWriter)

MailMessageSerialize Method (XmlWriter)
Saves the message into XML stream using the specified XmlWriter object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Serialize(
    XmlWriter xmlWriter
)
Public Function Serialize (
    xmlWriter As XmlWriter
) As Boolean

Parameters

xmlWriter
Type: System.XmlXmlWriter
An XmlWriter object.

Return Value

Type: Boolean
true if the message was successfully saved to .XML file; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | xmlWriter is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks
The saved message can be loaded back from .XML file using the Deserialize(XmlReader) method.
Examples
This sample loads the message from .EML file and saves this message to .XML file.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using System.Xml;
using System.Text;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
XmlTextWriter xtw = null;
try
{
    xtw = new XmlTextWriter(@"C:\Temp\msg.xml", Encoding.UTF8);
    msg.Serialize(xtw);
}
finally
{
    if (xtw != null) xtw.Close();
}
' To use the code below, import these namespaces at the top of your code.
Imports System.Xml
Imports System.Text
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Dim xtw As XmlTextWriter = Nothing
Try
    xtw = New XmlTextWriter("C:\Temp\msg.xml", Encoding.UTF8)
    msg.Serialize(xtw)
Finally
    If Not xtw Is Nothing Then
        xtw.Close()
    End If
End Try
See Also

Reference

MailMessage Class
Serialize Overload
MailBee.Mime Namespace


MailMessage.SerializeAsync Method

MailMessageSerializeAsync Method
Overload List
 | Name | Description
Public method | SerializeAsync(String) | async/await version of Serialize(String).
Public method | SerializeAsync(XmlWriter) | async/await version of Serialize(XmlWriter).
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.SerializeAsync Method (String)

MailMessageSerializeAsync Method (String)
async/await version of Serialize(String).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SerializeAsync(
    string filename
)
Public Function SerializeAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The path to the .XML file to be saved.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully saved to .XML file; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
See Also

Reference

MailMessage Class
SerializeAsync Overload
MailBee.Mime Namespace


MailMessage.SerializeAsync Method (XmlWriter)

MailMessageSerializeAsync Method (XmlWriter)
async/await version of Serialize(XmlWriter).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SerializeAsync(
    XmlWriter xmlWriter
)
Public Function SerializeAsync (
    xmlWriter As XmlWriter
) As Task(Of Boolean)

Parameters

xmlWriter
Type: System.XmlXmlWriter
An XmlWriter object.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message was successfully saved to .XML file; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | xmlWriter is a null reference (Nothing in Visual Basic).
MailBeeIOException | An I/O error occurred and ThrowExceptions is true.
Remarks
Be sure to enable Async when creating XmlReader instance.
See Also

Reference

MailMessage Class
SerializeAsync Overload
MailBee.Mime Namespace


MailMessage.SetDateFromString Method

MailMessageSetDateFromString Method
Sets the date of the message creation as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetDateFromString(
    string date
)
Public Sub SetDateFromString (
    date As String
)

Parameters

date
Type: SystemString
A string in RFC822 data format containing the date and time of the moment when the message was composed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | date is a null reference (Nothing in Visual Basic).
Remarks

This method sets the value of Date header of the message. The value should be in RFC822 format (like Tue, 09 Oct 2007 12:36:00 -0300), but this method allows setting any value except a null reference. If you specify it as an empty string, Date header will not be added to the message at all.

This method by default won't allow out-of-range values in date parts (for instance, 79 seconds while 59 is the maximum allowed value). You can, however, enable FixBadDates to let MailBee tolerate some not significant errors (although this is not recommended).

To set this date as DateTime value, use Date property.

Note Note
MailBee sets the date automatically to the current datetime when the message gets sent or submitted to the pickup folder. To suppress this, set msg.Builder.SetDateOnSend = false (assuming msg is MailMessage instance) prior to sending the message.
Examples
This sample creates a new message and sets the the date when it was composed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
Console.WriteLine(msg.Date.ToString());
msg.SetDateFromString("Thu, 31 Mar 2005 17:34:25 -0400");
Console.WriteLine(msg.Date.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
Console.WriteLine(msg.Date.ToString())
msg.SetDateFromString("Thu, 31 Mar 2005 17:34:25 -0400")
Console.WriteLine(msg.Date.ToString())
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageDate


MailMessage.SetUniqueMessageID Method

MailMessageSetUniqueMessageID Method
Sets a new unique value of Message-ID header and returns it.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SetUniqueMessageID(
    string domain
)
Public Function SetUniqueMessageID (
    domain As String
) As String

Parameters

domain
Type: SystemString
The domain name to be put in the MessageID field. If a null reference or an empty string, the local computer name is used.

Return Value

Type: String
A string containing the new unique value Message-ID value (with angle brackets).
Remarks

Message-ID value is composed of the current thread ID + "." + the random string + "@" + the domain name. This value is then enclosed in angle brackets (<>) and assigned to MessageID property.

You can set Message-ID value manually using MessageID property.

Note Note
MailBee automatically sets unique Message-ID value when the mail message is being sent (or submitted to the pickup folder) unless MailMessage.Builder.SetMessageIDOnSend property is set to false.
Examples
This sample creates a new message and sets its Message-ID.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)
MailMessage msg = new MailMessage();
Console.WriteLine(msg.MessageID);
msg.SetUniqueMessageID("afterlogic.com");
Console.WriteLine(msg.MessageID);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim msg As New MailMessage
Console.WriteLine(msg.MessageID)
msg.SetUniqueMessageID("afterlogic.com")
Console.WriteLine(msg.MessageID)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage Properties

MailMessage Properties

The MailMessage type exposes the following members.

Properties
 | Name | Description
 | Attachments | Gets the AttachmentCollection object containing the attachments of the mail message.
 | Bcc | Gets or sets the list of blind carbon copy (BCC) recipients of the message.
 | BodyHtmlText | Gets or sets the HTML body of the message.
 | BodyParts | Gets all the text bodies of the message.
 | BodyPlainText | Gets or sets the plain-text body of the message.
 | Builder | Gets or sets the options which affect how the mail message is built by MailBee.
 | Cc | Gets or sets the list of carbon copy (CC) recipients of the message.
 | Charset | Gets or sets the name of the charset which was used to compose the message.
 | ConfirmRead | Gets or sets the e-mail address of an entity which should receive the read confirmation message.
 | ConfirmReceipt | Gets or sets the e-mail address of an entity which should receive the delivery confirmation message (when the message gets into mailbox of the server).
 | ContentType | Gets the content type of the message.
 | Date | Gets or sets the date and the time when the mail message was composed.
 | DateReceived | Gets the date and the time when the message was received by the server.
Public property | DateSent | Gets or sets the date and the time when the mail message was sent.
Public property | Filename | Gets the filename of the file this message was loaded from.
 | From | Gets or sets the e-mail address of the message sender.
 | HasAttachments | Indicates if the message has any attachments.
 | Headers | Gets the collection of the message headers.
 | Importance | Gets or sets the importance of the message.
Public property | IndexOnServer | Gets the index of the mail message stored on the mail server.
 | IsEncrypted | Indicates if the message is encrypted.
 | IsEntire | Indicates if the message was received completely.
 | IsSigned | Indicates if the message has a digital signature.
 | LastResult | Gets the code of the last occurred error.
 | MailTransferEncodingHtml | Gets or sets the transfer encoding of the HTML body of the message.
 | MailTransferEncodingPlain | Gets or sets the transfer encoding of the plain-text body of the message.
Public property | MdnReportType | Gets or sets report-type value for Message Disposition Notification (MDN) messages.
 | Merge | Gets the MailMerge object which can be used to perform mail merge using the current e-mail message as a template.
 | MessageID | Gets or sets the Message-ID header of the message.
 | MimePartTree | Gets the root MIME part of the message.
 | Organization | Gets or sets the name of organization to which the sender of the message belongs.
 | Parser | Gets or sets the options which affect how the MailMessage object is parsed.
 | PartCount | Gets the number of parts of the composite message which is split into the several smaller mail messages.
 | PartIndex | Gets the index of the current part in the sequence of parts of a composite message.
 | Priority | Gets or sets the priority of the message.
 | RawHeader | Gets the message header section exactly as it is contained in the message.
 | References | Gets or sets the references of the message.
 | ReplyTo | Gets or sets the list of the e-mail addresses where to send a reply to this message.
 | ReturnPath | Gets the value of Return-Path header.
Public property | Sender | Gets or sets the value of Sender header.
 | Sensitivity | Gets or sets the sensitivity of the message.
 | Size | Gets the size of the message in bytes.
 | SizeOnServer | Gets the actual message size on the mail server.
 | Subject | Gets or sets the subject of the message.
 | ThrowExceptions | Gets or sets whether the MailMessage object will throw exceptions on errors.
 | TimeStamps | Gets the collection of which represents the trace route of the message.
 | To | Gets or sets the e-mail addresses of the primary recipients of the mail message.
 | UidOnServer | Gets Unique-ID (UID) of the message in the mailbox on the server.
 | Version | Gets the current version of MailBee.NET Objects.
 | XMailer | Gets or sets the details about the software which was used to create the message.
Top
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Attachments Property

MailMessageAttachments Property
Gets the AttachmentCollection object containing the attachments of the mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AttachmentCollection Attachments { get; }
Public ReadOnly Property Attachments As AttachmentCollection
    Get

Property Value

Type: AttachmentCollection
An AttachmentCollection object containing all the attachments of the mail message. The default value is an empty collection.
Remarks

Although Attachments property itself is read-only, the collection it returns can be modified through its Add(Attachment), Clear, Remove(String), RemoveAt(Int32) and other methods.

The developer can iterate through this collection using foreach operator (For Each in Visual Basic), access individual attachments using ItemInt32 property, or use SaveAll(String) method to save all attachments into a folder with a single method call.
Examples
The example is available in AttachmentCollection topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Bcc Property

MailMessageBcc Property
Gets or sets the list of blind carbon copy (BCC) recipients of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Bcc { get; set; }
Public Property Bcc As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
An EmailAddressCollection object containing a collection of e-mail addresses of blind carbon copy recipients of the message. The default value is an empty collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

To specify it as a string, set msg.Bcc.AsString value (assuming msg is MailMessage instance). Thus you can construct a list of BCC recipients as a string delimited with comma or semicolon.

Although the message is sent to all recipients which are set in Bcc property, BCC field will not be included in the message header unless MailMessage.Builder.RemoveBccOnSend property is set to false.
Examples
This sample loads the message from .EML file and displays the e-mail addresses of BCC recipients.
C#
VB
Copy
using System;
using MailBee.Mime;
using MailBee.Pop3Mail;

class Sample
{
    static void Main(string[] args)
    {
        // Quickly download the first message from the specified POP3 account
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "dan_brown", "password", 1);

        Console.WriteLine("The list of BCC recipients of the message:");

        // For each BCC recipient...
        foreach (EmailAddress adr in msg.Bcc)
        {
            // ...show its e-mail address.
            Console.WriteLine(adr.Email);
        }
    }
}
Imports System
Imports MailBee.Mime
Imports MailBee.Pop3Mail

Module Sample
    Sub Main(ByVal args As String())
        ' Quickly download the first message from the specified POP3 account
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "dan_brown", "password", 1)

        Console.WriteLine("The list of BCC recipients of the message:")

        ' For each BCC recipient...
        For Each adr As EmailAddress In msg.Bcc
            ' ...show its e-mail address.
            Console.WriteLine(adr.Email)
        Next
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
Pop3QuickDownloadMessage(String, String, String, Int32, Int32)
MailMessageCc


MailMessage.BodyHtmlText Property

MailMessageBodyHtmlText Property
Gets or sets the HTML body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string BodyHtmlText { get; set; }
Public Property BodyHtmlText As String
    Get
    Set

Property Value

Type: String
A string containing the HTML body of the message, or an empty string if the message does not have an HTML body.
Remarks
If the mail message doesn't contain HTML-formatted body and it's desired to get it from plain text, you should set MailMessage.Parser.PlainToHtmlMode to IfNoHtml value. MailBee will generate HTML body automatically and you can then get it from BodyHtmlText property as usually.
Note Note
MailMessage.Parser.PlainToHtmlMode should be set before any property of MailMessage object gets accessed and the message gets parsed. If message was already parsed, you will have to call MailMessage.Parser.Apply method to reparse it.
Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageBodyPlainText


MailMessage.BodyParts Property

MailMessageBodyParts Property
Gets all the text bodies of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPartCollection BodyParts { get; }
Public ReadOnly Property BodyParts As TextBodyPartCollection
    Get

Property Value

Type: TextBodyPartCollection
A reference to the collection containing all the text parts of the message. The default value is an empty collection.
Remarks

All the MIME parts of the message (except of multipart parts which are just containers of another parts) either fall into Attachments or BodyParts collections.

If ContentType of certain MIME part contains text string (for instance, it is text/plain or text/html) and this part is not attachment, this part of the message is considered to be a text part.

If you need to get the list or the hierarchy of all MIME parts of the message, use MimePartTree property.

Examples
The example is available in TextBodyPartCollection topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageMimePartTree
MailMessageAttachments


MailMessage.BodyPlainText Property

MailMessageBodyPlainText Property
Gets or sets the plain-text body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string BodyPlainText { get; set; }
Public Property BodyPlainText As String
    Get
    Set

Property Value

Type: String
A string containing the plain-text message body, or an empty string if the message does not have a plain text body.
Remarks
In the case when mail message does not have plain-text body, you can generate it from the HTML body using MakePlainBodyFromHtmlBody method.

Alternatively, to make plain-text version of HTML body of an existing message, you should set MailMessage.Parser.HtmlToPlainMode property to IfNoPlain value. This property must be set BEFORE any property of the MailMessage gets accessed.

Or, for a new message (the one you're composing), to make the outgoing message contain the plain-text body, set MailMessage.Builder.HtmlToPlainMode to IfNoPlain value. This property must be set BEFORE the message gets sent or saved to disk.

If you deal with plain-text messages with no quoted-printable or base64 encoding and experience issues with wrapping long text lines, consider setting UnwrappedLineLengthLimit property to a bigger value.

Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageBodyHtmlText


MailMessage.Builder Property

MailMessageBuilder Property
Gets or sets the options which affect how the mail message is built by MailBee.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageBuilderConfig Builder { get; set; }
Public Property Builder As MessageBuilderConfig
    Get
    Set

Property Value

Type: MessageBuilderConfig
A MessageBuilderConfig object containing the options which affect how the mail message is built by MailBee.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
This property returns a reference to the instance of configuration class which allows the developer to tune how the mail message is being produced from the current values of the MailMessage object into MIME format. Using this property, you can, for example, tell MailBee to automatically generate plain-text version of the message body if you supplied only the HTML version.
Examples
The example is available in MessageBuilderConfig topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageParser


MailMessage.Cc Property

MailMessageCc Property
Gets or sets the list of carbon copy (CC) recipients of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Cc { get; set; }
Public Property Cc As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
An EmailAddressCollection object containing a collection of e-mail addresses of carbon copy recipients of the message. The default value is an empty collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
To specify Cc as a string, set msg.Cc.AsString value (assuming msg is MailMessage instance).

If it's necessary to add some hidden recipients that should not be displayed in the mail message, the developer should use the Bcc property.

Examples
This sample loads the message from .EML file and displays the e-mail addresses of CC recipients.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        Console.WriteLine("The list of CC recipients of the message:");

        // For each carbon copy recipient...
        foreach (EmailAddress adr in msg.Cc)
        {
            // ...show e-mail address.
            Console.WriteLine(adr.Email);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        Console.WriteLine("The list of CC recipients of the message:")

        ' For each carbon copy recipient...
        For Each adr As EmailAddress In msg.Cc
            ' ...show e-mail address.
            Console.WriteLine(adr.Email)
        Next
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.MimeEmailAddressCollection
MailMessageBcc


MailMessage.Charset Property

MailMessageCharset Property
Gets or sets the name of the charset which was used to compose the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Charset { get; set; }
Public Property Charset As String
    Get
    Set

Property Value

Type: String
A string containing the name of the charset which was used to compose the message, or an empty string if the charset is not specified. The default value for new messages is utf-8.
Remarks

Every part of an e-mail message may have its own charset (although it's not recommended). E-mails composed with MailBee have the same charset value across the message (unless you manually specified different charsets of text parts using TextBodyPart.Charset property). If text parts of the message (originally composed with another program and being parsed with MailBee now) have different charsets, Charset property will return charset of the last text part of this message.

For existing e-mail messages being parsed (rather than for new messages being composed) Charset property value is not important for the developer because MailBee automatically converts the message content accordingly the charset information in the message and the application receives the already decoded content. In this case, Charset property value has the informative feature only.

However, when composing a new message (with international characters), you should specify the charset using Charset property in case if you don't want UTF-8 encoding. Or, in rare cases, you will use TextBodyPart.Charset property if you need different charset settings for different text parts.

If Charset is not specified, MailBee will use the following properties to determine encoding for string-to-byte and byte-to-string conversions:

  • MailMessage.Parser.EncodingDefault property when parsing e-mail messages (received from the mail server, loaded from disk or memory, etc)
  • TextBodyPart.Charset property when composing an e-mail message and building its source in MIME format

Setting Charset property will overwrite TextBodyPart.Charset values for all text parts of the message. But if you specified TextBodyPart.Charset value for a certain text part AFTER Charset had been set, that text part will retain the specified TextBodyPart.Charset in the resulting message (while Charset will be used for other text parts of the message).

Note Note
If any characters of the message contents are not defined in the specified charset, they will be replaced with "?" characters.
Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
TextBodyPartCharset


MailMessage.ConfirmRead Property

MailMessageConfirmRead Property
Gets or sets the e-mail address of an entity which should receive the read confirmation message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ConfirmRead { get; set; }
Public Property ConfirmRead As String
    Get
    Set

Property Value

Type: String
A string containing the e-mail address of the entity which should receive the read confirmation message, or an empty string if no read confirmation is set.
Remarks

The value of this property is taken from Disposition-Notification-To header. Usually it will contain the same e-mail address as From or ReplyTo field.

Note Note
This property will not have effect if the e-mail client software of the recipient does not support this feature.

To get or set the delivery confirmation, the developer should use ConfirmReceipt property.

Examples
This sample downloads the first message from the specified POP3 account and displays the e-mail address of read confirmation recipient if any.
C#
VB
Copy
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;
using System;

class Sample
{
    static void Main(string[] args)
    {

        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1);

        // Show the e-mail address of recipient of the read confirmation message.
        if (msg.ConfirmRead != String.Empty)
        {
            Console.WriteLine("Send read confirmation to " + msg.ConfirmRead);
        }
        else
        {
            Console.WriteLine("There is no read confirmation recipient available");
        }
    }
}
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pop3Mail
Imports System

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1)

        ' Show the e-mail address of recipient of the read confirmation message.
        If msg.ConfirmRead <> String.Empty Then
            Console.WriteLine("Send read confirmation to " & msg.ConfirmRead)
        Else
            Console.WriteLine("There is no read confirmation recipient available")
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageConfirmReceipt


MailMessage.ConfirmReceipt Property

MailMessageConfirmReceipt Property
Gets or sets the e-mail address of an entity which should receive the delivery confirmation message (when the message gets into mailbox of the server).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ConfirmReceipt { get; set; }
Public Property ConfirmReceipt As String
    Get
    Set

Property Value

Type: String
A string containing the e-mail address of a person which should receive the delivery confirmation message, or an empty string if no delivery confirmation is set.
Remarks

The value of this property is taken from Return-Receipt-To header. Usually (if set) it will contain the same e-mail address as From or ReplyTo field.

Note Note
This property will not have effect if the e-mail server software of the recipient does not support this feature.

Another method of requesting delivery receipt is using mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always (assuming mailer is an instance of Smtp class).

To get or set the read confirmation, the developer should use ConfirmRead property.
Examples
This sample creates new mail message, sets the e-mail address of delivery confirmation message recipient, and saves this message to disk.
C#
VB
Copy
using MailBee;
using MailBee.Mime;
using System;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();

        // Set the e-mail address of confirmation message recipient.
        msg.ConfirmReceipt = "jdoe@domain.com";

        // Save message to the specified .eml file.
        msg.SaveMessage(@"C:\Temp\MyMail.eml");
    }
}
Imports MailBee
Imports MailBee.Mime
Imports System

Module Sample
    Sub Main(ByVal args As String())
        Dim msg As New MailMessage

        ' Set the e-mail address of confirmation message recipient.
        msg.ConfirmReceipt = "jdoe@domain.com"

        ' Save message to the specified .eml file.
        msg.SaveMessage("C:\Temp\MyMail.eml")
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageConfirmRead
DeliveryNotificationOptionsNotifyCondition


MailMessage.ContentType Property

MailMessageContentType Property
Gets the content type of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentType { get; }
Public ReadOnly Property ContentType As String
    Get

Property Value

Type: String
A string containing the content type of the mail message. The default value for a new message is text/plain.
Remarks

The value of this property is taken from the Content-Type header. The typical content types are:

  • text/plain
  • text/html
  • text/calendar
  • multipart/alternative
  • multipart/mixed
  • application/x-zip-compressed
If the content-type is missing in the message being parsed, this property will return an empty string.

You do not need to manually set the content-type of the message. It will be set automatically depending on the structure of the message (e.g. its text bodies and attachments).

Examples
This sample downloads the first message from the specified POP3 account and displays the content type of the message.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Quickly download the first message from the specified POP3 account
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "dan_brown", "password", 1);

        // Show the content type of the message.
        Console.WriteLine("Content type is " + msg.ContentType);
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Quickly download the first message from the specified POP3 account
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "dan_brown", "password", 1)

        ' Show the content type of the message.
        Console.WriteLine("Content type is " & msg.ContentType)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Date Property

MailMessageDate Property
Gets or sets the date and the time when the mail message was composed.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime Date { get; set; }
Public Property Date As DateTime
    Get
    Set

Property Value

Type: DateTime
The date when the mail message was composed. The default value is MinValue.
Exceptions
Exception | Condition
MailBeeDateParsingException | A date parsing error occurred and ThrowExceptions is true.
Remarks

In the case when an existing message gets parsed, the value of this property is taken from Date header.

Otherwise, if a new message is being sent or submitted to the pickup folder and SetDateOnSend property is true, Date value will be set to Now directly at the moment of sending.

On other hand, if SetDateOnSend property is set to false, the existing value of Date header will be used. If it's MinValue, Date header will not be added to the message.

When the message gets built without sending (for instance, when you save it into a file), Date value is not changed. Thus, if you did not set it manually, no Date header will present in the resulting message.

To set the date to the current date and time, you can use msg.Date=DateTime.Now (assuming msg is MailMessage instance).

You can also use SetDateFromString(String) method to set Date header value from a string.

To get the date when the message was delivered to the mailbox (rather than composed), use DateReceived property.

Note Note
By default, all dates are adjusted to local timezone. To adjust to GMT (UTC) time, set DatesAsUtc property of Parser object to true.

Reading this property by default won't allow out-of-range values in Date header (for instance, 79 seconds while 59 is the maximum for a valid value). You can, however, enable FixBadDates to let MailBee tolerate some not significant errors (can be useful if you sometimes get e-mails created by poorly-written mail programs or spam software).

Examples

This sample loads the message from .EML file and changes the date and time when the message was composed. In the modified message, it will appear that the message was composed earlier today at midnight, not at the current moment.

Then, the sample suppresses automatic setting the date and time to Now during sending, and sends the message.

C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Set the date to the current date and 00-00 time.
        msg.Date = DateTime.Today;

        // Suppress automatic setting Date to the current datetime
        // when the message gets sent.
        msg.Builder.SetDateOnSend = false;

        // Send it.
        Smtp.QuickSend(msg);
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Set the date to the current date and 00-00 time.
        msg.Date = DateTime.Today

        ' Suppress automatic setting Date to the current datetime
        ' when the message gets sent.
        msg.Builder.SetDateOnSend = False

        ' Send it.
        Smtp.QuickSend(msg)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageDateReceived
MailMessageSetDateFromString(String)
MessageBuilderConfigSetDateOnSend


MailMessage.DateReceived Property

MailMessageDateReceived Property
Gets the date and the time when the message was received by the server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime DateReceived { get; }
Public ReadOnly Property DateReceived As DateTime
    Get

Property Value

Type: DateTime
A DateTime value containing the date and time when the message was delivered into the mailbox (obtained from Received header) or MinValue if no Received header is available in the message. The default value is MinValue.
Remarks

For an existing message, this property value is taken from Received headers of this message. When a new message is created using MailBee or if the existing message does not contain any Received headers, this property will return MinValue. If the e-mail message contains several Received headers, then the most recent one will be used to obtain DateReceived value.

When downloading messages from IMAP server, it's more reliable to use Envelope.DateReceived instead. Date information is always available in an IMAP envelope while Received header may be missing in a message.

To get or set the date when the message was composed, use Date property.

Note Note
By default, all dates are adjusted to UTC (GMT) timezone. To adjust to local time, set DatesAsUtc property of Parser object to true.
Examples
This sample downloads the first message from the specified POP3 account and displays the date and time when this message was received by the POP3 server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("mail.company.com", "bill", "secret", 1);

        Console.WriteLine("This message was received at " + msg.DateReceived.ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("mail.company.com", "bill", "secret", 1)

        Console.WriteLine("This message was received at " & msg.DateReceived.ToString())
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageDate


MailMessage.DateSent Property

MailMessageDateSent Property
Gets or sets the date and the time when the mail message was sent.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime DateSent { get; set; }
Public Property DateSent As DateTime
    Get
    Set

Property Value

Type: DateTime
The date when the mail message was sent. The default value is MinValue.
Exceptions
Exception | Condition
MailBeeDateParsingException | A date parsing error occurred and ThrowExceptions is true.
Remarks
This value is taken from "X-Date-Sent" header. It's not a standard header and most e-mails won't have it set. However, MailBee sets this header when you convert an e-mail from Outlook .MSG format into .EML format (using MsgConvert class). The same way, if you set this header, "Date Sent" value will appear in the resulting .MSG if you're doing .EML-to-.MSG conversion.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageDateReceived
MailMessageDate


MailMessage.Filename Property

MailMessageFilename Property
Gets the filename of the file this message was loaded from.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; }
Public ReadOnly Property Filename As String
    Get

Property Value

Type: String
The filename value of LoadMessage(String) method call used to load this message from the file, or a null reference (Nothing in Visual Basic) if this message was not loaded from a file.
Remarks

This property is especially useful if this MailMessage object was created by MailBee itself, not by your code, and you need to somehow link the filename you supplied to MailBee and the actual MailMessage object which was created by loading the message from that file.

Imagine you used AddJob(String, String, Boolean, String, EmailAddressCollection) method to create multiple send mail jobs from filenames of your stored .EML files. You then subscribed to some events of Smtp object, started processing enqueued send mail jobs, got an event triggered for certain MailMessage object (like MessageSent event) and want to know from which file the particular MailMessage was loaded. Filename property gives you the name of that file.

See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.From Property

MailMessageFrom Property
Gets or sets the e-mail address of the message sender.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress From { get; set; }
Public Property From As EmailAddress
    Get
    Set

Property Value

Type: EmailAddress
An EmailAddress object containing the e-mail address of the message sender.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
The value of this property is taken from From header.

To specify it as a string, set msg.From.AsString value (assuming msg is MailMessage instance).

If you need to deal with international e-mail addresses (IDN domains), use FromIdnAddress and ToIdnAddress methods to convert e-mail addresses between human-readable and SMTP-safe formats.

Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.HasAttachments Property

MailMessageHasAttachments Property
Indicates if the message has any attachments.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool HasAttachments { get; }
Public ReadOnly Property HasAttachments As Boolean
    Get

Property Value

Type: Boolean
true if the message has at least one attachment; otherwise, false.
Remarks
If only the headers of the message were received from the mail server, this property may not be 100% accurate. The developer should download the entire message to be sure if it really has any attachments or not.
Examples
This sample downloads the message from the specified POP3 account and displays the number of the message attachments.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1);

        // Check if the mail message has any attachments and display the corresponding message.
        if (msg.HasAttachments)
        {
            Console.WriteLine("This message has " + msg.Attachments.Count.ToString() + " attachments");
        }
        else
        {
            Console.WriteLine("This message does not have any attachments");
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1)

        ' Check if the mail message has any attachments and display the corresponding message.
        If msg.HasAttachments Then
            Console.WriteLine("This message has " & msg.Attachments.Count.ToString() & " attachments")
        Else
            Console.WriteLine("This message does not have any attachments")
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Headers Property

MailMessageHeaders Property
Gets the collection of the message headers.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection Headers { get; }
Public ReadOnly Property Headers As HeaderCollection
    Get

Property Value

Type: HeaderCollection
A HeaderCollection object containing the headers of the message.
Remarks

This property allows the developer to access any headers of the message, add new headers, or modify/delete existing ones.

Use RawHeader property to get the header section of the message as a string.

Examples
The example is available in Header topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageRawHeader


MailMessage.Importance Property

MailMessageImportance Property
Gets or sets the importance of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailPriority Importance { get; set; }
Public Property Importance As MailPriority
    Get
    Set

Property Value

Type: MailPriority
The importance of the message, or None if not specified. The default value is None.
Remarks

The importance of the message is taken from Importance header.

To get or set the message priority (rather than the message importance), use Priority property. It's common practice to set both Priority and Importance properties. Some e-mail clients do not support Importance or Priority but still support one of these fields. Thus, if you specify both, all e-mail clients will be able to understand at least one of the fields.

Examples
This sample sends a message only if it's very important.
C#
VB
Copy
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Send the message if it's very important.
        if (msg.Importance == MailPriority.Highest)
        {
            Smtp.QuickSend(msg);
        }
    }
}
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Send the message if it's very important.
        If msg.Importance = MailPriority.Highest Then
            Smtp.QuickSend(msg)
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessagePriority


MailMessage.IndexOnServer Property

MailMessageIndexOnServer Property
Gets the index of the mail message stored on the mail server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int IndexOnServer { get; }
Public ReadOnly Property IndexOnServer As Integer
    Get

Property Value

Type: Int32
Gets the ordinal position of the mail message in the mailbox on the mail server (starting from 1), or 0 if this message was created from another source rather than received from the mail server.
Remarks
Use UidOnServer property if you need to determine Unique-ID of the message rather than its ordinal position in the mailbox.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.IsEncrypted Property

MailMessageIsEncrypted Property
Indicates if the message is encrypted.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsEncrypted { get; }
Public ReadOnly Property IsEncrypted As Boolean
    Get

Property Value

Type: Boolean
true if the message is encrypted; otherwise, false.
Remarks

Messages can also be signed with a digital signature. To check if a message is signed or not, use IsSigned property. Note that you may also need to check IsSigned property of the decrypted message because the original message will have only IsEncrypted set but not IsSigned in case if the signature is within the encrypted data (thus, it's required to decrypt the message first in order to tell if it has a digital signature).

To operate with IsEncrypted or IsSigned messages, use Smime object.

Examples
This sample downloads a message from the POP3 server and reports whether this message is encrypted.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1);

        // Display the subject of the message if it's not encrypted.
        if (msg.IsEncrypted)
        {
            Console.WriteLine("The subject can not be displayed because the message is encrypted.");
        }
        else
        {
            Console.WriteLine("The message has the following subject:\r\n" + msg.Subject);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1)

        ' Display the subject of the message if it's not encrypted.
        If msg.IsEncrypted Then
            Console.WriteLine("The subject can not be displayed because the message is encrypted.")
        Else
            Console.WriteLine("The message has the following subject:" & vbCrLf & msg.Subject)
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageIsSigned


MailMessage.IsEntire Property

MailMessageIsEntire Property
Indicates if the message was received completely.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsEntire { get; }
Public ReadOnly Property IsEntire As Boolean
    Get

Property Value

Type: Boolean
true if the message is complete; otherwise, false.
Remarks

If the e-mail message is not entire, the developer can use PartCount property to examine whether the e-mail message is composite (i.e. actually consists of several messages which must be joined to get the complete message). To get the index of the part the message represents, use PartIndex property.

However, the message may be incomplete even if it's a normal message. For instance, if you downloaded only a message header from the mail server, the message will be incomplete too (you'll need to download the entire message to get it completely).

Examples
This sample gets the headers of the message and the first 10 lines of its body message from the POP3 server and determines whatever the message is entire, partial or incomplete. It will be partial if it's a composite message split into smaller ones, or it will be entire if the entire message body fits into 10 lines, or it will be incomplete if its body does not fit into 10 lines which have been downloaded.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Pop3Mail;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("mail.domain.com", "jdoe", "password", 1, 10);

        // Check whatever the message is entire, partial,
        // or it was received incompletely.
        if (msg.IsEntire)
        {
            Console.WriteLine("The message was completely received");
        }
        else if (msg.PartCount > 1)
        {
            Console.WriteLine(@"The message is partial (part index is " +
                msg.PartIndex + ")");
        }
        else
        {
            Console.WriteLine(@"The message was not completely received
                (the body is larger than 10 lines downloaded)");
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pop3Mail

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("mail.domain.com", "jdoe", "password", 1, 10)

        ' Check whatever the message is entire, partial,
        ' or it was received incompletely.
        If msg.IsEntire Then
            Console.WriteLine("The message was completely received")
        ElseIf msg.PartCount > 1 Then
            Console.WriteLine("The message is partial (part index is " & _
                msg.PartIndex.ToString & ")")
        Else
            Console.WriteLine("The message was not completely received " & _
                "(the body is larger than 10 lines downloaded)")
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessagePartIndex
MailMessagePartCount
MailMessageAppendPartialMessage(MailMessage)


MailMessage.IsSigned Property

MailMessageIsSigned Property
Indicates if the message has a digital signature.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSigned { get; }
Public ReadOnly Property IsSigned As Boolean
    Get

Property Value

Type: Boolean
true if the message is signed with a digital signature; otherwise, false.
Remarks
If the message is also encrypted (IsEncrypted is true), you can't usually tell if it's signed before you decrypt it. Thus, even if IsSigned is false, you should decrypt the message first and then check IsSigned of the decrypted message (available through DecryptedMessage property of the SmimeResult object returned by Decrypt(MailMessage) or by DecryptAndVerify(MailMessage, MessageVerificationFlags) method).
Examples
This sample loads the message from .EML file and reports whether the message is signed.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {

        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail1.eml");

        if (msg.IsSigned)
        {
            Console.WriteLine("The message is signed.");
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())

        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail1.eml")

        If msg.IsSigned Then
            Console.WriteLine("The message is signed.")
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageIsEncrypted


MailMessage.LastResult Property

MailMessageLastResult Property
Gets the code of the last occurred error.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error, or the OK value if no errors occurred. The default value is OK.
Remarks
This property always contains the code of last occurred error (even if ThrowExceptions property is set to true).
Examples
The example is available in ThrowExceptions topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBeeErrorCodes
MailMessageThrowExceptions


MailMessage.MailTransferEncodingHtml Property

MailMessageMailTransferEncodingHtml Property
Gets or sets the transfer encoding of the HTML body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailTransferEncoding MailTransferEncodingHtml { get; set; }
Public Property MailTransferEncodingHtml As MailTransferEncoding
    Get
    Set

Property Value

Type: MailTransferEncoding
The mail encoding (like Base64, 7-bit, etc) of the HTML body of the message. The default value for new messages is QuotedPrintable.
Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageEncodeAllHeaders(Encoding, HeaderEncodingOptions)


MailMessage.MailTransferEncodingPlain Property

MailMessageMailTransferEncodingPlain Property
Gets or sets the transfer encoding of the plain-text body of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailTransferEncoding MailTransferEncodingPlain { get; set; }
Public Property MailTransferEncodingPlain As MailTransferEncoding
    Get
    Set

Property Value

Type: MailTransferEncoding
The mail encoding (like Base64, 7-bit, etc) of the plain-text body of the message. The default value for new messages is QuotedPrintable.
Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageEncodeAllHeaders(Encoding, HeaderEncodingOptions)


MailMessage.MdnReportType Property

MailMessageMdnReportType Property
Gets or sets report-type value for Message Disposition Notification (MDN) messages.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MdnReportType { get; set; }
Public Property MdnReportType As String
    Get
    Set

Property Value

Type: String
The value of report-type parameter of Content-Type header if this message is MDN. If this value is a null reference (Nothing in Visual Basic) or an empty string, the message is not MDN. The default value is a null reference.
Remarks

For MDNs, typical values can be "delivery-status" or "disposition-notification". When this value is set and the message has attachments, MailBee will generate "multipart/report" Content-Type instead of "multipart/mixed".

To parse MDNs (such as bounced messages), you can use DeliveryStatusParser class.

See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Merge Property

MailMessageMerge Property
Gets the MailMerge object which can be used to perform mail merge using the current e-mail message as a template.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMerge Merge { get; }
Public ReadOnly Property Merge As MailMerge
    Get

Property Value

Type: MailMerge
A MailMerge object which can be used to perform mail merge of the given MailMessage object (acting as a template) with actual data.
Remarks
If you need to perform mail merge over database, it's easier to use Smtp.SendMailMerge method.
Examples
The example is available in MailMerge topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


MailMessage.MessageID Property

MailMessageMessageID Property
Gets or sets the Message-ID header of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MessageID { get; set; }
Public Property MessageID As String
    Get
    Set

Property Value

Type: String
A string containing the Message-ID. For newly created messages, it's an empty string; for existing messages (received from mail servers, loaded from disk, etc), it's set from the Message-ID header value during parsing the message.
Remarks
During sending the message or submitting it to the pickup folder, this property is set to a new unique value (unless MailMessage.Builder.SetMessageIDOnSend is false).

You can also set Message-ID manually using SetUniqueMessageID(String) method.

In MIME, Message-ID value is enclosed in angle brackets (<>). This property returns Message-ID value with angle brackets. Also, if you assign a new value without trailing angle brackets, they will be added to MessageID value automatically.

Note Note
Message-ID (MID) is NOT the same as Unique-ID (UID) which is assigned to each message in the mailbox by the POP3 or IMAP4 server.
Examples
This sample loads the message from .EML file and displays the Message-ID of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Show the Message-ID.
Console.WriteLine("The message ID is " + msg.MessageID);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Show the Message-ID.
Console.WriteLine("The message ID is " & msg.MessageID)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MessageBuilderConfigSetMessageIDOnSend


MailMessage.MimePartTree Property

MailMessageMimePartTree Property
Gets the root MIME part of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePart MimePartTree { get; }
Public ReadOnly Property MimePartTree As MimePart
    Get

Property Value

Type: MimePart
A MimePart object containing the root MIME part of the message.
Remarks

A mail message can be represented as a set of MIME parts which have headers, body, or sub-parts (if this MIME part is multi-part). For instance, a message which consists of the plain text only can be represented as a single MIME part (without any sub-parts).

On the other hand, complex messages having attachments or alternative bodies can be represented as a tree structure. In this case, the given property gets the root MIME part which is associated with the message itself.

To get all MIME parts of the message as an array rather than a tree, call msg.MimePartTree.GetAllParts() (assuming msg is MailMessage instance).

Examples
This sample loads the message from .EML file and displays the size of the root MIME part of the message in bytes.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Display the size of root MIME part in bytes.
        Console.WriteLine(msg.MimePartTree.Size.ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Display the size of root MIME part in bytes.
        Console.WriteLine(msg.MimePartTree.Size.ToString())
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MimePartGetAllParts


MailMessage.Organization Property

MailMessageOrganization Property
Gets or sets the name of organization to which the sender of the message belongs.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Organization { get; set; }
Public Property Organization As String
    Get
    Set

Property Value

Type: String
A string containing the value of Organization header of the message. The default value is an empty string.
Examples
This sample loads the message from .EML file and displays the name of the organization which sent this message.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1);

        // Display the name of organization which have sent the message.
        if (msg.Organization != String.Empty)
        {
            Console.WriteLine("The message was sent by " + msg.Organization);
        }
        else
        {
            Console.WriteLine("The message was sent by unknown organization or by person.");
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop3.mail.com", "kathy1981", "password", 1)

        ' Display the name of organization which have sent the message.
        If msg.Organization <> String.Empty Then
            Console.WriteLine("The message was sent by " & msg.Organization)
        Else
            Console.WriteLine("The message was sent by unknown organization or by person.")
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Parser Property

MailMessageParser Property
Gets or sets the options which affect how the MailMessage object is parsed.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageParserConfig Parser { get; set; }
Public Property Parser As MessageParserConfig
    Get
    Set

Property Value

Type: MessageParserConfig
A MessageParserConfig object containing the options which affect how the MailMessage object is parsed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

This property provides access to such features as automatic creation of plain-text or HTML parts of the message, automatic saving of the message to disk, converting URLs to HTML links, etc.

To set options which affect how the mail message is being built (for instance, when it gets sent or saved to disk), use the Builder property.

Examples
The example is available in MessageParserConfig topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageBuilder


MailMessage.PartCount Property

MailMessagePartCount Property
Gets the number of parts of the composite message which is split into the several smaller mail messages.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int PartCount { get; }
Public ReadOnly Property PartCount As Integer
    Get

Property Value

Type: Int32
The number of parts of the composite message which is split into the several smaller mail messages. If the message is not split, the return value is 1.
Remarks

Splitting the messages into the several smaller parts is a common way of transmitting large messages which exceed the maximum message size that is allowed by the mail server. The developer can use the AppendPartialMessage(MailMessage) method to restore the entire original message from its smaller parts.

Besides that, the developer can use the IsEntire property to determine whatever a message was received completely and the PartIndex property to get the index of partial message.

Examples
The example is available in IsEntire property overview.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageIsEntire
MailMessagePartIndex
MailMessageAppendPartialMessage(MailMessage)


MailMessage.PartIndex Property

MailMessagePartIndex Property
Gets the index of the current part in the sequence of parts of a composite message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int PartIndex { get; }
Public ReadOnly Property PartIndex As Integer
    Get

Property Value

Type: Int32
The index of the current sub-message in the sequence of sub-messages of a composite message, which is split into several smaller ones. If the message is not a part of the composite message, the return value is 1.
Remarks
The developer can use the PartCount property to examine whatever mail message is composite or not and the IsEntire property to determine if a message was received completely.
Examples
The example is available in IsEntire property overview.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessagePartCount
MailMessageIsEntire
MailMessageAppendPartialMessage(MailMessage)


MailMessage.Priority Property

MailMessagePriority Property
Gets or sets the priority of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailPriority Priority { get; set; }
Public Property Priority As MailPriority
    Get
    Set

Property Value

Type: MailPriority
The message priority level, or None if not set. The default value is None.
Remarks

Different mail clients may set or interpret the priority settings differently while some of them may ignore it.

The value of this property is taken from the X-Priority and X-MSMail-Priority headers.

Examples
This sample loads the message from .EML file, sets High priority level for it, and sends this message.
C#
VB
Copy
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Set the High priority level for the message.
        msg.Priority = MailPriority.High;

        // Send it.
        Smtp.QuickSend(msg);
    }
}
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Set the High priority level for the message.
        msg.Priority = MailPriority.High

        ' Send it.
        Smtp.QuickSend(msg)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageImportance


MailMessage.RawHeader Property

MailMessageRawHeader Property
Gets the message header section exactly as it is contained in the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RawHeader { get; }
Public ReadOnly Property RawHeader As String
    Get

Property Value

Type: String
A string containing the full header of the message.
Remarks
To get the entire source of the message including its header and body sections, use GetMessageRawData method.
Note Note
In MIME, the header of the message constists of name-value pairs which are also called headers. RawHeader refers to the former (also known as "full header"). Similar reusage of the same term takes place for a body. In MIME, a body section is the remaining part of the message after the header section. It includes attachments and text bodies of a message. The entire source of the message (the header section and the body section) is often called raw body.
Examples
This sample loads the message from .EML file and displays the raw header of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail1.eml");

Console.WriteLine(msg.RawHeader);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail1.eml")

Console.WriteLine(msg.RawHeader)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageGetMessageRawData


MailMessage.References Property

MailMessageReferences Property
Gets or sets the references of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string References { get; set; }
Public Property References As String
    Get
    Set

Property Value

Type: String
A string containing the references of the message. The default value is an empty string.
Remarks

The value of this property is taken from References header.

This header usually contains a space-separated list of Message-ID values of all messages in a thread. However, building message threads using this header is not reliable since many e-mail clients do not support this mechanism.

Examples
This sample loads the message from .EML file and displays the references of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Data\example.eml");
Console.WriteLine(msg.References);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

Dim msg As New MailMessage
msg.LoadMessage("C:\Data\example.eml")
Console.WriteLine(msg.References)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.ReplyTo Property

MailMessageReplyTo Property
Gets or sets the list of the e-mail addresses where to send a reply to this message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ReplyTo { get; set; }
Public Property ReplyTo As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
A reference to the collection of e-mail addresses which are intended recipients of a reply to this message. The default value is an empty collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

To specify it as a string, set msg.ReplyTo.AsString value (assuming msg is MailMessage instance).

This value is obtained from Reply-To header of the message. If you need to reply to a message which does not contain Reply-To header, send the reply to From address.

Examples
This sample gets a message from POP3 server and sends autoresponse to its Reply-To address.
C#
VB
Copy
using MailBee;
using MailBee.SmtpMail;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("mail.company.com", "bill", "password", 1);

        // Send the autoresponse message.
        Smtp.QuickSend("bill@company.com", msg.ReplyTo.ToString(), "Warning notification",
            "Since I'm currently on vacations, I'll reply your message after 01/08/06.");
    }
}
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.SmtpMail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("mail.company.com", "bill", "password", 1)

        ' Send the autoresponse message.
        Smtp.QuickSend("bill@company.com", msg.ReplyTo.ToString, "Warning notification", _
            "Since I'm currently on vacations, I'll reply your message after 01/08/06.")
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageConfirmReceipt


MailMessage.ReturnPath Property

MailMessageReturnPath Property
Gets the value of Return-Path header.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ReturnPath { get; }
Public ReadOnly Property ReturnPath As String
    Get

Property Value

Type: String
A string containing the e-mail address of the actual sender of the message. The default value is an empty string.
Remarks

The mail server which transmitted the message may add this header to specify the email address of the original sender of the mail message. If the message was never sent, this property will contain an empty string. With TimeStamps property (which represents Received headers), ReturnPath provides trace route information about the message.

You cannot set ReturnPath directly (because it's set by the mail server, not by MailBee). However, if you need to send a message from the address different from From address, you can pass it as senderEmail parameter value of Send(String, String) method. In this case, the mail server will set Return-Path header to senderEmail value, not to From value.

Examples
This sample loads the message from .EML file and displays the email address of the originator of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Show the return path of the message.
Console.WriteLine("The return path is " + msg.ReturnPath);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Show the return path of the message.
Console.WriteLine("The return path is " & msg.ReturnPath)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageTimeStamps


MailMessage.Sender Property

MailMessageSender Property
Gets or sets the value of Sender header.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Sender { get; set; }
Public Property Sender As String
    Get
    Set

Property Value

Type: String
A string containing the value of Sender header of the message. The default value is an empty string.
Remarks
This is an optional header. It's sometimes used as an alternative to From in case if the message was sent from the address which differs from From address. If you want to specify the real sender's address, you can set this property for that.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Sensitivity Property

MailMessageSensitivity Property
Gets or sets the sensitivity of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailSensitivity Sensitivity { get; set; }
Public Property Sensitivity As MailSensitivity
    Get
    Set

Property Value

Type: MailSensitivity
The sensitivity of the message, or None if not set. The default value is None.
Remarks
Remarks
The value of this property is taken from Sensitivity header.
Examples
This sample loads the message from .EML file and sets the private level of sensitivity of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

' The actual code (put it into a method of your class)

' Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail1.eml");

msg.Sensitivity = MailSensitivity.Private;
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail1.eml")

msg.Sensitivity = MailSensitivity.Private
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Size Property

MailMessageSize Property
Gets the size of the message in bytes.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Size { get; }
Public ReadOnly Property Size As Integer
    Get

Property Value

Type: Int32
The size of the message in bytes.
Remarks
If only the message headers were received from mail server, this property contains the size of these headers, but not of the entire message. To get the size of the entire message, use SizeOnServer property.
Examples
This sample downloads the message from the mail server (only the header and the first 10 lines of the body are downloaded) and checks if the message was received completely (and thus its body fits into 10 lines).
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first mail message from the specified POP3 account.
        MailMessage msg = Pop3.QuickDownloadMessage("mail.domain.com", "jdoe", "password", 1, 10);

        if (msg.Size == msg.SizeOnServer)
        {
            Console.WriteLine("The message was received completely");
        }
        else
        {
            Console.WriteLine(@"The message was not received completely
                (maybe only the message headers were received)");
        }
    }

}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Download the first mail message from the specified POP3 account.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("mail.domain.com", "jdoe", "password", 1, 10)

        If msg.Size = msg.SizeOnServer Then
            Console.WriteLine("The message was received completely")
        Else
            Console.WriteLine("The message was not received completely" & _
                "(maybe only the message headers were received)")
        End If
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageSizeOnServer


MailMessage.SizeOnServer Property

MailMessageSizeOnServer Property
Gets the actual message size on the mail server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int SizeOnServer { get; }
Public ReadOnly Property SizeOnServer As Integer
    Get

Property Value

Type: Int32
The actual message size in bytes.
Remarks
This property indicates the actual message size and may not be equal to the value of Size property, which indicates the size of the received message. For instance, if only the message headers were received from mail server, Size property will contain the size of the message headers. However, SizeOnServer property will still return the size of the entire message.
Examples
The sample is available in Size property overview.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailMessageSize


MailMessage.Subject Property

MailMessageSubject Property
Gets or sets the subject of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Subject { get; set; }
Public Property Subject As String
    Get
    Set

Property Value

Type: String
A string containing the subject of the message. The default value is an empty string.
Remarks
This value is taken from Subject header of the message.
Examples
The sample is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.ThrowExceptions Property

MailMessageThrowExceptions Property
Gets or sets whether the MailMessage object will throw exceptions on errors.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
true if MailMessage object will throw exceptions on errors; otherwise, false. The default value is true.
Remarks

If this property is set to true and an error occurs, an exception derived from MailBeeException is thrown.

Note Note
The code of the last occurred error is always contained in LastResult property. The list of all error codes is available in ErrorCodes class overview.

Even if this property is set to false, the exceptions which occur due to errors in MailBee usage will still be thrown. Typical example of such errors is passing invalid arguments to methods.

Examples
This sample simulates an error and exception by attempting to load a file with non-existent name. The first attempt is made with exceptions turned off, the second - with exceptions turned on.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();

        // Turn off exception handling.
        msg.ThrowExceptions = false;

        // Generate an error.
        if (!msg.LoadMessage("Wrong Path"))
        {
            Console.WriteLine("Error occurred. Error code is " + msg.LastResult.ToString());
        }

        // Turn on exception handling.
        msg.ThrowExceptions = true;

        // The code below will throw an exception.
        try
        {
            msg.LoadMessage("Wrong Path");
        }
        catch (MailBeeException ex)
        {
            // But we catch it. We display the type of the exception. In your app,
            // you can check other useful properties such as Message or ErrorCode.
            Console.WriteLine("\r\nThe following exception was thrown:\r\n" + ex.GetType().ToString());
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim msg As New MailMessage

        ' Turn off exception handling.
        msg.ThrowExceptions = False

        ' Generate an error.
        If Not msg.LoadMessage("Wrong Path") Then
            Console.WriteLine("Error occurred. Error code is " & msg.LastResult.ToString())
        End If

        ' Turn on exception handling.
        msg.ThrowExceptions = True

        ' Throw an exception.
        Try
            msg.LoadMessage("Wrong Path")
        Catch ex As MailBeeException
            ' But we catch it. We display the type of the exception. In your app,
            ' you can check other useful properties such as Message or ErrorCode.
            Console.WriteLine(vbCrLf & "The following exception was thrown:" & vbCrLf & _
                ex.GetType().ToString())
        End Try
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBeeMailBeeException
MailMessageLastResult


MailMessage.TimeStamps Property

MailMessageTimeStamps Property
Gets the collection of which represents the trace route of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TimeStampCollection TimeStamps { get; }
Public ReadOnly Property TimeStamps As TimeStampCollection
    Get

Property Value

Type: TimeStampCollection
A reference to the collection which contains the list of entries added to the message by all mail gateways the message has passed through while being delivered. The default value is an empty collection.
Remarks
This collection is populated from Received headers of the message. They represent the route of delivery of the message from the sender to the recipient.
Examples
The example is available in TimeStamp topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.MimeTimeStamp


MailMessage.To Property

MailMessageTo Property
Gets or sets the e-mail addresses of the primary recipients of the mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection To { get; set; }
Public Property To As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
A reference to the collection of the e-mail addresses of the primary recipients of the mail message. The default value is an empty collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

To specify this property as a string, set msg.To.AsString value (assuming msg is MailMessage instance).

To send a message, you should specify at least one recipient's e-mail address in To, Cc, or Bcc property. It's possible, however, to send a mail message even if no recipients specified in the message itself using Smtp.Send method.

If you need to deal with international e-mail addresses (IDN domains), use FromIdnAddress and ToIdnAddress methods to convert e-mail addresses between human-readable and SMTP-safe formats.

Examples
The example is available in MailMessage topic.
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.UidOnServer Property

MailMessageUidOnServer Property
Gets Unique-ID (UID) of the message in the mailbox on the server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object UidOnServer { get; }
Public ReadOnly Property UidOnServer As Object
    Get

Property Value

Type: Object
Returns a null reference (Nothing in Visual Basic) if the message was not received from the mail server; if received from IMAP4 server, returns a long value (Int64) containing positive 32bit value of IMAP4 UID, or -1 if UID could not be retrieved; if received from POP3 server, returns a string containing POP3 UID of this message, or a null reference if the UID value is not available.
Remarks
By default, MailBee does not download the list of POP3 UIDs unless any method which accesses UIDs (such as GetMessageUids) is called. To make sure UIDs are downloaded, set Uidl flag in InboxPreloadOptions property value prior to connecting to the POP3 server. However, some old POP3 servers do not support UIDs, and thus this property will still return null if UIDs are not supported by the server.
Note Note
The developer should use type casting from Object when using this property.
Examples
This sample shows how to obtain UID values of two messages (one received from POP3 server while another - from IMAP4 server).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Assume msgPop3 and msgImap are MailMessage objects which already
// have been received from POP3 and IMAP4 servers.
string pop3Uid = (string)msgPop3.UidOnServer;
long imapUid = (long)msgImap.UidOnServer;
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Assume msgPop3 and msgImap are MailMessage objects which already
' have been received from POP3 and IMAP4 servers.
Dim pop3UID As String = CType(msgPop3.UidOnServer, String)
Dim imapUid As Long = CType(msgImap.UidOnServer, Long)
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessage.Version Property

MailMessageVersion Property
Gets the current version of MailBee.NET Objects.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string containing the current version of MailBee.NET Objects (such as major.minor.build.revision).
Examples
This sample creates the new message and displays the version of MailBee.NET Objects.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();
        Console.WriteLine("You are using MailBee.NET Objects v" + msg.Version);
    }

}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        Dim msg As New MailMessage
        Console.WriteLine("You are using MailBee.NET Objects v" & msg.Version)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MailMessage.XMailer Property

MailMessageXMailer Property
Gets or sets the details about the software which was used to create the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string XMailer { get; set; }
Public Property XMailer As String
    Get
    Set

Property Value

Type: String
A string containing the information about the software which was used to create the message. By default, it's MailBee.NET N, where N - is Version.
Examples
This sample loads the message from .EML file and displays the details of the software, which were used to create the message.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\TestMail.eml");

        // Show the details of software which was used
        // to compose the message.
        Console.WriteLine("The mailer is " + msg.XMailer);
    }

}
Imports System
Imports MailBee
Imports MailBee.Mime

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\TestMail.eml")

        ' Show the details of software which was used
        ' to compose the message.
        Console.WriteLine("The mailer is " & msg.XMailer)
    End Sub
End Module
See Also

Reference

MailMessage Class
MailBee.Mime Namespace


MailMessageCollection Class

MailMessageCollection Class
Provides properties and methods for managing and examining the collection of MailMessage objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeMailMessageCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailMessageCollection : CollectionBase
Public Class MailMessageCollection
    Inherits CollectionBase

The MailMessageCollection type exposes the following members.

Constructors
 | Name | Description
Public method | MailMessageCollection | Initializes a new instance of the MailMessageCollection class
Top
Methods
 | Name | Description
 | Add(MailMessage) | Adds the specified MailMessage object to the collection.
Public method | Add(MailMessageCollection) | Adds the contents of the specified MailMessageCollection the current collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
 | Reverse | Reverses the order of the list of the messages that are stored in the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the MailMessage object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks
This collection is not read-only. You can add messages to this collection using Add(MailMessage) method and reverse the collection using Reverse method. Reverse method is useful if you have received a list of messages from the mail server (for instance, using DownloadMessageHeaders(Int32, Int32, Int32) method) and new messages appear last in this list. To make newer messages be listed first, call Reverse on the returned collection.
Examples
This sample loads the message from .EML file and adds this message to a new collection.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
MailMessageCollection msgColl = new MailMessageCollection();
msgColl.Add(msg);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Dim msgColl = New MailMessageCollection
msgColl.Add(msg)
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage


MailMessageCollection Constructor

MailMessageCollection Constructor
Initializes a new instance of the MailMessageCollection class

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection()
Public Sub New
See Also

Reference

MailMessageCollection Class
MailBee.Mime Namespace


MailMessageCollection Methods

MailMessageCollection Methods

The MailMessageCollection type exposes the following members.

Methods
 | Name | Description
 | Add(MailMessage) | Adds the specified MailMessage object to the collection.
Public method | Add(MailMessageCollection) | Adds the contents of the specified MailMessageCollection the current collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
 | Reverse | Reverses the order of the list of the messages that are stored in the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MailMessageCollection Class
MailBee.Mime Namespace


MailMessageCollection.Add Method

MailMessageCollectionAdd Method
Adds the specified MailMessage or MailMessageCollection object to the collection.
Overload List
 | Name | Description
 | Add(MailMessage) | Adds the specified MailMessage object to the collection.
Public method | Add(MailMessageCollection) | Adds the contents of the specified MailMessageCollection the current collection.
Top
See Also

Reference

MailMessageCollection Class
MailBee.Mime Namespace


MailMessageCollection.Add Method (MailMessage)

MailMessageCollectionAdd Method (MailMessage)
Adds the specified MailMessage object to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    MailMessage message
)
Public Sub Add (
    message As MailMessage
)

Parameters

message
Type: MailBee.MimeMailMessage
The MailMessage object to be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
Examples
The example is available in MailMessageCollection topic.
See Also

Reference

MailMessageCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeMailMessage


MailMessageCollection.Add Method (MailMessageCollection)

MailMessageCollectionAdd Method (MailMessageCollection)
Adds the contents of the specified MailMessageCollection the current collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    MailMessageCollection messages
)
Public Sub Add (
    messages As MailMessageCollection
)

Parameters

messages
Type: MailBee.MimeMailMessageCollection
The MailMessageCollection object whose items should be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | messages is a null reference (Nothing in Visual Basic).
See Also

Reference

MailMessageCollection Class
Add Overload
MailBee.Mime Namespace


MailMessageCollection.Reverse Method

MailMessageCollectionReverse Method
Reverses the order of the list of the messages that are stored in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reverse()
Public Sub Reverse
Remarks
For instance, this method can be used to display the list of message received from mail server in descending order (from new to old ones). By default, mail server returns messages in ascending order (from old to new ones). This method allows the developer to have this collection re-sorted in descending order.
Examples
The sample creates new collection, loads 4 messages from .EML files, adds these messages to the collection, and displays the subjects of these messages. Then, the collection is reversed and the subjects of the messages are shown again (in reverse order).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessageCollection msgColl = new MailMessageCollection();
MailMessage msg = new MailMessage();
for (int i = 1; i < 5; i++)
{
    msg.LoadMessage(string.Format(@"C:\Docs\TestMail{0}.eml", i));
    msgColl.Add(msg);
}
foreach (MailMessage m in msgColl)
{
    Console.WriteLine(m.Subject);
}
msgColl.Reverse();
foreach (MailMessage m in msgColl)
{
    Console.WriteLine(m.Subject);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msgColl As MailMessageCollection = New MailMessageCollection
Dim msg As New MailMessage
Dim i As Integer
For i = 1 To 4
    msg.LoadMessage(String.Format("C:\Docs\TestMail{0}.eml", i))
    msgColl.Add(msg)
Next
For Each m As MailMessage In msgColl
    Console.WriteLine(m.Subject)
Next
msgColl.Reverse()
For Each m As MailMessage In msgColl
    Console.WriteLine(m.Subject)
Next
See Also

Reference

MailMessageCollection Class
MailBee.Mime Namespace
Pop3DownloadMessageHeaders(Int32, Int32, Int32)


MailMessageCollection Properties

MailMessageCollection Properties

The MailMessageCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the MailMessage object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailMessageCollection Class
MailBee.Mime Namespace


MailMessageCollection.Item Property

MailMessageCollectionItem Property
Gets or sets the MailMessage object at the specified zero-based index in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As MailMessage
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index of the MailMessage object in the collection.

Property Value

Type: MailMessage
A MailMessage object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

MailMessageCollection Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MailPriority Enumeration

MailPriority Enumeration
Defines the available values for MailMessage.Priority property.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MailPriority
Public Enumeration MailPriority
Members
Member name | Value | Description
None | 0 | The priority is not set.
Highest | 1 | The highest priority.
High | 2 | High priority.
Normal | 3 | Normal priority.
Low | 4 | Low priority.
Lowest | 5 | The lowest priority.
See Also

Reference

MailBee.Mime Namespace


MailSensitivity Enumeration

MailSensitivity Enumeration
Defines the available values for MailMessage.Sensitivity property.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MailSensitivity
Public Enumeration MailSensitivity
Members
Member name | Value | Description
None | 0 | No sensitivity is set.
Normal | 1 | The normal sensitivity.
Personal | 2 | The sensitivity is set to Personal, as specified by Outlook clients.
Private | 3 | The sensitivity is set to Private, as specified by Outlook clients.
Confidential | 4 | The sensitivity is set to CompanyConfidential, as specified by Outlook clients.
See Also

Reference

MailBee.Mime Namespace


MailTransferEncoding Enumeration

MailTransferEncoding Enumeration
Defines the available values for the properties specifying mail transfer encoding for text parts or attachments of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MailTransferEncoding
Public Enumeration MailTransferEncoding
Members
Member name | Value | Description
None | 0 | The text part is not encoded.
Raw7bit | 1 | The contents of the text part are not encoded 7-bit chars (ASCII) only.
Raw8bit | 2 | The contents of the text part are not encoded 8-bit chars.
QuotedPrintable | 3 | The contents of the text part are encoded with Quoted-Printable. The output is 7-bit, ASCII chars except '=' char are represented as itself, 8-bit chars and '=' char are represented as '=XX'. Recommended for texts which are mostly ASCII.
Base64 | 4 | The contents of the text part are encoded with Base64. The output is 7-bit but not human readable. 3 chars are represented as 4 7-bit bytes. Recommended for binary data and non-ASCII texts.
Uue | 5 | The contents of the text part are encoded with UUE. Like Base64, the ouput is 7-bit but not human readable. Not recommended for use but supported for compatibility.
Remarks
The properties of this type are MailMessage.MailTransferEncodingPlain, MailMessage.MailTransferEncodingHtml, TextBodyPart.TransferEncoding. To add attachments with mail-transfer-encoding specification, use the method like Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding).
See Also

Reference

MailBee.Mime Namespace


MessageBodyType Enumeration

MessageBodyType Enumeration
Defines the available types of the mail message body being loaded with LoadBodyText(String, MessageBodyType) method.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MessageBodyType
Public Enumeration MessageBodyType
Members
Member name | Value | Description
Plain | 0 | Plain-text body.
Html | 1 | HTML body.
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage


MessageBuilderConfig Class

MessageBuilderConfig Class
Provides properties and methods which affect how the mail message is being built from the MailMessage object properties and collections into the message raw data (in MIME format).
Inheritance Hierarchy
SystemObject
MailBee.MimeMessageBuilderConfig

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MessageBuilderConfig
Public Class MessageBuilderConfig

The MessageBuilderConfig type exposes the following members.

Methods
 | Name | Description
 | Apply | Rebuilds the message accordingly the current settings.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | SetDomainKeysSignOnSend | Forces MailBee to sign all outgoing e-mail messages with DKIM or DomainKeys signatures.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | AddressDelimeter | Gets or sets the character to be used as a delimiter for e-mail addresses.
Public property | BuildHeaderOnly | Forces MailBee to build only the message header and leave the body section intact.
 | HtmlToPlainMode | Gets or sets the condition which triggers automatic conversion of the HTML body of the message into plain-text.
Public property | HtmlToPlainOptions | Gets or sets the options which affect automatic conversion of the HTML body into plain-text.
Public property | KeepEmptyHeaders | Forces MailBee to include empty headers in the message upon building the message.
 | OnReplaceUriWithCid | Gets or sets the delegate to be called whenever MailBee tries to import the resource referenced in the HTML body and replace it with CID.
 | RelatedFilesFolder | Gets or sets the path to the folder from which to take the files related to the message.
Public property | RemoveBccOnSend | Indicates whether BCC header should be removed from the message when it gets sent or submitted to the pickup folder.
Public property | SetDateOnSend | Indicates whether the current date and time should be added to the message at the moment of sending or submitting to the pickup folder.
Public property | SetMessageIDOnSend | Indicates if Message-ID header should be set to a new unique value and added to the message at the moment of sending or submitting to the pickup folder.
Top
Remarks

This class allows the developer to tune how a new mail message will be generated from MailMessage properties and collections. This may include automatic creation of plain-text version of the HTML body, setting Date and MessageID values, and much more. A new mail message is a message created with MailBee.

To tune how an existing mail message should be being parsed, use MailMessage.Parser property. An existing mail message is a message received from another source (such as file, stream, mail server, etc).

A message can be both existing and new. For instance, if you have received a message from the mail server (this makes this message existing), modified it and are re-sending it again. This will produce a new message (although it's based on another existing message).

Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, use MailMessage.Builder property.
Examples
The sample creates a new message, enables automatic creation of the plain-text version of the HTML body, and saves the message to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Tell MailBee to create plain-text version of the HMTL body.
msg.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;

// Set the HTML body contents.
msg.BodyHtmlText = @"<html><b>Hello</b>, <i>World</i>!</html>";

// Save the message into a folder. The plain-text version will be
// created at this point along with generating MIME source of the message.
msg.SaveMessage(@"C:\Temp\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Tell MailBee to create plain-text version of the HMTL body.
msg.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain

' Set the HTML body contents.
msg.BodyHtmlText = "<html><b>Hello</b>, <i>World</i>!</html>"

' Save the message into a folder. The plain-text version will be
' created at this point along with generating MIME source of the message.
msg.SaveMessage("C:\Temp\TestMail.eml")
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage
MailMessageBuilder
MailMessageParser


MessageBuilderConfig Methods

MessageBuilderConfig Methods

The MessageBuilderConfig type exposes the following members.

Methods
 | Name | Description
 | Apply | Rebuilds the message accordingly the current settings.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | SetDomainKeysSignOnSend | Forces MailBee to sign all outgoing e-mail messages with DKIM or DomainKeys signatures.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace


MessageBuilderConfig.Apply Method

MessageBuilderConfigApply Method
Rebuilds the message accordingly the current settings.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Apply()
Public Sub Apply
Remarks

The Builder properties which affect building the message should be set BEFORE using this method. Otherwise, these options won't take effect.

Normally, there is no need to call this method since MailBee automatically applies the current Builder settings when building the MIME source of the message from its properties and collections. You should, however, call this method if you need to get the results of buiding the message without saving it into a file, sending it, etc. For instance, if you configured MailBee to generate plain-text version of the HTML body during building the message (actually, this convesion is turned on by default), you may want to get this plain-text version for some reason (i.e. you are not going to send the message now, you need this plain-text version itself). In this case, it's enough to call Apply method.

Internally, Apply method just calls GetMessageRawData method of the parent MailMessage object but does not return any value.

Examples
This sample creates a new message, loads HTML message body from HTML file, and generates plain-text body from the HTML body. The sample demonstrates that the plain-text body won't be generated until the message gets built (which occurs either when the MIME source of the message needs to be generated or when Apply method is called).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message body from HTML file.
MailMessage msg = new MailMessage();
msg.LoadBodyText(@"C:\Docs\index.htm", MessageBodyType.Html);

// Show the empty plain-text message body.
Console.WriteLine(msg.BodyPlainText);
Console.WriteLine("---------------------------------------");

// Build the message. Plain-text version will be created at this moment.
msg.Builder.Apply();

// Show the generated plain-text message body.
Console.WriteLine(msg.BodyPlainText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message body from HTML file.
Dim msg As New MailMessage
msg.LoadBodyText("C:\Docs\index.htm", MessageBodyType.Html)

' Show the empty plain-text message body.
Console.WriteLine(msg.BodyPlainText)
Console.WriteLine("---------------------------------------")

' Build the message. Plain-text version will be created at this moment.
msg.Builder.Apply()

' Show the generated plain-text message body.
Console.WriteLine(msg.BodyPlainText)
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MessageBuilderConfig.SetDomainKeysSignOnSend Method

MessageBuilderConfigSetDomainKeysSignOnSend Method
Forces MailBee to sign all outgoing e-mail messages with DKIM or DomainKeys signatures.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetDomainKeysSignOnSend(
    bool enabled,
    bool isWebApp,
    string[] headersToSign,
    string privateKeyStr,
    bool isFilename,
    string selector,
    DomainKeysTypes dkTypes
)
Public Sub SetDomainKeysSignOnSend (
    enabled As Boolean,
    isWebApp As Boolean,
    headersToSign As String(),
    privateKeyStr As String,
    isFilename As Boolean,
    selector As String,
    dkTypes As DomainKeysTypes
)

Parameters

enabled
Type: SystemBoolean
If true, enables automatic signing. If false, disables it (this is the default behavior).
isWebApp
Type: SystemBoolean
Must be true for ASP.NET applications, false otherwise.
headersToSign
Type: SystemString
The array of the names of the headers to be included in the signature, or a null reference (Nothing in Visual Basic) if all the message headers should be included in the signature.
privateKeyStr
Type: SystemString
The contents or the filename of the DomainKeys/DKIM private key.
isFilename
Type: SystemBoolean
If true, privateKeyStr denotes the private key filename; otherwise, the contents.
selector
Type: SystemString
The prefix of the sub-domain serving DomainKeys/DKIM for the sender domain.
dkTypes
Type: MailBee.SecurityDomainKeysTypes
Specifies which signatures to create (classic DK, newer DKIM, or both).
Remarks

This method tells MailBee to automatically call DomainKeysSign(Boolean, String, String, Boolean, String, DomainKeysTypes) each time this e-mail gets sent or submitted to the pickup folder.

MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.

See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace


MessageBuilderConfig Properties

MessageBuilderConfig Properties

The MessageBuilderConfig type exposes the following members.

Properties
 | Name | Description
 | AddressDelimeter | Gets or sets the character to be used as a delimiter for e-mail addresses.
Public property | BuildHeaderOnly | Forces MailBee to build only the message header and leave the body section intact.
 | HtmlToPlainMode | Gets or sets the condition which triggers automatic conversion of the HTML body of the message into plain-text.
Public property | HtmlToPlainOptions | Gets or sets the options which affect automatic conversion of the HTML body into plain-text.
Public property | KeepEmptyHeaders | Forces MailBee to include empty headers in the message upon building the message.
 | OnReplaceUriWithCid | Gets or sets the delegate to be called whenever MailBee tries to import the resource referenced in the HTML body and replace it with CID.
 | RelatedFilesFolder | Gets or sets the path to the folder from which to take the files related to the message.
Public property | RemoveBccOnSend | Indicates whether BCC header should be removed from the message when it gets sent or submitted to the pickup folder.
Public property | SetDateOnSend | Indicates whether the current date and time should be added to the message at the moment of sending or submitting to the pickup folder.
Public property | SetMessageIDOnSend | Indicates if Message-ID header should be set to a new unique value and added to the message at the moment of sending or submitting to the pickup folder.
Top
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace


MessageBuilderConfig.AddressDelimeter Property

MessageBuilderConfigAddressDelimeter Property
Gets or sets the character to be used as a delimiter for e-mail addresses.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AddressDelimeterChar AddressDelimeter { get; set; }
Public Property AddressDelimeter As AddressDelimeterChar
    Get
    Set

Property Value

Type: AddressDelimeterChar
An AddressDelimeterChar value representing the delimiter character.
Remarks

This property allows the developer to select a comma (",") or semicolon (";") character to be used as a delimiter for e-mail addresses when composing e-mail address strings consisting of multiple e-mail addresses. The default value is Comma.

This property has no effect on parsing e-mail address strings. During parsing, MailBee accepts both comma and semicolon as valid delimiters.

Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
Examples
The sample creates a new message, sets two recipient e-mail addresses, and demonstrates the effect of changing the delimiter character.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// Create a new MailMessage object.
MailMessage msg = new MailMessage();

// Add message recipients.
msg.To.Add("jdoe@domain.com");
msg.To.Add("bill@domain.com");

// Set semicolon as a delimiter character.
msg.Builder.AddressDelimeter = AddressDelimeterChar.Semicolon;

Console.WriteLine(msg.To.AsString);

// Set comma as a delimiter character.
msg.Builder.AddressDelimeter = AddressDelimeterChar.Comma;

Console.WriteLine(msg.To.AsString);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' Create a new MailMessage object.
Dim msg As New MailMessage

' Add message recipients.
msg.To.Add("jdoe@domain.com")
msg.To.Add("bill@domain.com")

' Set semicolon as a delimiter character.
msg.Builder.AddressDelimeter = AddressDelimeterChar.Semicolon

Console.WriteLine(msg.To.AsString)

' Set comma as a delimiter character.
msg.Builder.AddressDelimeter = AddressDelimeterChar.Comma

Console.WriteLine(msg.To.AsString)
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MessageBuilderConfig.BuildHeaderOnly Property

MessageBuilderConfigBuildHeaderOnly Property
Forces MailBee to build only the message header and leave the body section intact.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool BuildHeaderOnly { get; set; }
Public Property BuildHeaderOnly As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee recreates the header section and appends the existing body section without rebuilding it. If false, the entire message gets rebuilt. The default value is false.
Remarks

You can use this property if you have an existing message and want to modify it by altering its headers only.

Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace


MessageBuilderConfig.HtmlToPlainMode Property

MessageBuilderConfigHtmlToPlainMode Property
Gets or sets the condition which triggers automatic conversion of the HTML body of the message into plain-text.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPlainAutoConvert HtmlToPlainMode { get; set; }
Public Property HtmlToPlainMode As HtmlToPlainAutoConvert
    Get
    Set

Property Value

Type: HtmlToPlainAutoConvert
An HtmlToPlainAutoConvert value which specifies when the HTML body of the message should be automatically converted into the plain-text body. The default value is IfNoPlain.
Remarks
This property controls the condition of automatic converting of the HTML body of the message into plain-text. The original HTML version will not be removed anyway, the plain-text version will be added as alternative body.
Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
Examples
The example is available in MessageBuilderConfig topic.
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


MessageBuilderConfig.HtmlToPlainOptions Property

MessageBuilderConfigHtmlToPlainOptions Property
Gets or sets the options which affect automatic conversion of the HTML body into plain-text.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPlainConvertOptions HtmlToPlainOptions { get; set; }
Public Property HtmlToPlainOptions As HtmlToPlainConvertOptions
    Get
    Set

Property Value

Type: HtmlToPlainConvertOptions
A set of flags affecting how the HTML body of the message is converted into plain-text. The default value is None.
Remarks
This property is usually used in conjunction with HtmlToPlainMode property.
Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MessageBuilderConfigHtmlToPlainMode


MessageBuilderConfig.KeepEmptyHeaders Property

MessageBuilderConfigKeepEmptyHeaders Property
Forces MailBee to include empty headers in the message upon building the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool KeepEmptyHeaders { get; set; }
Public Property KeepEmptyHeaders As Boolean
    Get
    Set

Property Value

Type: Boolean
if true, empty headers will be added to the message header. If false, they will be omitted. The default value is false.
Remarks
Usually, empty headers (which have name but no value) are not needed. However, you may need them in case of DKIM signing to prevent the message from being tampered by adding headers which don't participate in the signature.
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace


MessageBuilderConfig.OnReplaceUriWithCid Property

MessageBuilderConfigOnReplaceUriWithCid Property
Gets or sets the delegate to be called whenever MailBee tries to import the resource referenced in the HTML body and replace it with CID.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ReplaceUriWithCidHandler OnReplaceUriWithCid { get; set; }
Public Property OnReplaceUriWithCid As ReplaceUriWithCidHandler
    Get
    Set

Property Value

Type: ReplaceUriWithCidHandler
The default value is a null reference (Nothing in Visual Basic).
Remarks
Setting this property only makes sense before calling LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) or ImportRelatedFiles(ImportRelatedFilesOptions) methods. See ReplaceUriWithCidHandler topic for details.
Examples
This sample loads some HTML from a file including referenced images. However, images from "https" resources are not imported and their <IMG SRC> remain intact.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;

class Sample
{
    static bool SkipSecureResources(string uri)
    {
        if (uri.ToLower().StartsWith("https:"))
        {
            return false;
        }
        return true;
    }

    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();

        // Set the delegate and import HTML with related resources. All the references starting with "https:"
        // will be left intact. Other references will be replaced with CIDs generated by MailBee and the files
        // mentioned by these references will be attaced to the message. Each attachment will have Content-ID
        // equal to the corresponding CID in the HTML body.
        msg.Builder.OnReplaceUriWithCid = new ReplaceUriWithCidHandler(SkipSecureResources);
        msg.LoadBodyText(@"C:\Temp\test.html", MessageBodyType.Html, null,
            ImportBodyOptions.ImportRelatedFiles | ImportBodyOptions.ImportRelatedFilesFromUris);

        msg.SaveMessage(@"C:\Temp\test.eml");
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime

Class Sample
    Shared Function SkipSecureResources(ByVal uri As String) As Boolean
        If uri.ToLower().StartsWith("https:") Then
            Return False
        End If
        Return True
    End Function

    Shared Sub Main(ByVal args() As String)
        Dim msg As MailMessage = New MailMessage()

        ' Set the delegate and import HTML with related resources. All the references starting with "https:"
        ' will be left intact. Other references will be replaced with CIDs generated by MailBee and the files
        ' mentioned by these references will be attaced to the message. Each attachment will have Content-ID
        ' equal to the corresponding CID in the HTML body.
        msg.Builder.OnReplaceUriWithCid = AddressOf SkipSecureResources
        msg.LoadBodyText("C:\Temp\test.html", MessageBodyType.Html, Nothing, _
            ImportBodyOptions.ImportRelatedFiles Or ImportBodyOptions.ImportRelatedFilesFromUris)

        msg.SaveMessage("C:\Temp\test.eml")
    End Sub
End Class
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace


MessageBuilderConfig.RelatedFilesFolder Property

MessageBuilderConfigRelatedFilesFolder Property
Gets or sets the path to the folder from which to take the files related to the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RelatedFilesFolder { get; set; }
Public Property RelatedFilesFolder As String
    Get
    Set

Property Value

Type: String
A string containing the path to the folder containing the files related to the message. The default value is an empty string which means the files will be searched in the current folder or in the folder where the HTML file being imported resides.
Remarks

MailBee uses this property value when importing files denoted by relative paths only. For absolute paths, this property is NOT used. For instance, if certain <IMG> tag looks like <IMG SRC="C:\Pictures\1.jpg">, <IMG SRC="file:///C:/Docs/picture.gif"> or <IMG SRC="http://www.company.com/logo.png">, it contains absolute path, not relative. Examples of relative paths are <IMG SRC="logo.png">, <IMG SRC="/picture.gif">, <IMG SRC="subfolder\logo.png">. In other words, a relative path does not contain the entire path. To constuct the entire path, the relative path needs to be prepended with certain base path. If this base path is not the current folder in your case, you need to specify it in this property.

RelatedFilesFolder may contain an URI (URL) as well as a local filesystem path. In this case, MailBee will assume that relative paths lead to the resources located on the web.

RelatedFilesFolder property will have effect only if it is set BEFORE related files get imported. The methods which may import them are LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) and ImportRelatedFiles(ImportRelatedFilesOptions).

Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
Examples
This sample creates a new mail message and loads the message body from HTML file. The body charset is set to Windows-1252 and it's allowed to import related files from the local filesystem and from the web. For relative paths, C:\Temp location on the local filesystem will be used as a base path.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.Text;
using MailBee;
using MailBee.Mime;

MailMessage newMsg = new MailMessage();
newMsg.Builder.RelatedFilesFolder = @"C:\Temp";
newMsg.LoadBodyText(@"C:\Docs\TestMail.htm",
    MessageBodyType.Html,
    Encoding.GetEncoding("Windows-1252"),
    ImportBodyOptions.ImportRelatedFiles |
    ImportBodyOptions.ImportRelatedFilesFromUris);
' To use the code below, import these namespaces at the top of your code.
Imports System.Text
Imports MailBee
Imports MailBee.Mime

Dim newMsg As New MailMessage
newMsg.Builder.RelatedFilesFolder = "C:\Temp"
newMsg.LoadBodyText("C:\Docs\TestMail.htm", _
    MessageBodyType.Html, _
    Encoding.GetEncoding("Windows-1252"), _
    ImportBodyOptions.ImportRelatedFiles Or _
    ImportBodyOptions.ImportRelatedFilesFromUris)
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailMessageLoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions)
MailMessageImportRelatedFiles(ImportRelatedFilesOptions)


MessageBuilderConfig.RemoveBccOnSend Property

MessageBuilderConfigRemoveBccOnSend Property
Indicates whether BCC header should be removed from the message when it gets sent or submitted to the pickup folder.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RemoveBccOnSend { get; set; }
Public Property RemoveBccOnSend As Boolean
    Get
    Set

Property Value

Type: Boolean
true if BCC header should be removed before sending the message; otherwise, false. The default value is true.
Remarks
The message will be delivered to BCC recipients in any case (regardless of RemoveBccOnSend value).
Note Note
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
Note Note
This property is ignored when the message is being sent via EWS rather than SMTP (EWS limitation). Exchange server always removes BCC.
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailMessageBcc


MessageBuilderConfig.SetDateOnSend Property

MessageBuilderConfigSetDateOnSend Property
Indicates whether the current date and time should be added to the message at the moment of sending or submitting to the pickup folder.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetDateOnSend { get; set; }
Public Property SetDateOnSend As Boolean
    Get
    Set

Property Value

Type: Boolean
true if the current date and time should be put into Date header of the message at the very moment of sending or submitting to the pickup folder; otherwise, false. The default value is true.
Remarks
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
Note Note
When submitting messages to the pickup folder, you may want to set this property to false and make the actual SMTP agent (like MailBee.NET Queue) set this value when connecting to the SMTP server. Otherwise, if e-mails are generated and delivered at a different time, the spam filter on the recipient's end may consider your e-mails spam. This is because it's common for spam e-mails to have different creation and delivery dates.
Note Note
This property is ignored when the message is being sent via EWS rather than SMTP (EWS limitation).
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailMessageDate


MessageBuilderConfig.SetMessageIDOnSend Property

MessageBuilderConfigSetMessageIDOnSend Property
Indicates if Message-ID header should be set to a new unique value and added to the message at the moment of sending or submitting to the pickup folder.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetMessageIDOnSend { get; set; }
Public Property SetMessageIDOnSend As Boolean
    Get
    Set

Property Value

Type: Boolean
true if a new unique Message-ID should be added to the message at the moment of sending or submitting to the pickup folder; otherwise, false. The default value is true.
Remarks
MessageBuilderConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Builder property.
See Also

Reference

MessageBuilderConfig Class
MailBee.Mime Namespace
MailMessageMessageID


MessageElements Enumeration

MessageElements Enumeration
Defines a set of flags which specify message elements to be cleared by MailMessage.Clear method call.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum MessageElements
<FlagsAttribute>
Public Enumeration MessageElements
Members
Member name | Value | Description
None | 0 | No elements to remove.
Recipients | 1 | Remove all message recipients specified in To, Cc, and Bcc fields.
Attachments | 2 | Remove all items from Attachments collection.
CustomHeaders | 4 | Remove all non-standard headers from the message.
RouteHeaders | 8 | Remove all Received and Return-Path headers from the message.
RawBody | 16 | Clear the raw body presentation of the message (in MIME format). This can save memory when dealing with very large e-mails. See Clear(MessageElements) topic for details.
See Also

Reference

MailBee.Mime Namespace
MailMessageClear(MessageElements)


MessageFolderBehavior Enumeration

MessageFolderBehavior Enumeration
Defines the available modes of maintaining the unique message folder associated with the mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MessageFolderBehavior
Public Enumeration MessageFolderBehavior
Members
Member name | Value | Description
CreateAndDelete | 0 | On GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method call, create temporary folder in WorkingFolder and place the message files there. Once the MailMessage object is deleted or Dispose is called, this folder will be automatically removed with all its contents.
CreateOnly | 1 | Similar to CreateAndDelete, but the unique folder will not be deleted on MailMessage object destruction. This is useful in web applications where MailMessage object exists only for the time of generating response to the client. The developer should remember the folder name (using GetMessageFolder method) and delete it later (when the message is no longer needed).
DoNotCreate | 2 | Do not create a unique folder and place all the files directly in WorkingFolder. No files or folders will be deleted on MailMessage object destruction.
Remarks

When using GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method to save message files into temporary location, the developer has option to tell MailBee to create a unique folder in WorkingFolder and place all message files there, not in WorkingFolder itself. This is useful when multiple messages are processed simultaneously (such as in a web application which is accessed by multiple users).

If the option to create a unique folder is selected, the name of this folder is generated as:
WorkingFolder + "\" + SHA1Digest(Message-ID).

Note Note
MailBee neither saves anything to disk nor creates any folders unless the developer explicitly requests this (for instance, calls GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method). Anyway, messages get parsed directly in memory.
See Also

Reference

MailBee.Mime Namespace


MessageParserConfig Class

MessageParserConfig Class
Provides properties and methods which affect how the mail message is being parsed from the raw data (MIME source) into the MailMessage object properties and collections.
Inheritance Hierarchy
SystemObject
MailBee.MimeMessageParserConfig

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MessageParserConfig
Public Class MessageParserConfig

The MessageParserConfig type exposes the following members.

Methods
 | Name | Description
 | Apply | Applies the current parsing options and re-parses the message.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetMessageFolder | Returns the full path to the folder where the message files were saved by GetHtmlAndSaveRelatedFiles or SaveHtmlAndRelatedFiles(String) method calls or by enabled message autosave mechanism.
Public method | GetMessageIDHash | Returns SHA1 hash of the specified value, or SHA1 hash of the MessageID if no value specified.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Reset | Resets the parsing settings to the default values.
Public method | SetHtmlOutputMode | Configures the parser to prepare the message for displaying in HTML container (such as browser).
 | SetPlainOutputMode | Configures the parser to prepare the message for displaying in plain-text container (such as a TextBox control in WinForms application or the console).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | AHRefCleanup | Gets or sets the options of processing <A HREF> tags in the HTML body.
 | AHRefSuffix | Gets or sets a string which should be added to all <A HREF> tags as their attribute.
 | AutoSaveHtmlMode | Gets or sets if (and how) the HTML body of the message should be saved to disk.
Public property | CharsetConverter | Gets the object which controls charset conversions of string values of MailMessage properties when these values are returned to the application.
 | CharsetMetaTagMode | Gets or sets if (and how) <META> tags should be processed.
Public property | DatesAsUtc | Indicates whether MailBee should return datetime values adjusted to UTC (GMT) timezone.
Public property | EncodingDefault | Gets or sets Encoding to use when the charset is not specified in the e-mail message.
Public property | EncodingOverride | Gets or sets Encoding to use for decoding the message headers and text body parts from bytes to strings.
Public property | FixCrLf | Enables MailBee to replace single Lf characters with CrLf when extracting the plain-text body during parsing the message.
 | HeadersAsHtml | Gets or sets whether the message headers should be returned as HTML.
 | HtmlToPlainMode | Gets or sets the mode which specifies if the HTML body should be automatically converted into the plain text.
 | HtmlToPlainOptions | Gets or sets the options which affect how the HTML body of the message gets converted into plain text.
 | HtmlToSimpleHtmlMode | Gets or sets the mode which specifies when the HTML part of the message should be converted into simple HTML (plain text converted into HTML).
 | HtmlToSimpleHtmlOptions | Gets or sets the options which affect how the HTML part of the message gets converted into simple HTML.
 | ParseHeaderOnly | Gets or sets if only the headers of the message should be parsed.
 | PlainToHtmlMode | Gets or sets if the plain-text body of the message should be automatically converted into HTML.
 | PlainToHtmlOptions | Gets or sets options which affect how the plain-text message body gets converted into HTML.
 | PlainToHtmlQuotationTag | Gets or sets the string containing the tag to be used for highlighting quotations in the message.
 | WorkingFolder | Gets or sets the path to the temporary folder where the files related to the message should be stored.
Public property | WriteUtf8ByteOrderMark | Gets or sets if MailBee should add UTF-8 BOM when saving HTML files in UTF-8 encoding.
Top
Remarks

The properties and methods of this object allow you to fine-tune the process of parsing the message, processing HTML body, creating plain-text from HTML, saving embedded pictures, etc.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.

If you need more advanced methods to post-process HTML body (such as to remove or block unsafe content like Javascript or external images), consider using Processor class and HTML processing rules (for instance, GetSafeHtmlRules).

Examples
This sample creates a new message, tells MailBee parser to save the message as message.htm file (and related files if any) during parsing the message, and parses the message to make message.htm be saved.
Note Note
The message will be parsed automatically if it was not yet parsed and the application requested any item of the message which can be obtained from parsed message only. For instance, reading Subject property or accessing Attachments collection will trigger the parser if the message was not parsed yet. However, in this sample we do not need any values of MailMessage properties and thus we request parsing explicitly using Apply method.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        // Download the first message from the mail server.
        MailMessage msg = Pop3.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", 1);

        // By default, MailBee does not store anything to disk during parsing messages.
        // Tell MailBee parser to save the message as message.htm file during parsing.
        msg.Parser.AutoSaveHtmlMode = HtmlMessageAutoSaving.SaveMessageHtmAndRelatedFiles;

        // By default, MailBee does not create HTML version for plain-text messages. To
        // make sure the created message.htm will not be empty in the case of plain-text
        // message, tell MailBee to create HTML version (which will then be saved as
        // message.htm file). Thus, if the message does contain HTML version, it will be
        // used. If not, MailBee will generate it.
        msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml;

        // By default, message.htm would be saved in the current folder of the application.
        // Tell MailBee to save message.htm and related files into another location.
        msg.Parser.WorkingFolder = @"C:\Docs";

        // Apply parsing and make message.htm file be saved. Alternatively, we could have
        // just called reading msg.Subject or similar property to trigger the parser.
        // However, it would not be elegant approach. Also, Apply method will make the
        // message get reparsed if it was already parsed. This is not used in the current
        // sample but can be helpful if you need to apply different parsing settings to
        // the same message.
        msg.Parser.Apply();

        // Show the path of the folder where message.htm was saved.
        Console.WriteLine(msg.Parser.GetMessageFolder());
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Download the first message from the mail server.
        Dim msg As MailMessage = Pop3.QuickDownloadMessage("mail.domain.com", "jdoe", "secret", 1)

        ' By default, MailBee does not store anything to disk during parsing messages.
        ' Tell MailBee parser to save the message as message.htm file during parsing.
        msg.Parser.AutoSaveHtmlMode = HtmlMessageAutoSaving.SaveMessageHtmAndRelatedFiles

        ' By default, MailBee does not create HTML version for plain-text messages. To
        ' make sure the created message.htm will not be empty in the case of plain-text
        ' message, tell MailBee to create HTML version (which will then be saved as
        ' message.htm file). Thus, if the message does contain HTML version, it will be
        ' used. If not, MailBee will generate it.
        msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml

        ' By default, message.htm would be saved in the current folder of the application.
        ' Tell MailBee to save message.htm and related files into another location.
        msg.Parser.WorkingFolder = "C:\Docs"

        ' Apply parsing and make message.htm file be saved. Alternatively, we could have
        ' just called reading msg.Subject or similar property to trigger the parser.
        ' However, it would not be elegant approach. Also, Apply method will make the
        ' message get reparsed if it was already parsed. This is not used in the current
        ' sample but can be helpful if you need to apply different parsing settings to
        ' the same message.
        msg.Parser.Apply()

        ' Show the path of the folder where message.htm was saved.
        Console.WriteLine(msg.Parser.GetMessageFolder())
    End Sub
End Class
See Also

Reference

MailBee.Mime Namespace
MailMessageParser
MailMessageBuilder


MessageParserConfig Methods

MessageParserConfig Methods

The MessageParserConfig type exposes the following members.

Methods
 | Name | Description
 | Apply | Applies the current parsing options and re-parses the message.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetMessageFolder | Returns the full path to the folder where the message files were saved by GetHtmlAndSaveRelatedFiles or SaveHtmlAndRelatedFiles(String) method calls or by enabled message autosave mechanism.
Public method | GetMessageIDHash | Returns SHA1 hash of the specified value, or SHA1 hash of the MessageID if no value specified.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Reset | Resets the parsing settings to the default values.
Public method | SetHtmlOutputMode | Configures the parser to prepare the message for displaying in HTML container (such as browser).
 | SetPlainOutputMode | Configures the parser to prepare the message for displaying in plain-text container (such as a TextBox control in WinForms application or the console).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.Apply Method

MessageParserConfigApply Method
Applies the current parsing options and re-parses the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Apply()
Public Sub Apply
Remarks

A mail message does not get parsed until any of its properties which requires parsing has been accessed. For instance, if you just received a message from the mail server, it does not get parsed as this point. You may set the required parsing options at this point and then access any of the properties or methods of this message which make it get parsed. No need to call Apply methods in this case.

However, you may need to call this method if the parsing settings have changed after the message has already been parsed (for instance, you accessed the property which made the message get parsed and from this property value you found out that you need to reparse the message with different setting). See ParseHeaderOnly topic for more information.

Examples
The example is available int MessageParserConfig topic.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.GetMessageFolder Method

MessageParserConfigGetMessageFolder Method
Returns the full path to the folder where the message files were saved by GetHtmlAndSaveRelatedFiles or SaveHtmlAndRelatedFiles(String) method calls or by enabled message autosave mechanism.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetMessageFolder()
Public Function GetMessageFolder As String

Return Value

Type: String
A string containing the full path to the folder where the message files were saved due to calling GetHtmlAndSaveRelatedFiles or or SaveHtmlAndRelatedFiles(String) methods or due to parsing the message with enabled autosave mechanism, or a null reference (Nothing in Visual Basic) if no files have been saved yet (the methods above have not been called yet, the message with enabled autosave mechanism was not parsed yet, or the files saved by these methods have already been deleted on Reset or Dispose call).
Remarks

For example, this method is useful when the message files were saved into the unique folder (created in WorkingFolder by GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method with folderMode parameter set to CreateOnly). In this case, the unique folder is created but not automatically deleted when the MailMessage object gets destroyed. The developer can call this method to get the unique folder path, save it somewhere (such as ASP.NET Session) and then use this path to delete the folder later.

If GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) was called with folderMode set to DoNotCreate (or parameterless overload of GetHtmlAndSaveRelatedFiles was used), no unique folder is created, all message files are stored directly in WorkingFolder, and GetMessageFolder method returns the same value as WorkingFolder property.

Automatic saving of the message files during parsing the message can be enabled with AutoSaveHtmlMode if required. By default, MailBee does not write anything to disk during parsing.

When WorkingFolder is a null reference, it's internally assumed that WorkingFolder specifies the system temporary folder of the current user. Thus, GetMessageFolder value will be different from WorkingFolder (which is a null reference) but the behaviour will be the same as described above (for instance, in regard to whether to create unique message sub-folders in the specified folder, etc).

Examples
This sample demonstrates how to get the path of the folder with the message files if MailBee is configured to create unique folder specially for this message within the specified folder.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.WorkingFolder = @"C:\Temp";
Console.WriteLine(msg.GetHtmlAndSaveRelatedFiles(@"C:\Temp",
    VirtualMappingType.NonWeb,
    MessageFolderBehavior.CreateAndDelete));
Console.WriteLine(msg.Parser.GetMessageFolder());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.WorkingFolder = "C:\Temp"
Console.WriteLine(msg.GetHtmlAndSaveRelatedFiles("C:\Temp", _
    VirtualMappingType.NonWeb, _
    MessageFolderBehavior.CreateAndDelete))
Console.WriteLine(msg.Parser.GetMessageFolder())
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigWorkingFolder


MessageParserConfig.GetMessageIDHash Method

MessageParserConfigGetMessageIDHash Method
Returns SHA1 hash of the specified value, or SHA1 hash of the MessageID if no value specified.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetMessageIDHash(
    string messageID
)
Public Function GetMessageIDHash (
    messageID As String
) As String

Parameters

messageID
Type: SystemString
A string to generate SHA1 hash for, or a null reference (Nothing in Visual Basic) to generate the hash for MessageID value of the owner.

Return Value

Type: String
A string value containing the SHA1 hash in uppercase.
Remarks
By default, when you save HTML message with linked resources (like embedded pictures), MailBee creates a folder where to put them. The name is generated as SHA1Hash(Message-ID). You can also use GetMessageIDHash(String) manually. For instance, if you need to get a unique name for a message folder but you don't need to save HTML with embedded pictures. An example is when you want to save the message attachments.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigGetMessageFolder


MessageParserConfig.Reset Method

MessageParserConfigReset Method
Resets the parsing settings to the default values.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reset()
Public Sub Reset
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.SetHtmlOutputMode Method

MessageParserConfigSetHtmlOutputMode Method
Configures the parser to prepare the message for displaying in HTML container (such as browser).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetHtmlOutputMode()
Public Sub SetHtmlOutputMode
Remarks
This method configures the parser as follows:
  • PlainToHtmlMode=PlainToHtmlAutoConvert.IfNoHtml;
  • HtmlToPlainMode=HtmlToPlainAutoConvert.Never;
  • HtmlToSimpleHtmlMode=HtmlToSimpleHtmlAutoConvert.Never;
  • HeadersAsHtml=true;
You should call this method before the message gets parsed. If you called it after, you should reparse it with Apply method.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigApply
MessageParserConfigSetPlainOutputMode


MessageParserConfig.SetPlainOutputMode Method

MessageParserConfigSetPlainOutputMode Method
Configures the parser to prepare the message for displaying in plain-text container (such as a TextBox control in WinForms application or the console).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void SetPlainOutputMode()
Public Sub SetPlainOutputMode
Remarks
This method configures the parser as follows:
  • PlainToHtmlMode=PlainToHtmlAutoConvert.Never;
  • HtmlToPlainMode=HtmlToPlainAutoConvert.IfNoPlain
  • HtmlToSimpleHtmlMode=HtmlToSimpleHtmlAutoConvert.Never;
  • HeadersAsHtml=false;
To specify an output message in HTML text mode, use SetPlainOutputMode property.
Examples
The example is available in MessageParserConfig class overview.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigApply
MessageParserConfigSetHtmlOutputMode


MessageParserConfig Properties

MessageParserConfig Properties

The MessageParserConfig type exposes the following members.

Properties
 | Name | Description
 | AHRefCleanup | Gets or sets the options of processing <A HREF> tags in the HTML body.
 | AHRefSuffix | Gets or sets a string which should be added to all <A HREF> tags as their attribute.
 | AutoSaveHtmlMode | Gets or sets if (and how) the HTML body of the message should be saved to disk.
Public property | CharsetConverter | Gets the object which controls charset conversions of string values of MailMessage properties when these values are returned to the application.
 | CharsetMetaTagMode | Gets or sets if (and how) <META> tags should be processed.
Public property | DatesAsUtc | Indicates whether MailBee should return datetime values adjusted to UTC (GMT) timezone.
Public property | EncodingDefault | Gets or sets Encoding to use when the charset is not specified in the e-mail message.
Public property | EncodingOverride | Gets or sets Encoding to use for decoding the message headers and text body parts from bytes to strings.
Public property | FixCrLf | Enables MailBee to replace single Lf characters with CrLf when extracting the plain-text body during parsing the message.
 | HeadersAsHtml | Gets or sets whether the message headers should be returned as HTML.
 | HtmlToPlainMode | Gets or sets the mode which specifies if the HTML body should be automatically converted into the plain text.
 | HtmlToPlainOptions | Gets or sets the options which affect how the HTML body of the message gets converted into plain text.
 | HtmlToSimpleHtmlMode | Gets or sets the mode which specifies when the HTML part of the message should be converted into simple HTML (plain text converted into HTML).
 | HtmlToSimpleHtmlOptions | Gets or sets the options which affect how the HTML part of the message gets converted into simple HTML.
 | ParseHeaderOnly | Gets or sets if only the headers of the message should be parsed.
 | PlainToHtmlMode | Gets or sets if the plain-text body of the message should be automatically converted into HTML.
 | PlainToHtmlOptions | Gets or sets options which affect how the plain-text message body gets converted into HTML.
 | PlainToHtmlQuotationTag | Gets or sets the string containing the tag to be used for highlighting quotations in the message.
 | WorkingFolder | Gets or sets the path to the temporary folder where the files related to the message should be stored.
Public property | WriteUtf8ByteOrderMark | Gets or sets if MailBee should add UTF-8 BOM when saving HTML files in UTF-8 encoding.
Top
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.AHRefCleanup Property

MessageParserConfigAHRefCleanup Property
Gets or sets the options of processing <A HREF> tags in the HTML body.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AHRefTagAttributes AHRefCleanup { get; set; }
Public Property AHRefCleanup As AHRefTagAttributes
    Get
    Set

Property Value

Type: AHRefTagAttributes
A set of flags specifying the attributes which should be removed from all <A HREF> tags. The default value is None.
Remarks

You can use this and AHRefSuffix properties together to decorate <A HREF> tags, for instance, remove Target attribute and add target=_blank to every <A HREF> tag to make links open in a new window.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.

If you need more advanced methods to post-process HTML body (such as to remove or block unsafe content like Javascript or external images), consider using Processor class and HTML processing rules (for instance, GetSafeHtmlRules).

Examples
This sample loads the message from .EML file and removes all Onclick attributes from all <A HREF> tags.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.AHRefCleanup = AHRefTagAttributes.Onclick;
msg.Parser.Apply();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.AHRefCleanup = AHRefTagAttributes.Onclick
msg.Parser.Apply()
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigAHRefSuffix
MailBee.HtmlProcessor


MessageParserConfig.AHRefSuffix Property

MessageParserConfigAHRefSuffix Property
Gets or sets a string which should be added to all <A HREF> tags as their attribute.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AHRefSuffix { get; set; }
Public Property AHRefSuffix As String
    Get
    Set

Property Value

Type: String
A string to be added to all <A HREF> tags as their attribute. The default value is an empty string (nothing gets added).
Remarks

This and AHRefCleanup properties are usually used together.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message from .EML file, removes Target attributes from all <A HREF> tags, and adds target=_blank instead. This will make all the links open in a new window.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.AHRefCleanup = AHRefTagAttributes.Target;
msg.Parser.AHRefSuffix = "target=_blank";
msg.Parser.Apply();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.AHRefCleanup = AHRefTagAttributes.Target
msg.Parser.AHRefSuffix = "target=_blank"
msg.Parser.Apply()
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigAHRefCleanup


MessageParserConfig.AutoSaveHtmlMode Property

MessageParserConfigAutoSaveHtmlMode Property
Gets or sets if (and how) the HTML body of the message should be saved to disk.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlMessageAutoSaving AutoSaveHtmlMode { get; set; }
Public Property AutoSaveHtmlMode As HtmlMessageAutoSaving
    Get
    Set

Property Value

Type: HtmlMessageAutoSaving
The method of saving the HTML body of the message to disk during parsing the message. The default value is NoAutoSave.
Remarks

This property makes it easier to get any HTML message as a file. You can also save the message as HTML file using SaveHtmlAndRelatedFiles(String) method.

To make plain-text messages be saved as HTML files as well, you should also set PlainToHtmlMode property value to IfNoHtml.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
The example is available in MessageParserConfig topic.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigPlainToHtmlMode


MessageParserConfig.CharsetConverter Property

MessageParserConfigCharsetConverter Property
Gets the object which controls charset conversions of string values of MailMessage properties when these values are returned to the application.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringConversionConfig CharsetConverter { get; }
Public ReadOnly Property CharsetConverter As StringConversionConfig
    Get

Property Value

Type: StringConversionConfig
A reference to the StringConversionConfig instance which provides access to the settings which controls charset conversions of string values of MailMessage properties when these values are returned to the application.
Remarks

This property is for advanced use.

By default, all returned strings are Unicode. This property allows the developer to make returned strings be represented in any charset. This may be useful for web applications which do not use UTF-8. WinForms and console applications (and UTF-8 web applications) do not need to use this property.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.CharsetMetaTagMode Property

MessageParserConfigCharsetMetaTagMode Property
Gets or sets if (and how) <META> tags should be processed.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CharsetMetaTagProcessing CharsetMetaTagMode { get; set; }
Public Property CharsetMetaTagMode As CharsetMetaTagProcessing
    Get
    Set

Property Value

Type: CharsetMetaTagProcessing
The method of processing <META> tags which contain charset information. The default value is DoNothing.
Remarks

This property can be used to enable modification of <META> containing the charset specification of the HTML body. HTML messages often contain tags like <META content="xxxxxx; charset=xxxxxx">. However, if the application displays everything in another charset (usually, UTF-8), this charset specification will no longer be valid. It's recommended to remove it from the body by setting CharsetMetaTagMode to RemoveCharsetMetaTag before the message gets parsed. When no charset is specified in <META> tag, the client browser will obtain it from the web page header where it will already be correctly specified by ASP.NET engine.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message from .EML file and sets the correct charset in META tag of the HTML body. Because it's not yet known which charset will be used to print the HTML body contents on the web page, <META content="xxxxxx; charset=xxxxxx"> tag will be simply removed. This is usually OK since the correct charset information will be available in the web page header.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.CharsetMetaTagMode = CharsetMetaTagProcessing.SetCorrectCharset;
msg.Parser.Apply();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.CharsetMetaTagMode = CharsetMetaTagProcessing.SetCorrectCharset
msg.Parser.Apply()
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.DatesAsUtc Property

MessageParserConfigDatesAsUtc Property
Indicates whether MailBee should return datetime values adjusted to UTC (GMT) timezone.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DatesAsUtc { get; set; }
Public Property DatesAsUtc As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, all date properties such as Date, DateReceived, etc will return datetime values as UTC (GMT) time; if false, MailBee will return datetime values as local time. The default value is false.
Remarks

If this property is set to true, all dates specified in mail message are returned as UTC. Otherwise, all dates are timezone-corrected to match local time of the computer running MailBee.

This property has immediate effect. There is no need to re-parse the message (i.e. no need to call Apply method).

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.EncodingDefault Property

MessageParserConfigEncodingDefault Property
Gets or sets Encoding to use when the charset is not specified in the e-mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding EncodingDefault { get; set; }
Public Property EncodingDefault As Encoding
    Get
    Set

Property Value

Type: Encoding
An Encoding object specifying the charset to use during parsing the message for decoding message bytes into strings if the charset is not specifed in the message. The default value is Global.DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.EncodingOverride Property

MessageParserConfigEncodingOverride Property
Gets or sets Encoding to use for decoding the message headers and text body parts from bytes to strings.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding EncodingOverride { get; set; }
Public Property EncodingOverride As Encoding
    Get
    Set

Property Value

Type: Encoding
A Encoding object specifying the charset to be used when decoding headers and text parts of the message from bytes to strings, or a null reference (Nothing in Visual Basic) if the charset settings should be obtained from the message (if it contains the charset information) or from EncodingDefault property (if the charset information is missing in the message). The default value is a null reference.
Remarks
If this property is not null, MailBee will use the specified encoding instead of the charset specified in the message or in EncodingDefault property. This can be useful if the charset information in the message is incorrect and the developer needs to manually override the charset specification.
Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
GlobalDefaultEncoding


MessageParserConfig.FixCrLf Property

MessageParserConfigFixCrLf Property
Enables MailBee to replace single Lf characters with CrLf when extracting the plain-text body during parsing the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool FixCrLf { get; set; }
Public Property FixCrLf As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will replace single Lf (#10) with CrLf (#13#10); if false, MailBee will do not perform such replacement. The default value is false.
Remarks

This is a resource-consuming operation. Enable this property only if you often get e-mails with Lf instead of CrLf and the container where you display the plain-text data does not understand Lf as a line break. For instance, the standard control does not break the line when it encounters Lf without preceeding Cr, while RichTextBox does.

If you know you need this conversion enabled, be sure to enable it BEFORE accessing any properties or methods of the downloaded message (i.e. before the message got parsed).

This property affects only plain-text body. For HTML, the exact format of line breaks is not important.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.HeadersAsHtml Property

MessageParserConfigHeadersAsHtml Property
Gets or sets whether the message headers should be returned as HTML.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool HeadersAsHtml { get; set; }
Public Property HeadersAsHtml As Boolean
    Get
    Set

Property Value

Type: Boolean
true if the message headers should be returned in HTML-encoded form; false if they should be returned as-is. The default value is false.
Remarks

If this property is set to true, all MailMessage properties representing the message headers (like RawHeader, To, From, Subject, etc) will return their values HTML encoded. For instance, ">" will be returned as "&gt;".

This can be useful when printing values of MailMessage properties into HTML container (such as browser).

This property has immediate effect. There is no need to ever call Apply after changing its value.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample creates a new message, sets To field and displays its value both HTML-encoded and as-is.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.To.AsString = "John Doe <jdoe@domain.com>";
Console.WriteLine("HTML Encoding off: " + msg.To.ToString());
msg.Parser.HeadersAsHtml = true;
Console.WriteLine("HTML Encoding on: " + msg.To.ToString());
// To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.To.AsString = "John Doe <jdoe@domain.com>"
Console.WriteLine("HTML Encoding off: " & msg.To.ToString())
msg.Parser.HeadersAsHtml = True
Console.WriteLine("HTML Encoding on: " & msg.To.ToString())
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MessageParserConfig.HtmlToPlainMode Property

MessageParserConfigHtmlToPlainMode Property
Gets or sets the mode which specifies if the HTML body should be automatically converted into the plain text.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPlainAutoConvert HtmlToPlainMode { get; set; }
Public Property HtmlToPlainMode As HtmlToPlainAutoConvert
    Get
    Set

Property Value

Type: HtmlToPlainAutoConvert
The mode which specifies the condition which triggers automatic conversion of HTML body into plain-text body during parsing the message. The default value is Never.
Remarks

Set this property value to IfNoPlain to tell MailBee to automatically generate plain-text version of HTML body if it's not available in the message.

To set additional options of converting HTML into plain text, use HtmlToPlainOptions property.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message from .EML file and tells MailBee to automatically create plain-text version from HTML version if no plain-text version is available. Also, the conversion process is tuned so that the contents of ALT attributes of <IMG> tags would appear in the generated plain text.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;
msg.Parser.HtmlToPlainOptions = HtmlToPlainConvertOptions.AddImgAltText;
Console.WriteLine(msg.BodyPlainText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain
msg.Parser.HtmlToPlainOptions = HtmlToPlainConvertOptions.AddImgAltText
Console.WriteLine(msg.BodyPlainText)
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MailBee.MimeHtmlToPlainConvertOptions
MailBee.MimeMailMessage


MessageParserConfig.HtmlToPlainOptions Property

MessageParserConfigHtmlToPlainOptions Property
Gets or sets the options which affect how the HTML body of the message gets converted into plain text.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPlainConvertOptions HtmlToPlainOptions { get; set; }
Public Property HtmlToPlainOptions As HtmlToPlainConvertOptions
    Get
    Set

Property Value

Type: HtmlToPlainConvertOptions
A set of flags which affect how the HTML body of the message gets converted into plain text. The default value is None.
Remarks
Usually this property is used together with HtmlToPlainMode property.
Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
The example is available in HtmlToPlainMode topic.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigHtmlToPlainMode


MessageParserConfig.HtmlToSimpleHtmlMode Property

MessageParserConfigHtmlToSimpleHtmlMode Property
Gets or sets the mode which specifies when the HTML part of the message should be converted into simple HTML (plain text converted into HTML).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToSimpleHtmlAutoConvert HtmlToSimpleHtmlMode { get; set; }
Public Property HtmlToSimpleHtmlMode As HtmlToSimpleHtmlAutoConvert
    Get
    Set

Property Value

Type: HtmlToSimpleHtmlAutoConvert
The mode specifying the condition which triggers automatic conversion of the HTML part of the message into simple HTML during parsing the message. The default value is Never.
Remarks
Simple HTML represenation can be useful if it's required to get plain-text version of HTML body but display this plain text in HTML container (such as browser). See HtmlToSimpleHtmlAutoConvert topic for details.
Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message from .EML file, converts HTML body into simple HTML format, and displays it.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.HtmlToSimpleHtmlMode = HtmlToSimpleHtmlAutoConvert.IfHtml;
msg.Parser.HtmlToSimpleHtmlOptions = HtmlToSimpleHtmlConvertOptions.AddImgAltText;
Console.WriteLine(msg.BodyHtmlText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.HtmlToSimpleHtmlMode = HtmlToSimpleHtmlAutoConvert.IfHtml
msg.Parser.HtmlToSimpleHtmlOptions = HtmlToSimpleHtmlConvertOptions.AddImgAltText
Console.WriteLine(msg.BodyHtmlText)
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigHtmlToPlainMode


MessageParserConfig.HtmlToSimpleHtmlOptions Property

MessageParserConfigHtmlToSimpleHtmlOptions Property
Gets or sets the options which affect how the HTML part of the message gets converted into simple HTML.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToSimpleHtmlConvertOptions HtmlToSimpleHtmlOptions { get; set; }
Public Property HtmlToSimpleHtmlOptions As HtmlToSimpleHtmlConvertOptions
    Get
    Set

Property Value

Type: HtmlToSimpleHtmlConvertOptions
A set of flags which affect how the HTML part of the message gets converted into simple HTML. The default value is None.
Remarks
Usually, this property is used together with HtmlToSimpleHtmlMode property.
Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
The example is available in HtmlToSimpleHtmlMode topic.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigHtmlToSimpleHtmlMode


MessageParserConfig.ParseHeaderOnly Property

MessageParserConfigParseHeaderOnly Property
Gets or sets if only the headers of the message should be parsed.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ParseHeaderOnly { get; set; }
Public Property ParseHeaderOnly As Boolean
    Get
    Set

Property Value

Type: Boolean
true if only the headers of the message should be parsed; otherwise, the entire message will be parsed. The default value is false.
Remarks

Parsing the message header only can save resources and improve performance in the case if only the headers is everything needed at the current moment. When downloading the message from the mail server, you can use methods which get just message headers. But when loading the message from a file or any other source which is not a mail server, you should use ParseHeaderOnly for that.

Unlike other properties of MessageParserConfig object which can be set both before and after calling LoadMessage(String) method, effect of ParseHeaderOnly differs depending on whether you called it BEFORE loading the message from a file (or stream) or AFTER. If you set ParseHeaderOnly BEFORE loading the message, the loading routine will not even load everything but the header from the file (or stream). If you set ParseHeaderOnly AFTER loading the message (but before accessing any of its properties which may trigger the parsing), the loading routine will already be completed to this moment and the entire message source will be read from the file (or stream); in this case, only the header of this message source will be parsed but the message source itself will be complete. For instance, you can then change ParseHeaderOnly value back to false and call Apply to re-parse this message completely this time. For instance, you can use this approach to preview messages during search: you read a message completely but parse only its header. If the header contains certain data (let's say, Subject of certain kind), you then reparse it completely and get the data you need. If Subject does not contain the required string, you discard the message and proceed to another one.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message header from .EML file and displays the subject of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.Parser.ParseHeaderOnly = true;
msg.LoadMessage(@"C:\Docs\TestMail.eml");
Console.WriteLine(msg.Subject);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.Parser.ParseHeaderOnly = True
msg.LoadMessage("C:\Docs\TestMail.eml")
Console.WriteLine(msg.Subject)
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MailMessageRawHeader


MessageParserConfig.PlainToHtmlMode Property

MessageParserConfigPlainToHtmlMode Property
Gets or sets if the plain-text body of the message should be automatically converted into HTML.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PlainToHtmlAutoConvert PlainToHtmlMode { get; set; }
Public Property PlainToHtmlMode As PlainToHtmlAutoConvert
    Get
    Set

Property Value

Type: PlainToHtmlAutoConvert
The mode specifying the condition which triggers automatic conversion the plain-text body of the message into HTML. The default value is Never.
Remarks

You may need to set this property in order to display plain-text message in an HTML container (such as browser).

To set additional options for coverting plain text into HTML, use HtmlToPlainOptions property.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message from .EML file, converts its plain-text body into HTML if the HTML body is not available in the message, and displays the HTML body.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml;
msg.Parser.PlainToHtmlOptions = PlainToHtmlConvertOptions.UriToLink;
Console.WriteLine(msg.BodyHtmlText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml
msg.Parser.PlainToHtmlOptions = PlainToHtmlConvertOptions.UriToLink
Console.WriteLine(msg.BodyHtmlText)
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigPlainToHtmlOptions


MessageParserConfig.PlainToHtmlOptions Property

MessageParserConfigPlainToHtmlOptions Property
Gets or sets options which affect how the plain-text message body gets converted into HTML.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PlainToHtmlConvertOptions PlainToHtmlOptions { get; set; }
Public Property PlainToHtmlOptions As PlainToHtmlConvertOptions
    Get
    Set

Property Value

Type: PlainToHtmlConvertOptions
A set of flags which affect how the plain-text message body gets converted into HTML. The default value is None.
Remarks
Usually this property is used together with PlainToHtmlMode property.
Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
The example is available in PlainToHtmlMode topic.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigPlainToHtmlMode


MessageParserConfig.PlainToHtmlQuotationTag Property

MessageParserConfigPlainToHtmlQuotationTag Property
Gets or sets the string containing the tag to be used for highlighting quotations in the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string PlainToHtmlQuotationTag { get; set; }
Public Property PlainToHtmlQuotationTag As String
    Get
    Set

Property Value

Type: String
A string containing the quoting tag (like <...>). The default value is an empty string.
Remarks
Usually this property is used in plain-text reply messages. If it's set to non-empty string, then the following activities are also performed during converting plain-text into HTML:
  • To determine the quotation sign, the alphanumeric string (without spaces) ending with ">" will be searched on every line of the plain-text body
  • Then the entire quotation will be highlighted in the finished HTML text
Closing tags are generated automatically. For instance, if PlainToHtmlQuotationTag is <font color=red>, MailBee will automatically finish every quoted line with </font>.
Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.
Examples
This sample loads the message from .EML file, sets the quoting tag and tells MailBee to generate HTML version of the plain-text body even if the HTML body is available (this is required since we're not interested in HTML body in this sample), and displays the generated HTML body with quotations high-lighted.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfPlain;
msg.Parser.PlainToHtmlOptions = PlainToHtmlConvertOptions.UriToLink;
msg.Parser.PlainToHtmlQuotationTag = "<font color=red>";
Console.WriteLine(msg.BodyHtmlText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfPlain
msg.Parser.PlainToHtmlOptions = PlainToHtmlConvertOptions.UriToLink
msg.Parser.PlainToHtmlQuotationTag = "<font color=red>"
Console.WriteLine(msg.BodyHtmlText)
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigPlainToHtmlMode


MessageParserConfig.WorkingFolder Property

MessageParserConfigWorkingFolder Property
Gets or sets the path to the temporary folder where the files related to the message should be stored.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string WorkingFolder { get; set; }
Public Property WorkingFolder As String
    Get
    Set

Property Value

Type: String
A string containing the path to the temporary folder where the related files should be stored, or an empty string if they should be stored in the current folder or a null reference if they should be stored in the system temporary folder of the currently logged user. The default value is an empty string.
Remarks

If this property is an empty string (the default value), the related files will be saved to the current folder during call of GetHtmlAndSaveRelatedFiles method; in the case of SaveHtmlAndRelatedFiles(String) method, they will be saved into the same folder where the HTML file denoted by filename parameter will be saved to.

If the message parser was configured to automatically save related files and optionally message.htm file during parsing the message (AutoSaveHtmlMode is SaveMessageHtmAndRelatedFiles or AlterHtmlBody), the effect of setting WorkingFolder will be the same as for GetHtmlAndSaveRelatedFiles method. Thus, if WorkingFolder is an empty string, related files and message.htm file will be saved in the current folder.

If GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method was used to save related files and folderMode parameter value was NOT DoNotCreate, related files will be stored not directly in WorkingFolder but in its sub-folder which will be created specially for this message with unique name. This makes it possible to use the same WorkingFolder for processing multiple messages simultaneously without the risk of mixing files belonging to different messages.

Note Note
MessageParserConfig object cannot be used on its own. To access its members, the developer should use MailMessage.Parser property.

In case of UWP apps, this path must be accessible to the application. E.g. ApplicationData.Current.LocalFolder.Path.

Examples
The example is available in MessageParserConfig topic.
See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace
MessageParserConfigGetMessageFolder


MessageParserConfig.WriteUtf8ByteOrderMark Property

MessageParserConfigWriteUtf8ByteOrderMark Property
Gets or sets if MailBee should add UTF-8 BOM when saving HTML files in UTF-8 encoding.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool WriteUtf8ByteOrderMark { get; set; }
Public Property WriteUtf8ByteOrderMark As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will prepend UTF-8 output in an HTML file being written to with a 3-byte Byte-Order-Mark (if BOM is not already in the source HTML); if false, no BOM will be added (the default value).
Remarks

This property affects how SaveHtmlAndRelatedFiles(String) method and AutoSaveHtmlMode property (when it's configured to save HTML files). You can set it to true to make it easier for web browsers to understand that the file contents is encoded in UTF-8 (when it's so). This property has no effect when the HTML being writtein is not UTF-8 encoded or BOM is already there.

Setting this property to true often helps if special or non-Latin characters look incorrect when viewing saved HTML files.

See Also

Reference

MessageParserConfig Class
MailBee.Mime Namespace


MimePart Class

MimePart Class
Represents a MIME part of the message.
Inheritance Hierarchy
SystemObject
MailBee.MimeMimePart

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MimePart
Public Class MimePart

The MimePart type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAllParts | Returns the collection containing this MIME part and all its sub-parts (if any) as a flat list.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetRawData | Gets the raw data of the MIME part source.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Parse | Creates a new instance of MimePart object from the specified MIME data.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name | Description
Boundary | Gets the string which delimits MIME parts nested into this part.
Charset | Gets the name of the character encoding of the MIME part.
ContentID | Gets the Content-ID value of the MIME part.
ContentLocation | Gets the content location of the MIME part.
ContentType | Gets the content type of the MIME part as a string.
Description | Gets the content description of the MIME part as a string.
Disposition | Gets the content disposition of the MIME part.
Filename | Gets the filename of the MIME part as specified in the message.
Headers | Gets or sets the collection of the MIME part headers.
IsComplete | Indicates whether the MIME part of the message was received completely.
IsFile | Indicates whether the MIME part is a file.
IsInline | Indicates whether the MIME part is inline.
IsMessageInside | Indicates whether the MIME part is an encapsulated mail message.
IsRelated | Indicates whether the MIME part is related to other MIME parts of this message.
MailEncodingOriginal | Gets the name of the mail transfer encoding of the MIME part.
Name | Gets the name of the MIME part.
PartType | Gets the category of the MIME part content.
RawHeader | Gets a string containing the header section of the MIME part in the original form.
Size | Gets the size of the MIME part content in bytes.
SubParts | Gets the collection of all immediate sub-parts of the MIME part.
Top
Remarks

Each e-mail message consists of one or more MIME parts. Each MIME part consists of a header section and (optionally) a body section. The body section may contain the actual content (text, binary data, etc) or other MIME parts nested into this part. Attachments, text body parts and the message itself are examples of MIME parts.

During parsing the message, MailBee creates a tree of linked MimePart and MimePartCollection objects.

To access the MIME part which corresponds to the message itself (the root part), use MimePartTree property. To access the MIME part which corresponds to a certain attachment, use AsMimePart property of that Attachment object. To access the MIME part which corresponds to a certain text body part, use AsMimePart property of that TextBodyPart object.

Because most properties of MimePart and Attachment object have the same meaning (and every attachment is internally a MIME part - you can get it with Attachment.AsMimePart property), the documentation on these properties usually refers to their versions in Attachment class. Some MimePart properties, however, not applicable or important for Attachment object and thus can only be found in MimePart class.

It's usually not need to create MimePart objects manually. To compose a message consisting of multiple parts, add attachments or text body parts to it. MailBee will produce MIME parts for them during building the message.

However, it's possible to create an instance of MimePart class using Parse(Byte) method.

Examples
The example is available in Boundary topic.
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeAttachment
MailBee.MimeTextBodyPart


MimePart Methods

MimePart Methods

The MimePart type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAllParts | Returns the collection containing this MIME part and all its sub-parts (if any) as a flat list.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetRawData | Gets the raw data of the MIME part source.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Parse | Creates a new instance of MimePart object from the specified MIME data.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePart.GetAllParts Method

MimePartGetAllParts Method
Returns the collection containing this MIME part and all its sub-parts (if any) as a flat list.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePartCollection GetAllParts()
Public Function GetAllParts As MimePartCollection

Return Value

Type: MimePartCollection
A reference to the MimePartCollection object containing body structures of the MIME part and all its sub-parts (including sub-sub-parts, etc).
Remarks

The developer can use this method to get flat representation of the MIME parts tree. This is useful when it's required to quickly iterate through all of the MIME parts (for instance, to count all the attachments of the mail message).

To get the collection of immediate sub-parts of the MIME part, use SubParts property.

Note Note
If a MIME part does not have any sub-parts, this method will return MimePartCollection object containing only this MIME part itself.
Examples
The example is available in MimePartCollection topic.
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MailBee.MimeMailMessage
MailBee.MimeMimePartCollection
MimePartSubParts


MimePart.GetRawData Method

MimePartGetRawData Method
Gets the raw data of the MIME part source.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] GetRawData()
Public Function GetRawData As Byte()

Return Value

Type: Byte
A byte array containing the complete source, with headers and body section, of the MIME part, or an empty array if the part had no MIME source.
Remarks

This property can be used to get not yet parsed, not yet decoded source of the MIME part.

In case if the MIME part was generated by MailBee rather than parsed from a MIME source(this will occur if you construct a new e-mail message rather than parse an existing one), this property will return a byte array of zero length. If you need to workaround this, tell MailBee to build the MIME representation of the message, such as with msg.Builder.Apply() call where msg is MailMessage instance. After that, you can use this method to get the newly generated MIME source. Again, this is not required for existing messages (which have MIME source from the start).

If you need to get binary content, parsed and decoded, of an attachment, use Attachment.GetData method.

See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePart.Parse Method

MimePartParse Method
Creates a new instance of MimePart object from the specified MIME data.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MimePart Parse(
    byte[] dataToParse
)
Public Shared Function Parse (
    dataToParse As Byte()
) As MimePart

Parameters

dataToParse
Type: SystemByte
The byte array containing the MIME part contents (the header and the body).

Return Value

Type: MimePart
A reference to the created MimePart object.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | dataToParse is a null reference (Nothing in Visual Basic).
Remarks
You can use this method to parse standalone MIME parts rather than entire messages. For instance, it's possible to tell IMAP server to return a particular MIME part. You can then parse the received data using Parse(Byte) method. Then, you can create Attachment object from the created MimePart.
Examples
The example is available in Envelope.GetEnvelopeItem topic.
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MailBee.MimeMimePartCollection
MailBee.MimeMailMessage


MimePart Properties

MimePart Properties

The MimePart type exposes the following members.

Properties
Name | Description
Boundary | Gets the string which delimits MIME parts nested into this part.
Charset | Gets the name of the character encoding of the MIME part.
ContentID | Gets the Content-ID value of the MIME part.
ContentLocation | Gets the content location of the MIME part.
ContentType | Gets the content type of the MIME part as a string.
Description | Gets the content description of the MIME part as a string.
Disposition | Gets the content disposition of the MIME part.
Filename | Gets the filename of the MIME part as specified in the message.
Headers | Gets or sets the collection of the MIME part headers.
IsComplete | Indicates whether the MIME part of the message was received completely.
IsFile | Indicates whether the MIME part is a file.
IsInline | Indicates whether the MIME part is inline.
IsMessageInside | Indicates whether the MIME part is an encapsulated mail message.
IsRelated | Indicates whether the MIME part is related to other MIME parts of this message.
MailEncodingOriginal | Gets the name of the mail transfer encoding of the MIME part.
Name | Gets the name of the MIME part.
PartType | Gets the category of the MIME part content.
RawHeader | Gets a string containing the header section of the MIME part in the original form.
Size | Gets the size of the MIME part content in bytes.
SubParts | Gets the collection of all immediate sub-parts of the MIME part.
Top
See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePart.Boundary Property

MimePartBoundary Property
Gets the string which delimits MIME parts nested into this part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Boundary { get; }
Public ReadOnly Property Boundary As String
    Get

Property Value

Type: String
A string containing the delimiter separating MIME sub-parts of this part if. If this part is not multi-part, the return value is an empty string.
Remarks

If the MIME part is multi-part (has one or more MIME parts nested into it), these sub-parts should be separated with a unique delimiter string. This string is specified in boundary attribute of the Content-Type header of the part header section.

For instance, if the MIME part header is Content-type: multipart/mixed; boundary="Boundary_(ID_frk7dChObvUn0w8y7BE4uQ)", the Boundary property will return Boundary_(ID_frk7dChObvUn0w8y7BE4uQ) value.

Examples
This sample loads the message from .EML file and displays the boundary used to delimit sub-root MIME parts of this message. If the message is not multi-part and consists of a root part only, the sample will print an empty line.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Show the boundary.
Console.WriteLine(msg.MimePartTree.Boundary);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Show the boundary.
Console.WriteLine(msg.MimePartTree.Boundary)
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MailBee.MimeMimePartCollection


MimePart.Charset Property

MimePartCharset Property
Gets the name of the character encoding of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Charset { get; }
Public ReadOnly Property Charset As String
    Get

Property Value

Type: String
A string containing the name of the character encoding of the MIME part, or an empty string if the charset is not specified in the MIME part.
Remarks

For instance, if Content-Type header string is Content-Type: text/plain; charset="EUC-KR", this property will return EUC-KR value.

Note Note
Although MimePartTree object represents the root MIME part of the message and thus headers of that MimePart are the same as headers of the MailMessage itself, there still can be difference between msg.Charset and msg.MimePartRoot.Charset values. This is because msg.MimePartRoot.Charset always returns the charset information specified in the headers of this MIME part, while msg.Charset returns the charset specified in another MIME part in the case if the root part of the message does not contain the charset information but any of the nested parts does. This is common case for multi-part messages because multi-part parts do not contain charset information. Use MailMessage.Charset to determine the overall charset of the message.
Examples
This sample loads the message from .EML file and displays the charset of the message as specified in the root part. This value will be empty if the message is multi-part (for instance, contains attachments or alternative plain-text body).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Show the charset specified in the message headers.
Console.WriteLine(msg.MimePartTree.Charset);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Show the charset specified in the message headers.
Console.WriteLine(msg.MimePartTree.Charset)
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MailMessageCharset


MimePart.ContentID Property

MimePartContentID Property
Gets the Content-ID value of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentID { get; }
Public ReadOnly Property ContentID As String
    Get

Property Value

Type: String
A string containing the Content-ID (CID) value of the MIME part, or an empty string if the MIME part has no Content-ID.
Remarks
See Attachment.ContentID for more information regarding Content-IDs.
Examples
This sample loads the message from .EML file and displays Content-ID of each MIME part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every MIME part...
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    // ...show MIME part identifier.
    Console.WriteLine(part.ContentID);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every MIME part...
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    ' ...show MIME part identifier.
    Console.WriteLine(part.ContentID)
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartIsInline


MimePart.ContentLocation Property

MimePartContentLocation Property
Gets the content location of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentLocation { get; }
Public ReadOnly Property ContentLocation As String
    Get

Property Value

Type: String
A string containing the MIME part's content location taken from Content-Location header, or an empty string if Content-Location header is not set.
Remarks

The value of this property is taken from Content-Location header of the message. It usually contains the URI (URL) of the resource contained in this MIME part.

For instance, if the header is Content-Location: http://www.afterlogic.com/images/top.gif, ContentLocation property will return http://www.afterlogic.com/images/top.gif value.

See Attachment.ContentLocation for more information regarding Content-Location.

Examples
This sample loads the message from .EML file and displays the location of each MIME part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    Console.WriteLine(part.ContentLocation);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

For Each part As MimePart In msg.MimePartTree.GetAllParts()
    Console.WriteLine(part.ContentLocation)
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartContentID


MimePart.ContentType Property

MimePartContentType Property
Gets the content type of the MIME part as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ContentType { get; }
Public ReadOnly Property ContentType As String
    Get

Property Value

Type: String
A string containing the MIME part's content type taken from Content-Type header, or an empty string if the content type is not set.
Remarks

The content type value usually consists of common and specific types delimited with "/" character (e.g. image/jpeg, text/html, text/plain, etc). For instance, if the header is Content-Type: text/plain; charset="GB2312", the text/plain value will be returned (additional parameters of Content-Type header will be omitted).

See Attachment.ContentType for more information regarding content types.

Examples
This sample loads the message from .EML file and displays the content type of each MIME part of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every part...
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    // ...show part type.
    Console.WriteLine("The type is " + part.ContentType);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every part...
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    ' ...show part type.
    Console.WriteLine("The type is " & part.ContentType)
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartHeaders


MimePart.Description Property

MimePartDescription Property
Gets the content description of the MIME part as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Description { get; }
Public ReadOnly Property Description As String
    Get

Property Value

Type: String
A string containing the MIME part's content description taken from Content-Description header, or an empty string if Content-Description header is not set. The default value is an empty string.
Remarks
See Attachment.Description for more information regarding Content-Description.
Examples
This sample loads the message from file and displays the description of the root MIME part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
Console.WriteLine(msg.MimePartTree.Description);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Console.WriteLine(msg.MimePartTree.Description)
See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePart.Disposition Property

MimePartDisposition Property
Gets the content disposition of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Disposition { get; }
Public ReadOnly Property Disposition As String
    Get

Property Value

Type: String
A string containing the MIME part's disposition taken from Content-Disposition header, or an empty string if Content-Disposition header is not set. The default value is an empty string.
Remarks

For instance, if the header is Content-Disposition: attachment; filename="image.jpg", the attachment value will be returned (additional parameters will be omitted).

If Disposition is inline or missing, this means this MIME part contains a resource which must be rendered when the message body gets displayed. If it's attachment, the resource is a file which does not need to be rendered in order to correctly display the message.

Examples
This sample loads the message from .EML file and displays disposition of the root MIME part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
Console.WriteLine(msg.MimePartTree.Disposition);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Console.WriteLine(msg.MimePartTree.Disposition)
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartIsInline


MimePart.Filename Property

MimePartFilename Property
Gets the filename of the MIME part as specified in the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; }
Public ReadOnly Property Filename As String
    Get

Property Value

Type: String
A string containing the MIME part's filename taken from filename parameter of Content-Disposition header, or an empty string if not available.
Remarks

For instance, if the header is Content-Disposition: attachment; filename="image.jpg", the Filename property will contain the image.jpg value.

Note Note
This property corresponds to Attachment.FilenameOriginal property, not to Attachment.Filename. For instance, if Filename is empty, Attachment.Filename will still contain valid name which can be used to save the file to disk.
Examples
This sample loads the message from .EML file and displays the filenames of each MIME part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    Console.WriteLine(part.Filename);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    Console.WriteLine(part.Filename)
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartName


MimePart.Headers Property

MimePartHeaders Property
Gets or sets the collection of the MIME part headers.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection Headers { get; set; }
Public Property Headers As HeaderCollection
    Get
    Set

Property Value

Type: HeaderCollection
A HeaderCollection object containing the headers of the MIME part.
Remarks
You can modify these headers. See Attachment.Headers for more information.
Examples
This sample loads the message from .EML file and displays all headers of each MIME part of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    Console.WriteLine(string.Format("MimePart {0} headers values:", part.Name));
    foreach (Header hdr in part.Headers)
    {
        Console.WriteLine(hdr.Value);
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    Console.WriteLine(String.Format("MimePart {0} headers values:", part.Name))
    For Each hdr As Header In part.Headers
        Console.WriteLine(hdr.Value)
    Next
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartRawHeader


MimePart.IsComplete Property

MimePartIsComplete Property
Indicates whether the MIME part of the message was received completely.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsComplete { get; }
Public ReadOnly Property IsComplete As Boolean
    Get

Property Value

Type: Boolean
true if the MIME part was received completely; otherwise, false.
Remarks

If the message was received partially, this property may return false for some MIME parts of the message.

MailBee tests if the MIME part is complete by checking if the closing boundary was found. This, however, works for multi-part messages only. If the message consists of a single part and does not include any boundaries, it's not possible to determine if the part was received completely. However, in this case you can check MailMessage.SizeOnServer property. If its value is larger than MailMessage.Size, the message was incompletely received from the mail server.

Examples
This sample loads the message from file and checks if all MIME parts of this message were received entirely.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
bool allPartsAreComplete = true;
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    if (!part.IsComplete)
    {
        allPartsAreComplete = false;
        break;
    }
}
if (allPartsAreComplete)
{
    Console.WriteLine("allPartsAreComplete == true");
}
else
{
    Console.WriteLine("allPartsAreComplete == false");
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Dim allPartsAreComplete As Boolean = True
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    If Not part.IsComplete Then
        allPartsAreComplete = False
        Exit For
    End If
Next
If allPartsAreComplete Then
    Console.WriteLine("allPartsAreComplete = True")
Else
    Console.WriteLine("allPartsAreComplete = False")
End If
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MailMessageIsEntire
MailMessageSizeOnServer


MimePart.IsFile Property

MimePartIsFile Property
Indicates whether the MIME part is a file.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsFile { get; }
Public ReadOnly Property IsFile As Boolean
    Get

Property Value

Type: Boolean
true if the MIME part is a file; otherwise, false.
Remarks

See Attachment.IsFile for more information.

Examples
This sample loads the message from .EML file and displays all MIME parts recognized as files.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    if (part.IsFile)
    {
        Console.WriteLine("MIME part " + part.Filename + " is file.");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    If part.IsFile Then
        Console.WriteLine("MIME part " & part.Filename & " is file.")
    End If
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePart.IsInline Property

MimePartIsInline Property
Indicates whether the MIME part is inline.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsInline { get; }
Public ReadOnly Property IsInline As Boolean
    Get

Property Value

Type: Boolean
true if the MIME part is inline; otherwise, false.
Remarks
See Attachment.IsInline for more information.
Examples
This sample loads the message from .EML file and displays all inline MIME parts of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    if (part.IsInline)
    {
        Console.WriteLine("MIME part " + part.Name + " is inline.");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    If part.IsInline Then
        Console.WriteLine("MIME part " & part.Name & " is inline.")
    End If
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartIsRelated


MimePart.IsMessageInside Property

MimePartIsMessageInside Property
Indicates whether the MIME part is an encapsulated mail message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsMessageInside { get; }
Public ReadOnly Property IsMessageInside As Boolean
    Get

Property Value

Type: Boolean
true if the MIME part is a mail message; otherwise, false.
Remarks

See Attachment.GetEncapsulatedMessage for more information.

Examples
This sample loads the message from .EML file and displays the number of encapsulated mail messages. It does not count, however, any encapsulated messages which may reside within other encapsulated messages (multiple messages nested within each other).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
int innerMessageCount = 0;
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    if (part.IsMessageInside)
    {
        innerMessageCount++;
    }
}
Console.WriteLine("Number of inner messages: " + innerMessageCount.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim innerMessageCount As Integer = 0
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    If part.IsMessageInside Then
        innerMessageCount = innerMessageCount + 1
    End If
Next
Console.WriteLine("Number of inner messages: " & innerMessageCount.ToString())
See Also

Reference

MimePart Class
MailBee.Mime Namespace
AttachmentGetEncapsulatedMessage


MimePart.IsRelated Property

MimePartIsRelated Property
Indicates whether the MIME part is related to other MIME parts of this message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsRelated { get; }
Public ReadOnly Property IsRelated As Boolean
    Get

Property Value

Type: Boolean
true if the MIME part is related to other MIME part of this message; otherwise, false.
Remarks
The MIME part is considered to be related if it's inline and has non-empty ContentID. This means this part is probably mentioned in the message body and thus relates to that body.
Examples
This sample loads the message from .EML file and displays the number of the related MIME parts.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
int relatedPartsCount = 0;
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    if (part.IsRelated)
    {
        relatedPartsCount++;
    }
}
Console.WriteLine("Number of related parts: " + relatedPartsCount.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim relatedPartsCount As Integer = 0
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    If part.IsRelated Then
        relatedPartsCount = relatedPartsCount + 1
    End If
Next
Console.WriteLine("Number of related parts: " & relatedPartsCount.ToString())
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartIsInline


MimePart.MailEncodingOriginal Property

MimePartMailEncodingOriginal Property
Gets the name of the mail transfer encoding of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MailEncodingOriginal { get; }
Public ReadOnly Property MailEncodingOriginal As String
    Get

Property Value

Type: String
A string containing the name of the mail transfer encoding of the MIME part, or an empty string if the mail transfer encoding information is not available.
Remarks
The value of this property is taken from Content-Transfer-Encoding header. The examples of such encodings are Base64, Quoted-Printable, etc. If missing, this the mail transfer encoding is not used and the MIME part data should be read as is.
Note Note
This value is for advanced use only. You do not need to manually decode MIME part data because MailBee always decodes it automatically.
Examples
This sample loads the message from .EML file and displays the mail transfer encoding of the root MIME part.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
Console.WriteLine(msg.MimePartTree.MailEncodingOriginal);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Console.WriteLine(msg.MimePartTree.MailEncodingOriginal)
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MailBee.MimeMailTransferEncoding


MimePart.Name Property

MimePartName Property
Gets the name of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; }
Public ReadOnly Property Name As String
    Get

Property Value

Type: String
A string containing the "friendly name" (or "display name") of the MIME part, or an empty string if the friendly name is not available.
Remarks

The value of this property is taken from the name parameter of the Content-Type message header.

See Attachment.Name for more information regarding MIME part friendly name.

Examples
This sample loads the message from .EML file and displays the name of each MIME part.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    Console.WriteLine(part.Name);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    Console.WriteLine(part.Name)
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartFilename


MimePart.PartType Property

MimePartPartType Property
Gets the category of the MIME part content.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePartType PartType { get; }
Public ReadOnly Property PartType As MimePartType
    Get

Property Value

Type: MimePartType
The category of the MIME part.
Remarks
While ContentType property returns string value, this property returns one of more generalized MimePartType values.
Examples
This sample loads the message from .EML file and displays the category type of the root MIME part.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
Console.WriteLine(msg.MimePartTree.PartType.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Console.WriteLine(msg.MimePartTree.PartType.ToString())
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartContentType


MimePart.RawHeader Property

MimePartRawHeader Property
Gets a string containing the header section of the MIME part in the original form.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RawHeader { get; }
Public ReadOnly Property RawHeader As String
    Get

Property Value

Type: String
A string containing the MIME part header section as it came with the message, or an empty string if the MIME part was added by the application (for instance, as Attachment object) rather than extracted from the message.
Examples
This sample loads the message from .EML file and displays the raw header sections of each MIME part.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    Console.WriteLine(part.RawHeader);
    Console.WriteLine();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    Console.WriteLine(part.RawHeader)
    Console.WriteLine()
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace
MimePartHeaders


MimePart.Size Property

MimePartSize Property
Gets the size of the MIME part content in bytes.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Size { get; }
Public ReadOnly Property Size As Integer
    Get

Property Value

Type: Int32
A size of the MIME part of the message in bytes.

Return Value

Type: Int32
Remarks
This size includes the lengths of the header and body sections of the MIME part of the message. If the body was mail-transfer-encoded in the message, this size will reflect the size of the MIME part BEFORE decoding. This is different from Attachment.Size value which returns the size of the attachment body section AFTER decoding. Also, Attachment.Size does not count the header section.
Examples
This sample loads the message from .EML file and displays the size of all MIME parts.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    Console.WriteLine(part.Size.ToString());
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    Console.WriteLine(part.Size.ToString())
Next
See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePart.SubParts Property

MimePartSubParts Property
Gets the collection of all immediate sub-parts of the MIME part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePartCollection SubParts { get; }
Public ReadOnly Property SubParts As MimePartCollection
    Get

Property Value

Type: MimePartCollection
A reference to the collection of all immediate sub-parts of the MIME part, or a null reference (Nothing in Visual Basic) if this MIME part is not multi-part.
Remarks
This property contains the collection of immediate sub-parts of the MIME part. To get the MIME part and all its sub-parts (including sub-sub-parts) as a flat list, use GetAllParts method.
Examples
This sample loads the message from .EML file and displays the content type of each MIME part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
if (msg.MimePartTree.SubParts != null)
{
    foreach (MimePart part in msg.MimePartTree.SubParts)
    {
        Console.WriteLine(part.ContentType.ToString());
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
If Not msg.MimePartTree.SubParts Is Nothing Then
    For Each part As MimePart In msg.MimePartTree.SubParts
        Console.WriteLine(part.ContentType.ToString())
    Next
End If
See Also

Reference

MimePart Class
MailBee.Mime Namespace


MimePartCollection Class

MimePartCollection Class
Provides properties and methods for examining the collection of MimePart objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeMimePartCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MimePartCollection : CollectionBase
Public Class MimePartCollection
    Inherits CollectionBase

The MimePartCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets the MIME part at the specified zero-based index in the collection.
 | ItemString | Gets the MIME part by the specified Content-Type.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Examples
This sample loads the message from .EML file and displays Content-Type of all MIME parts.
C#
VB
Copy
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every part...
foreach (MimePart part in msg.MimePartTree.GetAllParts())
{
    // ...show its Content-Type.
    Console.WriteLine("The type is " + part.ContentType);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' For every part...
For Each part As MimePart In msg.MimePartTree.GetAllParts()
    ' ...show its Content-Type.
    Console.WriteLine("The type is " & part.ContentType)
Next
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMimePart


MimePartCollection Methods

MimePartCollection Methods

The MimePartCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MimePartCollection Class
MailBee.Mime Namespace


MimePartCollection Properties

MimePartCollection Properties

The MimePartCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets the MIME part at the specified zero-based index in the collection.
 | ItemString | Gets the MIME part by the specified Content-Type.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MimePartCollection Class
MailBee.Mime Namespace


MimePartCollection.Item Property

MimePartCollectionItem Property
Overload List
Name | Description
ItemInt32 | Gets the MIME part at the specified zero-based index in the collection.
ItemString | Gets the MIME part by the specified Content-Type.
Top
See Also

Reference

MimePartCollection Class
MailBee.Mime Namespace


MimePartCollection.Item Property (Int32)

MimePartCollectionItem Property (Int32)
Gets the MIME part at the specified zero-based index in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePart this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As MimePart
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the MIME part in the collection.

Property Value

Type: MimePart
A MimePart object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and displays Content-Type of all MIME parts.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
MimePartCollection subParts = msg.MimePartTree.GetAllParts();
for (int i = 0; i < subParts.Count; i++)
{
    MimePart part = subParts[i];
    Console.WriteLine(part.ContentType);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Dim i As Integer
Dim subParts As MimePartCollection = msg.MimePartTree.GetAllParts()
For i = 0 To subParts.Count - 1
    Dim part As MimePart = subParts(i)
    Console.WriteLine(part.ContentType)
Next
See Also

Reference

MimePartCollection Class
Item Overload
MailBee.Mime Namespace


MimePartCollection.Item Property (String)

MimePartCollectionItem Property (String)
Gets the MIME part by the specified Content-Type.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePart this[
    string name
] { get; }
Public ReadOnly Default Property Item (
    name As String
) As MimePart
    Get

Parameters

name
Type: SystemString
The Content-Type of the MIME part to be searched in the collection.

Property Value

Type: MimePart
A MimePart object which has ContentType value equal to the specified name; or a null reference (Nothing in Visual Basic) if the collection does not contain such MimePart objects.
Remarks

The search is case-sensitive. For instance, if name is text/plain while ContentType of the MIME part is TEXT/PLAIN, that MimePart object will still be returned.

If multiple MimePart objects in the collection meet the specified search condition, only the first found object will be returned.

Examples
This sample loads the message from .EML file and displays the size of XML body of the message if any.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
MimePart xmlPart = msg.MimePartTree.GetAllParts()["text/xml"];
if (xmlPart != null)
{
    Console.WriteLine(xmlPart.Size.ToString());
}
else
{
    Console.WriteLine("No such MimePart.");
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
Dim xmlPart As MimePart = msg.MimePartTree.GetAllParts()("text/xml")
If Not xmlPart Is Nothing Then
    Console.WriteLine(xmlPart.Size.ToString())
Else
    Console.WriteLine("No such MimePart.")
End If
See Also

Reference

MimePartCollection Class
Item Overload
MailBee.Mime Namespace


MimePartType Enumeration

MimePartType Enumeration
Defines the available categories of MIME parts.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum MimePartType
Public Enumeration MimePartType
Members
Member name | Value | Description
Other | 0 | The MIME part format is non-standard.
PlainText | 1 | The MIME part contains plain text (ContentType is text/plain value).
Html | 2 | The MIME part contains HTML (ContentType is text/html value).
RichText | 3 | The MIME part contains text in rich-text format (ContentType is text/rtf or text/richtext value).
Xml | 4 | The MIME part contains XML data (ContentType is text/xml value).
Rfc822Message | 5 | The MIME part contains encapsulated e-mail message (ContentType is message/rfc822 value).
Image | 6 | The MIME part represents an image (ContentType is image/* value, e.g. image/jpeg, image/gif, etc).
Multipart | 7 | The MIME part contains nested MIME parts (ContentType is multipart/* value, e.g. multipart/mixed, multipart/related, etc).
Remarks
To determine the category of the given MIME part, use PartType property.
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeMimePart


NewAttachmentOptions Enumeration

NewAttachmentOptions Enumeration
Defines the available flags affecting how a new Attachment object will be created by Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) method and its overloads which accept options parameter.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum NewAttachmentOptions
<FlagsAttribute>
Public Enumeration NewAttachmentOptions
Members
Member name | Value | Description
None | 0 | No additional options.
ReplaceIfExists | 1 | If the attachment with such name already exists in collection, it will be replaced with the newly created one. Otherwise, the newly created attachment will be appended to collection.
Inline | 2 | Forcibly add the attachment as inline object. This causes MailBee to insert "Content-Disposition: inline" instead of "Content-Disposition: attachment" in the header section.
NoDefaultHeaders | 4 | Add only custom headers (specified by customHeaders parameter of Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding)) method) and do not produce any default headers.
PathIsUri | 8 | The path to the attachment is a URI (URL) rather than filesystem path. Example is http://www.domain.com/picture.gif. If this flag is not set, filesystem path will be assumed (e.g. C:\Inetpub\wwwroot\picture.gif). This flag has no effect for those overloads of Add(String, String, String, String, HeaderCollection, NewAttachmentOptions, MailTransferEncoding) method which add the attachment from memory rather than from a file.
NoContentDispositionForInline | 16 | If Inline flag is set, NoContentDispositionForInline flag will cause the header section not contain Content-Disposition header at all. Because "inline" is the default value of Content-Disposition parameter in MIME, it's usually safe to omit it completely for inline attachments. Note that not including Content-Disposition header will also cause its "filename" parameter not being set.
See Also

Reference

MailBee.Mime Namespace


PlainToHtmlAutoConvert Enumeration

PlainToHtmlAutoConvert Enumeration
Defines modes which specify the condition which triggers automatic conversion of the plain-text body into HTML during parsing the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum PlainToHtmlAutoConvert
Public Enumeration PlainToHtmlAutoConvert
Members
Member name | Value | Description
IfNoHtml | 0 | When the message does not have an HTML body.
IfPlain | 1 | When the message does have the plain-text body (if there is the HTML body as well, it will be overwritten).
Never | 2 | The plain-text body will not be automatically converted into HTML.
Remarks
You can set any of these modes via MailMessage.Parser.PlainToHtmlMode property.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser


PlainToHtmlConvertOptions Enumeration

PlainToHtmlConvertOptions Enumeration
Defines the available flags affecting conversion of the plain-text body into HTML during parsing the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum PlainToHtmlConvertOptions
<FlagsAttribute>
Public Enumeration PlainToHtmlConvertOptions
Members
Member name | Value | Description
None | 0 | No additional options.
UriToLink | 1 | All URIs (URLs) contained in the plain-text body of the message should be converted into HTML links (e.g. http://www.afterlogic.com will be converted into <a href="http://www.afterlogic.com">http://www.afterlogic.com</a> link). Can be used in conjunction with AHRefSuffix to further decorate HTML links being produced.
Remarks
You can set any combination of these options via MailMessage.Parser.PlainToHtmlOptions property.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser


ReplaceUriWithCidHandler Delegate

ReplaceUriWithCidHandler Delegate
Defines the signature of a method supplied by the application in order to decide whether a particular URI in the HTML being imported must be replaced with a CID and the corresponding resource be attached to the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate bool ReplaceUriWithCidHandler(
    string uri
)
Public Delegate Function ReplaceUriWithCidHandler (
    uri As String
) As Boolean

Parameters

uri
Type: SystemString
The URL of the resource referenced in the HTML being imported.

Return Value

Type: Boolean
Must return true in order to replace this URL with the auto-generated CID and attach the correponding resource to the message.
Remarks

The purpose of this delegate is to let the application precisely control which links to the related resources must be left as-is in the HTML being imported (such as when using LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) or ImportRelatedFiles(ImportRelatedFilesOptions) methods). By default, all such resources are imported and attached to the message.

To set this delegate, use OnReplaceUriWithCid property.

See Also

Reference

MailBee.Mime Namespace
MailMessageLoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions)
MailMessageImportRelatedFiles(ImportRelatedFilesOptions)


StringConversionConfig Class

StringConversionConfig Class
Provides properties the developer can use to affect how the values of string properties of MailMessage and dependent objects should be charset-converted when being returned to the application.
Inheritance Hierarchy
SystemObject
MailBee.MimeStringConversionConfig

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class StringConversionConfig
Public Class StringConversionConfig

The StringConversionConfig type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ConversionMode | Gets or sets the mode of charset conversion of the values of string properties of MailMessage object.
Public property | CustomByteEncoding | Gets or sets the base encoding of the returned values of string properties of MailMessage object.
Public property | DestinationEncoding | Gets or sets the charset of the returned values of string properties of MailMessage object.
Top
Remarks

This class is for advanced use. Use it only if have web application which is non-Unicode (not UTF-8) and you need to avoid conversion of the mail message data into the response charset. This may happen when ASP.NET produces the page output (which consits of 8-bit bytes, not 16-bit Unicode chars) and thus converts the data from strings into bytes. The default conversion into the response charset may cause loss of characters which are not defined in this charset.

To avoid this, MailBee can simulate that the message data belong to the system charset while this is actually not so. The details of "string to byte and back to string" approach are:

  1. Convert a string into bytes accordingly the appropriate character encoding (this encoding can be taken from the charset information of the message or hardcoded using DestinationEncoding property).
  2. Convert the bytes into a string accordingly CustomByteEncoding (prior to that, the application should set CustomByteEncoding to the value of responseEncoding setting of web.config file) and return the resulting string to the application.
  3. Then, ASP.NET takes the string generated at the previous step and puts it into the response buffer (which is a byte stream) by converting it from the string into bytes (i.e. opposite action). Since ASP.NET uses the same responseEncoding for that, the resulting byte array will be exactly the same as the one generated at the first step (the second and the third steps compensated each other). This way, the client will receive the same bytes which have been generated by MailBee (these bytes hold the message data encoded in the original message charset or in DestinationEncoding charset). Thus, no characters will be lost when ASP.NET produces the page response and thus converts the string data into responseEncoding even if the string data contain characters which are not defined in responseEncoding charset.
Because the client will receive the message data in the charset specified in the message (or in DestinationEncoding charset), you should also properly set META tag of the HTML data received by the client. You can use MailMessage.Parser.CharsetMetaTagMode property for this. However, if you have not hard-coded the desired charset with DestinationEncoding property and send the message data in its original charset, you should also take care of any other non-ASCII data you may be sending in the server response. For instance, if the HTML data you're sending to the client browser also contain any labels with international characters (such as localized UI elements), they may render incorrectly if they belong to another charset (not the one used the message was composed in). The typical workaround is to HTML encode any international characters so they would become charset independent.

In short, the main purpose of this class is to transfer the given byte data (as it appears in the message) to the client provided that this data will pass through ASP.NET response generator which accepts only strings. This means the byte data should be wrapped into strings using the same encoding used by ASP.NET to convert them from strings back to bytes. You should set this encoding via CustomByteEncoding property.

With this class it's also possible to modify the encoding of the byte data itself (DestinationEncoding property). It affects the charset of the data the client will receive. Or, you can tell MailBee to retain the original charset encoding of the data as it appears in the message.

To set a particular mode of the charset conversion, use ConversionMode property.

Note Note
This class cannot be used on its own. To access its members, use MailMessage.Parser.CharsetConverter property.
See Also

Reference

MailBee.Mime Namespace
MailMessageParser


StringConversionConfig Methods

StringConversionConfig Methods

The StringConversionConfig type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

StringConversionConfig Class
MailBee.Mime Namespace


StringConversionConfig Properties

StringConversionConfig Properties

The StringConversionConfig type exposes the following members.

Properties
 | Name | Description
Public property | ConversionMode | Gets or sets the mode of charset conversion of the values of string properties of MailMessage object.
Public property | CustomByteEncoding | Gets or sets the base encoding of the returned values of string properties of MailMessage object.
Public property | DestinationEncoding | Gets or sets the charset of the returned values of string properties of MailMessage object.
Top
See Also

Reference

StringConversionConfig Class
MailBee.Mime Namespace


StringConversionConfig.ConversionMode Property

StringConversionConfigConversionMode Property
Gets or sets the mode of charset conversion of the values of string properties of MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringConversionMode ConversionMode { get; set; }
Public Property ConversionMode As StringConversionMode
    Get
    Set

Property Value

Type: StringConversionMode
The mode which specifies how to convert the charset of the values of string properties of MailMessage and dependent objects when returning these values to the application. The default value is NoConversion.
See Also

Reference

StringConversionConfig Class
MailBee.Mime Namespace
MessageParserConfigCharsetConverter


StringConversionConfig.CustomByteEncoding Property

StringConversionConfigCustomByteEncoding Property
Gets or sets the base encoding of the returned values of string properties of MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding CustomByteEncoding { get; set; }
Public Property CustomByteEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
An Encoding to use as base encoding of the returned values of string properties of MailMessage and dependent objects. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

You should set this property to the value of responseEncoding of the ASP.NET application (it's usually set in web.config file).

This encoding specifies the encoding to be used on the second step of "string to byte and back to string" conversion when converting bytes into strings.

See Also

Reference

StringConversionConfig Class
MailBee.Mime Namespace
StringConversionConfigDestinationEncoding


StringConversionConfig.DestinationEncoding Property

StringConversionConfigDestinationEncoding Property
Gets or sets the charset of the returned values of string properties of MailMessage object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding DestinationEncoding { get; set; }
Public Property DestinationEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A character Encoding into which to convert the string values when returning them from string properties of MailMessage and dependent objects to the application. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
This property has no effect unless ConversionMode is set to ConvertToDestinationEncoding.
See Also

Reference

StringConversionConfig Class
MailBee.Mime Namespace
StringConversionConfigConversionMode


StringConversionMode Enumeration

StringConversionMode Enumeration
Defines the modes which specify if (and how) the values of string properties of MailMessage and dependent objects should be charset-converted when being returned to the application.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum StringConversionMode
Public Enumeration StringConversionMode
Members
Member name | Value | Description
NoConversion | 0 | The strings will be returned as Unicode. This is normal behavior suitable for most applications.
KeepOriginalByteEncoding | 1 | The original encoding of the string data should be kept.
ConvertToWinByteEncoding | 2 | Convert the string data into Windows version of the original encoding.
ConvertToDestinationEncoding | 3 | Convert the string data into the specified DestinationEncoding.
Remarks

By default, all string properties of MailMessage and dependent objects (such as Attachment, MimePart, etc) return string values in Unicode. Most applications live fine with that.

However, if you are developing non-Unicode web application (i.e. it can use the charset different from UTF-8), you can use MailMessage.Parser.CharsetConverter.ConversionMode property to tell MailBee to return strings in another charset encoding.

The modes defined in this enumeration control if the message data will be returned as Unicode or will retain the same encoding it has in the message or will be converted using another encoding.

See Also

Reference

MailBee.Mime Namespace
MessageParserConfigCharsetConverter


TextBodyPart Class

TextBodyPart Class
Represents a text body of the message.
Inheritance Hierarchy
SystemObject
MailBee.MimeTextBodyPart

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TextBodyPart
Public Class TextBodyPart

The TextBodyPart type exposes the following members.

Constructors
Name | Description
TextBodyPart | Creates a new instance of TextBodyPart object from the specified MimePart object.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsTextReader | Returns StringReader initialized with the text contents of this body part.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | AsMimePart | Gets the text part as MimePart object.
 | Charset | Gets or sets the charset of the text part contents.
 | Headers | Gets the collection of the text part headers.
Public property | IsICalendar | Gets if this body part contains iCal data entry (like meeting request or event).
 | IsOriginal | Indicates if the text part came with the message or it was added automatically during parsing the message.
 | Text | Gets or sets the contents of the text part as a string.
 | TransferEncoding | Gets or sets the mail transfer encoding of the text part contents.
Top
Remarks

The MIME parts of the message can include text parts and attachments.

A MIME part is considered to be a text part if its ContentType starts with text/ and this part is not attachment. For instance, MIME parts of the following content types are text parts:

  • text/plain
  • text/html
  • text/xml
  • text/calendar

To get plain-text body of the message, use BodyPlainText property. To get HTML body, use BodyHtmlText property.

To access all the text parts (in the case if you need specific part, such as XML body if any), use BodyParts property.

Examples
The example is available in TextBodyPartCollection topic.
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeAttachment
MailBee.MimeMimePart


TextBodyPart Constructor

TextBodyPart Constructor
Creates a new instance of TextBodyPart object from the specified MimePart object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart(
    MimePart src
)
Public Sub New (
    src As MimePart
)

Parameters

src
Type: MailBee.MimeMimePart
The MimePart object from which to create the text part.
Examples
A similar example (creating attachments from MIME parts) is available in GetEnvelopeItem(String, Boolean) method documentation.
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace
MailBee.MimeMimePart


TextBodyPart Methods

TextBodyPart Methods

The TextBodyPart type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsTextReader | Returns StringReader initialized with the text contents of this body part.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace


TextBodyPart.GetAsTextReader Method

TextBodyPartGetAsTextReader Method
Returns StringReader initialized with the text contents of this body part.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextReader GetAsTextReader()
Public Function GetAsTextReader As TextReader

Return Value

Type: TextReader
StringReader object.
Remarks

This helper method allows for using ICalVCard library to parse iCal data.

See IsICalendar topic for details.

See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace
TextBodyPartIsICalendar


TextBodyPart Properties

TextBodyPart Properties

The TextBodyPart type exposes the following members.

Properties
 | Name | Description
 | AsMimePart | Gets the text part as MimePart object.
 | Charset | Gets or sets the charset of the text part contents.
 | Headers | Gets the collection of the text part headers.
Public property | IsICalendar | Gets if this body part contains iCal data entry (like meeting request or event).
 | IsOriginal | Indicates if the text part came with the message or it was added automatically during parsing the message.
 | Text | Gets or sets the contents of the text part as a string.
 | TransferEncoding | Gets or sets the mail transfer encoding of the text part contents.
Top
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace


TextBodyPart.AsMimePart Property

TextBodyPartAsMimePart Property
Gets the text part as MimePart object.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MimePart AsMimePart { get; }
Public ReadOnly Property AsMimePart As MimePart
    Get

Property Value

Type: MimePart
A MimePart object representing the text part as a MIME part.
Remarks

MimePart corresponding to the given text part provides access to those properties that are not available in TextBodyPart but accessible in MimePart only.

To get the root part of the MIME parts tree of the message, use MimePartTree property of MailMessage object. MimePartTree MIME part contains all the MIME parts of the message.

Examples
The example is available in TextBodyPartCollection topic.
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace


TextBodyPart.Charset Property

TextBodyPartCharset Property
Gets or sets the charset of the text part contents.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Charset { get; set; }
Public Property Charset As String
    Get
    Set

Property Value

Type: String

Property Value

Type: String
A string containing the name of the charset of the text body part contents, or an empty string if the charset is not specified in the message.
Remarks

When composing a message, you can use this property to set different charsets for different text parts of the message.

It has no effect on parsing messages. To set the encoding to be used during parsing messages, use EncodingDefault or EncodingOverride properties.

Examples
This sample creates a new message with HTML and plain-text bodies, sets different charsets for these bodies, and save the message to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.BodyHtmlText = "<b>Hello</b>, <i>World</i>!";
msg.BodyParts.Html.Charset = "utf-8";
msg.BodyPlainText = "Hello, World!";
msg.BodyParts.Plain.Charset = "us-ascii";
msg.SaveMessage(@"C:\Docs\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.BodyHtmlText = "<b>Hello</b>, <i>World</i>!"
msg.BodyParts.Html.Charset = "utf-8"
msg.BodyPlainText = "Hello, World!"
msg.BodyParts.Plain.Charset = "us-ascii"
msg.SaveMessage("C:\Docs\TestMail.eml")
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace
MailMessageCharset


TextBodyPart.Headers Property

TextBodyPartHeaders Property
Gets the collection of the text part headers.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HeaderCollection Headers { get; }
Public ReadOnly Property Headers As HeaderCollection
    Get

Property Value

Type: HeaderCollection
A HeaderCollection object containing the headers of the text part.
Examples
This sample loads the message from .EML file and displays the values of headers of each text part of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// For every text part...
foreach (TextBodyPart part in msg.BodyParts)
{
    // Show the type of the text part.
    Console.WriteLine(string.Format("Text part {0} headers values:", part.AsMimePart.ContentType));

    // For every header...
    foreach (Header hdr in part.Headers)
    {
        // Show the value of the header.
        Console.WriteLine(hdr.Value);
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

Dim part As TextBodyPart
Dim hdr As Header

' For every text part...
For Each part In msg.BodyParts
    ' Show the type of the text part.
    Console.WriteLine(String.Format("Text part {0} headers values:", part.AsMimePart.ContentType))

    ' For every header...
    For Each hdr In part.Headers
        ' Show the value of the header.
        Console.WriteLine(hdr.Value)
    Next
Next
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace
MailBee.MimeHeader


TextBodyPart.IsICalendar Property

TextBodyPartIsICalendar Property
Gets if this body part contains iCal data entry (like meeting request or event).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsICalendar { get; }
Public ReadOnly Property IsICalendar As Boolean
    Get

Property Value

Type: Boolean
true if this body part is an iCal data; otherwise, false.
Remarks

You can use GetAsTextReader method to get the contained iCal data in the form suitable for ICalVCard library.

For sample code and further details, see iCal and vCard Developer's Guide.

See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace


TextBodyPart.IsOriginal Property

TextBodyPartIsOriginal Property
Indicates if the text part came with the message or it was added automatically during parsing the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsOriginal { get; }
Public ReadOnly Property IsOriginal As Boolean
    Get

Property Value

Type: Boolean
true if the text part is the original part of the message; otherwise, false.
Remarks

If the message does not have plain-text or HTML body, Parser object can be configured to tell MailBee to generate such a body (in fact, create the corresponding TextBodyPart) during parsing. MailBee will place automatically created parts of the message into BodyParts collection.

Also, the developer can manually add a text part into BodyParts collection using its methods.

The scenarios listed above will produce TextBodyPart objects having IsOriginal set to false.

Examples
This sample loads the message from .EML file, generates HTML body from the plain-text body, and reports whether HTML and plain-text parts are original.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load plain-text message and make HTML body automatically.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\PlainTextEmail.eml");
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfPlain;

// Report plain-text and HTML parts origin.
Console.WriteLine("Plain part IsOriginal = " + msg.BodyParts.Plain.IsOriginal.ToString());
Console.WriteLine("HTML part IsOriginal = " + msg.BodyParts.Html.IsOriginal.ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load plain-text message and make HTML body automatically.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\PlainTextEmail.eml")
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfPlain

' Report plain-text and HTML parts origin.
Console.WriteLine("Plain part IsOriginal = " & msg.BodyParts.Plain.IsOriginal.ToString())
Console.WriteLine("HTML part IsOriginal = " & msg.BodyParts.Html.IsOriginal.ToString())
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace
MailMessageParser


TextBodyPart.Text Property

TextBodyPartText Property
Gets or sets the contents of the text part as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Text { get; set; }
Public Property Text As String
    Get
    Set

Property Value

Type: String
A string containing the actual contents of the text part.
Examples
The example is available in TextBodyPartCollection topic.
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace


TextBodyPart.TransferEncoding Property

TextBodyPartTransferEncoding Property
Gets or sets the mail transfer encoding of the text part contents.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailTransferEncoding TransferEncoding { get; set; }
Public Property TransferEncoding As MailTransferEncoding
    Get
    Set

Property Value

Type: MailTransferEncoding
The mail transfer encoding of the text part contents. The default value for new messages is QuotedPrintable.
Remarks

When parsing existing messages, the mail transfer encoding is taken from Content-Transfer-Encoding header. If the text part does not contain this header, the value will be None. However, MailBee always decodes messages automatically so this property is just for information purposes only.

When composing new messages, you use this property to set mail transfer encoding to non-QuotedPrintable value. However, this can be useful under special circumstances only. Anyway, to change mail transfer encoding of HTML or plain-text parts of the message, it's easier to use and properties of the MailMessage itself.

Examples
This sample creates a new message with HTML body, sets the mail transfer encoding for the XML part to Base64, and saves it to disk. In real-world app, it would be a bit easier to use property to achieve the same effect.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.BodyHtmlText = "<b>Hello</b>, <i>World</i>!";
msg.BodyParts.Html.TransferEncoding = MailTransferEncoding.Base64;
msg.SaveMessage(@"C:\Docs\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.BodyHtmlText = "<b>Hello</b>, <i>World</i>!"
msg.BodyParts.Html.TransferEncoding = MailTransferEncoding.Base64
msg.SaveMessage("C:\Docs\TestMail.eml")
See Also

Reference

TextBodyPart Class
MailBee.Mime Namespace
MailMessageMailTransferEncodingHtml
MailMessageMailTransferEncodingPlain
MailMessageMailTransferEncodingHtml
MailMessageMailTransferEncodingPlain
MailMessageMailTransferEncodingHtml


TextBodyPartCollection Class

TextBodyPartCollection Class
Provides properties and methods for managing and examining the collection of TextBodyPart objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeTextBodyPartCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TextBodyPartCollection : CollectionBase
Public Class TextBodyPartCollection
    Inherits CollectionBase

The TextBodyPartCollection type exposes the following members.

Methods
 | Name | Description
 | Add(String) | Creates a new text body part of the specified content type and appends it to the collection.
 | Add(TextBodyPart) | Adds the specified TextBodyPart object to the collection.
 | Add(String, HeaderCollection, Boolean) | Creates a new text body part having the specified parameters and appends it to the collection.
 | Clear | Removes all the text parts from the message.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Remove | Removes the text part of the specified content type from the message.
 | RemoveAt | Removes the text part at the specified zero-based index from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
 | Html | Gets a reference to the HTML text part of the message.
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets or sets the TextBodyPart object in the collection at the specified zero-based index.
 | ItemString | Gets a reference to the TextBodyPart object representing the text part of the specified content type.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | Plain | Gets a reference to the plain-text part of the message.
Top
Remarks
To access text parts of the message, use MailMessage.BodyParts property. Also, MailMessage object provides BodyHtmlText and BodyPlainText properties for quick access to the HTML and plain-text body of the message.
Examples
This sample loads the message from .EML file and displays the contents of all text parts of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (TextBodyPart textPart in msg.BodyParts)
{
    Console.WriteLine("Part type: " + textPart.AsMimePart.ContentType);
    Console.WriteLine(textPart.Text);
    Console.WriteLine();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each textPart As TextBodyPart In msg.BodyParts
    Console.WriteLine("Part type: " & textPart.AsMimePart.ContentType)
    Console.WriteLine(textPart.Text)
    Console.WriteLine()
Next
See Also

Reference

MailBee.Mime Namespace
MailMessageBodyParts
MailBee.MimeTextBodyPart


TextBodyPartCollection Methods

TextBodyPartCollection Methods

The TextBodyPartCollection type exposes the following members.

Methods
 | Name | Description
 | Add(String) | Creates a new text body part of the specified content type and appends it to the collection.
 | Add(TextBodyPart) | Adds the specified TextBodyPart object to the collection.
 | Add(String, HeaderCollection, Boolean) | Creates a new text body part having the specified parameters and appends it to the collection.
 | Clear | Removes all the text parts from the message.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
 | Remove | Removes the text part of the specified content type from the message.
 | RemoveAt | Removes the text part at the specified zero-based index from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace


TextBodyPartCollection.Add Method

TextBodyPartCollectionAdd Method
Adds a text body part to the collection.
Overload List
Name | Description
Add(String) | Creates a new text body part of the specified content type and appends it to the collection.
Add(TextBodyPart) | Adds the specified TextBodyPart object to the collection.
Add(String, HeaderCollection, Boolean) | Creates a new text body part having the specified parameters and appends it to the collection.
Top
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace


TextBodyPartCollection.Add Method (String)

TextBodyPartCollectionAdd Method (String)
Creates a new text body part of the specified content type and appends it to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart Add(
    string contentType
)
Public Function Add (
    contentType As String
) As TextBodyPart

Parameters

contentType
Type: SystemString
A string specifying the content type of the text part to be created.

Return Value

Type: TextBodyPart
A reference to the newly added text body part.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | contentType is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new message, adds XML part to the message, and saves this message to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.BodyParts.Add("text/xml");
msg.BodyParts["text/xml"].Text = "<?xml version=\"1.0\" ?>";
msg.SaveMessage(@"C:\Temp\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.BodyParts.Add("text/xml")
msg.BodyParts("text/xml").Text = "<?xml version=""1.0"" ?>"
msg.SaveMessage("C:\Temp\TestMail.eml")
See Also

Reference

TextBodyPartCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeTextBodyPart


TextBodyPartCollection.Add Method (TextBodyPart)

TextBodyPartCollectionAdd Method (TextBodyPart)
Adds the specified TextBodyPart object to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart Add(
    TextBodyPart part
)
Public Function Add (
    part As TextBodyPart
) As TextBodyPart

Parameters

part
Type: MailBee.MimeTextBodyPart
A TextBodyPart object to be added.

Return Value

Type: TextBodyPart
A reference to the added text body part (which is part object).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | part is a null reference (Nothing in Visual Basic).
Examples
This sample creates a new message, loads another message from .EML file, and adds all text parts of the second message to the TextBodyPartCollection of the first message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg1 = new MailMessage();
MailMessage msg2 = new MailMessage();
msg2.LoadMessage(@"C:\Docs\TestMail.eml");
for (int i = 0; i < msg2.BodyParts.Count; i++)
{
    msg1.BodyParts.Add(msg2.BodyParts[i]);
}
msg1.SaveMessage(@"C:\Temp\Result.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim i As Integer
Dim msg1 As New MailMessage
Dim msg2 As New MailMessage
msg2.LoadMessage("C:\Docs\TestMail.eml")
For i = 0 To msg2.BodyParts.Count - 1
    msg1.BodyParts.Add(msg2.BodyParts(i))
Next
msg1.SaveMessage("C:\Temp\Result.eml")
See Also

Reference

TextBodyPartCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeTextBodyPart


TextBodyPartCollection.Add Method (String, HeaderCollection, Boolean)

TextBodyPartCollectionAdd Method (String, HeaderCollection, Boolean)
Creates a new text body part having the specified parameters and appends it to the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart Add(
    string contentType,
    HeaderCollection customHeaders,
    bool noDefaultHeaders
)
Public Function Add (
    contentType As String,
    customHeaders As HeaderCollection,
    noDefaultHeaders As Boolean
) As TextBodyPart

Parameters

contentType
Type: SystemString
A string specifying the content type of the text part to be created.
customHeaders
Type: MailBee.MimeHeaderCollection
A reference to the collection of user-defined headers to be placed into the header section of the text part, a null reference (Nothing in Visual Basic) if no user-defined headers available.
noDefaultHeaders
Type: SystemBoolean
Indicates whether to add the standard headers.

Return Value

Type: TextBodyPart
A reference to the newly added text body part.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | contentType is a null reference (Nothing in Visual Basic) and noDefaultHeaders is false.
Remarks
By default, the newly created text part will contain Content-Type and (optionally) Content-Transfer-Encoding headers. If noDefaultHeaders was true, these headers will not be added and contentType value will be ignored.
Examples
This sample creates a new message, sets plain-text body and alternative XML body with user-defined header, and saves it to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Create a message and set plain-text body.
MailMessage msg = new MailMessage();
msg.BodyPlainText = "See XML body";

// Prepare custom headers for XML part.
HeaderCollection userDefined = new HeaderCollection();
userDefined.Add("Content-Class", "document", true);

// Create XML part and set its contents.
msg.BodyParts.Add("text/xml", userDefined, false).Text = "<?xml version=\"1.0\" ?>";

// Save the message to disk.
msg.SaveMessage(@"C:\Docs\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Create a message and set plain-text body.
Dim msg As MailMessage = New MailMessage
msg.BodyPlainText = "See XML body"

' Prepare custom headers for XML part.
Dim userDefined As HeaderCollection = New HeaderCollection
userDefined.Add("Content-Class", "document", True)

' Create XML part and set its contents.
msg.BodyParts.Add("text/xml", userDefined, False).Text = "<?xml version=""1.0"" ?>"

' Save the message to disk.
msg.SaveMessage("C:\Docs\TestMail.eml")
See Also

Reference

TextBodyPartCollection Class
Add Overload
MailBee.Mime Namespace
MailBee.MimeTextBodyPart


TextBodyPartCollection.Clear Method

TextBodyPartCollectionClear Method
Removes all the text parts from the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear()
Public Sub Clear
Examples
This sample loads the message from .EML file and removes all the text parts from this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all the text parts.
msg.BodyParts.Clear();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all the text parts.
msg.BodyParts.Clear()
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace
MailBee.MimeMailMessage


TextBodyPartCollection.Remove Method

TextBodyPartCollectionRemove Method
Removes the text part of the specified content type from the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    string contentType
)
Public Function Remove (
    contentType As String
) As Boolean

Parameters

contentType
Type: SystemString
A string specifying the content type of text part to be removed.

Return Value

Type: Boolean
true if the TextBodyPart object having the specified content type was found in the collection; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | contentType is a null reference (Nothing in Visual Basic).
Remarks
If more than one text part of the specified content type exist in the collection, only the first found text part will be deleted. To delete other text body parts of the specified content type, call this method until it starts returning false.
Examples
This sample loads the message from .EML file and removes all HTML text parts from the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove all HTML parts from the message.
while (msg.BodyParts.Remove("text/html"));
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove all HTML parts from the message.
While msg.BodyParts.Remove("text/html")
End While
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace


TextBodyPartCollection.RemoveAt Method

TextBodyPartCollectionRemoveAt Method
Removes the text part at the specified zero-based index from the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index of the text part in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and removes the first text part of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");

// Remove the first body part from the collection.
if (msg.BodyParts.Count > 0)
{
    msg.BodyParts.RemoveAt(0);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")

' Remove the first body part from the collection.
If (msg.BodyParts.Count > 0) Then
    msg.BodyParts.RemoveAt(0)
End If
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace


TextBodyPartCollection Properties

TextBodyPartCollection Properties

The TextBodyPartCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
 | Html | Gets a reference to the HTML text part of the message.
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets or sets the TextBodyPart object in the collection at the specified zero-based index.
 | ItemString | Gets a reference to the TextBodyPart object representing the text part of the specified content type.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | Plain | Gets a reference to the plain-text part of the message.
Top
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace


TextBodyPartCollection.Html Property

TextBodyPartCollectionHtml Property
Gets a reference to the HTML text part of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart Html { get; }
Public ReadOnly Property Html As TextBodyPart
    Get

Property Value

Type: TextBodyPart
A reference to TextBodyPart object representing the HTML body and its headers.
Remarks

If the message contains more than one HTML body, this property will return the first found. If the message does not contain HTML body, accessing this property will create new one.

If the above behaviour is not suitable for your case, you can always iterate through the collection and examine each text part as it appears in the message.

Examples
This sample creates a new message with HTML body part and saves this message to disk. In real-world apps, however, it would be easier to set HTML body contents using BodyHtmlText property.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.BodyParts.Html.Text = "<i>Hello</i>, <b>World</b>!";
msg.SaveMessage(@"C:\Docs\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.BodyParts.Html.Text = "<i>Hello</i>, <b>World</b>!"
msg.SaveMessage("C:\Docs\TestMail.eml")
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace
MailMessageBodyParts


TextBodyPartCollection.Item Property

TextBodyPartCollectionItem Property
Overload List
Name | Description
ItemInt32 | Gets or sets the TextBodyPart object in the collection at the specified zero-based index.
ItemString | Gets a reference to the TextBodyPart object representing the text part of the specified content type.
Top
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace


TextBodyPartCollection.Item Property (Int32)

TextBodyPartCollectionItem Property (Int32)
Gets or sets the TextBodyPart object in the collection at the specified zero-based index.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As TextBodyPart
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index of the text part in the collection.

Property Value

Type: TextBodyPart
A TextBodyPart object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
Examples
This sample loads the message from .EML file and displays the content of the first text body of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
if (msg.BodyParts.Count > 0)
{
    Console.WriteLine(msg.BodyParts[0].Text);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
If (msg.BodyParts.Count > 0) Then
    Console.WriteLine(msg.BodyParts(0).Text)
End If
See Also

Reference

TextBodyPartCollection Class
Item Overload
MailBee.Mime Namespace
MailBee.MimeTextBodyPart


TextBodyPartCollection.Item Property (String)

TextBodyPartCollectionItem Property (String)
Gets a reference to the TextBodyPart object representing the text part of the specified content type.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart this[
    string contentType
] { get; }
Public ReadOnly Default Property Item (
    contentType As String
) As TextBodyPart
    Get

Parameters

contentType
Type: SystemString
A string containing the content type of the text part to be searched (such as text/plain).

Property Value

Type: TextBodyPart
A TextBodyPart object representing the text part of the specified content type, or a null reference (Nothing in Visual Basic) if the text part of the specified content type does not exist in the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | contentType is a null reference (Nothing in Visual Basic).
Examples
This sample loads the message from .EML file and displays the contents of XML body of the message (if any).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
if (msg.BodyParts["text/xml"] != null)
{
    Console.WriteLine(msg.BodyParts["text/xml"].Text);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
If Not msg.BodyParts("text/xml") Is Nothing Then
    Console.WriteLine(msg.BodyParts("text/xml").Text)
End If
See Also

Reference

TextBodyPartCollection Class
Item Overload
MailBee.Mime Namespace
MailMessageContentType


TextBodyPartCollection.Plain Property

TextBodyPartCollectionPlain Property
Gets a reference to the plain-text part of the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TextBodyPart Plain { get; }
Public ReadOnly Property Plain As TextBodyPart
    Get

Property Value

Type: TextBodyPart
A reference to TextBodyPart object representing the plain-text body and its headers.
Remarks

If the message contains more than one plain-text body, this property will return the first found. If the message does not contain plain-text body, accessing this property will create new one.

If the above behaviour is not suitable for your case, you can always iterate through the collection and examine each text part as it appears in the message.

Examples
This sample creates a new message with the plain-text body and saves it to disk. In real-world apps, however, it would be easier to set plain-text body contents using BodyPlainText property.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)�
MailMessage msg = new MailMessage();
msg.BodyParts.Plain.Text = "Hello, World!";
msg.SaveMessage(@"C:\Docs\TestMail.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.BodyParts.Plain.Text = "Hello, World!"
msg.SaveMessage("C:\Docs\TestMail.eml")
See Also

Reference

TextBodyPartCollection Class
MailBee.Mime Namespace
MailMessageBodyParts


TimeStamp Class

TimeStamp Class
Provides properties and methods for examining a time stamp representing a moment when the message was received by a mail gateway or a mail server.
Inheritance Hierarchy
SystemObject
MailBee.MimeTimeStamp

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TimeStamp
Public Class TimeStamp

The TimeStamp type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | Bias | Gets the time offset in hours.
 | By | Gets the name of the domain which received the message and added the time stamp.
 | Date | Gets the date and time when the message was received by the mail server.
 | DateAsString | Gets the string containing the date and time when the message was received by the mail server.
 | For | Gets the e-mail address of the recipient as a string.
 | From | Gets the name and/or IP address of the source host from which the message was sent.
 | ID | Gets the unique message identifier assigned by the mail server.
Public property | IP | Gets the IPv4 address extracted from From part of the timestamp.
 | With | Gets the name of the protocol or service which was used to transmit the message.
Top
Remarks

When a mail message gets sent, it passes through one or more mail servers (gateways) during the delivery. Each mail server usually alters the message by adding a new Received header which contains the information about this server and time stamp of the moment when the message passed through this server. TimeStamp class represents the information extracted from a single Received header during parsing the message.

All TimeStamp objects are stored in TimeStampCollection which represents all Received headers of the message. You can access this collection using TimeStamps property.

The first TimeStamp object in the collection usually represents the moment when the message was received by the destination mail server. MailBee uses this TimeStamp object to obtain DateReceived value.

Note Note
Some mail servers do not add Received headers. Thus, no time stamps will be available to the application. In this case, the only way to obtain the date when the message was received is to get Envelope of the message using IMAP and get the date from DateReceived property. Also, even if Received header itself is available, some of its fields may be missing.
Examples
This sample loads the message from .EML file and displays all the values extracted from the time stamps of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class)
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (TimeStamp ts in msg.TimeStamps)
{
    Console.WriteLine(string.Format("Bias: {0}\r\nBy: {1}\r\nDate: {2}\r\nDateAsString: {3}\r\nFor: {4}\r\nFrom: {5}\r\nID: {6}\r\nWith: {7}",
        ts.Bias, ts.By, ts.Date.ToString(), ts.DateAsString, ts.For, ts.From, ts.ID, ts.With));
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each ts As TimeStamp In msg.TimeStamps
    Console.WriteLine(String.Format("Bias: {0}\r\nBy: {1}\r\nDate: {2}\r\nDateAsString: {3}\r\nFor: {4}\r\nFrom: {5}\r\nID: {6}\r\nWith: {7}", _
        ts.Bias, ts.By, ts.Date.ToString(), ts.DateAsString, ts.For, ts.From, ts.ID, ts.With))
Next
See Also

Reference

MailBee.Mime Namespace
MailBee.MimeTimeStampCollection


TimeStamp Methods

TimeStamp Methods

The TimeStamp type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp Properties

TimeStamp Properties

The TimeStamp type exposes the following members.

Properties
 | Name | Description
 | Bias | Gets the time offset in hours.
 | By | Gets the name of the domain which received the message and added the time stamp.
 | Date | Gets the date and time when the message was received by the mail server.
 | DateAsString | Gets the string containing the date and time when the message was received by the mail server.
 | For | Gets the e-mail address of the recipient as a string.
 | From | Gets the name and/or IP address of the source host from which the message was sent.
 | ID | Gets the unique message identifier assigned by the mail server.
Public property | IP | Gets the IPv4 address extracted from From part of the timestamp.
 | With | Gets the name of the protocol or service which was used to transmit the message.
Top
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.Bias Property

TimeStampBias Property
Gets the time offset in hours.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Bias { get; }
Public ReadOnly Property Bias As Integer
    Get

Property Value

Type: Int32
An integer number representing the timezone offset in hours.
Remarks

For instance, for Sat, 25 Dec 2004 09:59:47 -0500 date, the time offset is -0500 and this property will return -5 value.

If the timezone contains not only hours but minutes as well (such as -0530), this property will still return -5. You can get the original timezone value from DateAsString property if you need to precisely handle timezone offset values. Anyway, Date property will always return the correct date (if the DateAsString itself if correct).

Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.By Property

TimeStampBy Property
Gets the name of the domain which received the message and added the time stamp.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string By { get; }
Public ReadOnly Property By As String
    Get

Property Value

Type: String
A string containing the domain name taken from By field of the Received header, or an empty string if not available.
Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.Date Property

TimeStampDate Property
Gets the date and time when the message was received by the mail server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime Date { get; }
Public ReadOnly Property Date As DateTime
    Get

Property Value

Type: DateTime
The date and time when the message was received by the mail server.
Exceptions
Exception | Condition
MailBeeDateParsingException | A date parsing error occurred.
Remarks
To get this date as a string, use DateAsString property. Date property simply parses DateAsString value and returns it as DateTime.
Examples
The example is available in TimeStamp class overview.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace
TimeStampDateAsString


TimeStamp.DateAsString Property

TimeStampDateAsString Property
Gets the string containing the date and time when the message was received by the mail server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DateAsString { get; }
Public ReadOnly Property DateAsString As String
    Get

Property Value

Type: String
A string containing the date and time when the message was received by the mail server.
Remarks

This value is returned in the same format as it is specified in the Received header itself (e.g. Sat, 4 Dec 2004 09:59:47 -0500).

You can use Date property to get this date as DateTime.

Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace
TimeStampDate


TimeStamp.For Property

TimeStampFor Property
Gets the e-mail address of the recipient as a string.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string For { get; }
Public ReadOnly Property For As String
    Get

Property Value

Type: String
A string containing the e-mail address of the intended recipient of the message, or an empty string if the recipient is not specified in the Received header.
Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.From Property

TimeStampFrom Property
Gets the name and/or IP address of the source host from which the message was sent.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string From { get; }
Public ReadOnly Property From As String
    Get

Property Value

Type: String
Contains the sender's mail server domain name and/or IP address as specified in the Received header, or an empty string if from field is missing in the Received header.
Remarks

Typical examples of this property value: mail.domain.com ([1.2.3.4]), MYSERVER (mail.domain.com [1.2.3.4]), etc. There is no strict format for this value.

This value does not necessarily denote the original host which sent this message. Instead, it contains the name of the host which delivered the message to the host which added this time stamp to the message. If the delivery chain consists of many servers, From server simply denotes the previous link in the chain.

Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.ID Property

TimeStampID Property
Gets the unique message identifier assigned by the mail server.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ID { get; }
Public ReadOnly Property ID As String
    Get

Property Value

Type: String
A string containing the unique message identifier assigned by the mail server, or an empty string if id field is missing in the Received header.
Remarks
This value is neither MessageID nor Unique-ID assigned by the destination mail server to the message when it gets added into the mailbox. Also, if the message contains multiple Received headers, their ID values are usually different.
Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.IP Property

TimeStampIP Property
Gets the IPv4 address extracted from From part of the timestamp.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string IP { get; }
Public ReadOnly Property IP As String
    Get

Property Value

Type: String
The first occurrence of IPv4 address in From string, or an empty string if not available.
Remarks
If the entire Received timestamp is like this Received: from SMTPS01 (11.66.222.111) by HUB1.domain.com (10.20.30.40) with Microsoft SMTP Server id 12.34.46.57; Wed, 6 Apr 2016 16:44:13 +0530, this property will return 11.66.222.111.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStamp.With Property

TimeStampWith Property
Gets the name of the protocol or service which was used to transmit the message.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string With { get; }
Public ReadOnly Property With As String
    Get

Property Value

Type: String
A string containing the name of the mail transmitting protocol or service, or an empty string if with field is missing in the Received header.
Remarks
Typical examples of this property value: SMTP, HTTP, MyMailServer ESMTP, etc.
Examples
The example is available in TimeStamp topic.
See Also

Reference

TimeStamp Class
MailBee.Mime Namespace


TimeStampCollection Class

TimeStampCollection Class
Provides properties and methods for examining the collection of TimeStamp objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.MimeTimeStampCollection

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TimeStampCollection : CollectionBase
Public Class TimeStampCollection
    Inherits CollectionBase

The TimeStampCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the TimeStamp object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

When a mail message gets sent, it passes through one or more mail servers (gateways) during the delivery. Each mail server usually alters the message by adding a new Received header which contains the information about this server and time stamp of the moment when the message passed through this server. TimeStamp class represents the information extracted from a single Received header during parsing the message.

All TimeStamp objects are stored in TimeStampCollection which represents all Received headers of the message. You can access this collection using TimeStamps property.

The first TimeStamp object in the collection usually represents the moment when the message was received by the destination mail server. MailBee uses this TimeStamp object to obtain DateReceived value.

Note Note
Some mail servers do not add Received headers. Thus, no time stamps will be available to the application. In this case, the only way to obtain the date when the message was received is to get Envelope of the message using IMAP and get the date from DateReceived property. Also, even if Received header itself is available, some of its fields may be missing.

Because TimeStampCollection object contains all the time stamps associated with the message, you can easily find out the full route of the message from its sender to its recipient, determine if there had been any delays during the delivery, etc.

Examples
This sample loads the message from .EML file and, for each of the time stamps, displays the information (if available) about the host which sent or relayed this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\TestMail.eml");
foreach (TimeStamp ts in msg.TimeStamps)
{
    Console.WriteLine(ts.From);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As New MailMessage
msg.LoadMessage("C:\Docs\TestMail.eml")
For Each ts As TimeStamp In msg.TimeStamps
    Console.WriteLine(ts.From)
Next
See Also

Reference

MailBee.Mime Namespace
MailMessageTimeStamps
MailBee.MimeTimeStamp


TimeStampCollection Methods

TimeStampCollection Methods

The TimeStampCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TimeStampCollection Class
MailBee.Mime Namespace


TimeStampCollection Properties

TimeStampCollection Properties

The TimeStampCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the TimeStamp object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

TimeStampCollection Class
MailBee.Mime Namespace


TimeStampCollection.Item Property

TimeStampCollectionItem Property
Gets the TimeStamp object at the specified zero-based index in the collection.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TimeStamp this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As TimeStamp
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the TimeStamp object in the collection.

Property Value

Type: TimeStamp
A TimeStamp object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

TimeStampCollection Class
MailBee.Mime Namespace


TnefExtractionOptions Enumeration

TnefExtractionOptions Enumeration
Defines the available flags affecting which items to extract from a TNEF container (winmail.dat).

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum TnefExtractionOptions
<FlagsAttribute>
Public Enumeration TnefExtractionOptions
Members
Member name | Value | Description
None | 0 | No additional options. If used with GetAttachmentsFromTnef, empty collection will be returned.
ExtractAttachments | 1 | Extract attachments from a TNEF container.
ExtractRtfBody | 2 | Extract RTF body from a TNEF container. MailBee will add the RTF body as "richbody.rtf" file to the returned collection (if the RTF body exists in the TNEF). If combined with ExtractAttachments flag, "richbody.rtf" will be the last element of the returned collection.
Remarks
To extract data from MS-TNEF (winmail.dat) attachments, use GetAttachmentsFromTnef(TnefExtractionOptions) method.
See Also

Reference

MailBee.Mime Namespace


VirtualMappingType Enumeration

VirtualMappingType Enumeration
Defines the available modes which specify how the virtual paths should be generated by GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method for inline attachments referenced in HTML body.

Namespace: MailBee.Mime
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum VirtualMappingType
Public Enumeration VirtualMappingType
Members
Member name | Value | Description
NonWeb | 0 | Virtual paths are not used, physical paths themselves are placed in URIs (e.g. <IMG SRC="C:\Inetpub\wwwroot\picture.gif">).
Static | 1 | Virtual paths are used instead of physical paths (e.g. <IMG SRC="http://www.domain.com/picture.gif">). The message files must be stored in a location visible from the web.
Dynamic | 2 | The virtual path must point to a downloader script. MailBee.NET will also supply message_id and file_id parameters in URI. The downloader script can use them to locate the file to be downloaded to the client. The message files can be stored in a location which can be accessed by the downloader script but is not directly visible from the web (for better security). See GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method documentation for more information.
Base64 | 3 | Virtual path is ignored, all embedded objects are base64 encoded within the HTML. Nothing is saved into a temporary location, no temporary folder is created. GetHtmlWithBase64EncodedRelatedFiles method uses this mode.
StaticInMemory | 4 | The virtual path must be a prefix. To make the resulting virtual path, MailBee will append a suffix ("1", "2", etc) to each inline attachment referenced in the body. No files will actually be saved (although SavedAs property will be set to the resulting virtual path), the application needs to save files itself. Useful if you need to host these inline attachments on external storage (e.g. Amazon S3). GetHtmlAndRelatedFilesInMemory(String) method uses this mode.
Remarks

These modes specify how physical paths to embedded pictures (and other inline attachments related in HTML body and saved into temporary location by GetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior) method) are mapped into URIs placed into SRC elements of corresponding HTML tags.

Note Note
URI is a synonym of an URL.
See Also

Reference

MailBee.Mime Namespace
MailMessageGetHtmlAndSaveRelatedFiles(String, VirtualMappingType, MessageFolderBehavior)


MailBee.Outlook Namespace

MailBee.Outlook Namespace

MailBee.Outlook namespace has two main classes: MsgConvert and PstReader.

MsgConvert class provides methods for converting between RFC822 files and streams (usual MIME mail messages in .EML format) and Outlook .MSG files and streams (the data format of Outlook's standalone e-mails).

MsgConvert class also has methods for reading .MSG data into MailBee.Mime.MailMessage objects and writing these objects into .MSG files and streams.

PstReader class can read .PST files (used by Outlook to store all the data), extract its folder structure and all individual items like messages, contacts, tasks and appointments. All items can be represented as MailBee.Mime.MailMessage objects.

MsgConvert and PstReader support attachments, ANSI and Unicode charsets, plain-text, HTML and RTF bodies.

Classes
 | Class | Description
Public class | MailBeeOutlookMsgBuildingException | The exception that is thrown when the OLE2 building error occurs (for instance, when it's not possible to create Outlook .MSG file from the source data).
Public class | MailBeeOutlookMsgException | An abstract parent for all exceptions which can be thrown during parsing OLE2 documents (like Outlook .MSG files).
Public class | MailBeeOutlookMsgNotFoundException | The exception that is thrown on an attempt to parse a file which is not OLE2 document (and thus not Outlook .MSG).
Public class | MailBeeOutlookMsgParsingException | The exception that is thrown when the OLE2 parsing error occurs (for instance, Outlook .MSG file has errors in its OLE2 structure).
Public class | MailBeePstException | An abstract parent for all exceptions which can be thrown during parsing .PST files.
Public class | MailBeePstNotFoundException | The exception that is thrown on an attempt to parse a file which is not .PST file.
Public class | MailBeePstParsingException | The exception that is thrown when a .PST parsing error occurs (for instance, Outlook .PST file has errors in its structure).
 | MsgConvert | Provides methods for parsing and converting Outlook .MSG files/streams (in OLE2 format) into MailMessage objects and files/streams in .EML format (RFC822 MIME), and for building .MSG files/streams from MailMessage objects and .EML files/streams.
Public class | PstActivity | Represents an Activity item.
Public class | PstAppointment | Represents an Appointment item.
Public class | PstContact | Represents a Contact item.
Public class | PstDistList | Represents a distribution list.
Public class | PstFolder | Represents a folder of .PST database folder tree.
Public class | PstFolderCollection | Provides properties and methods for examining the collection of PstFolder objects.
Public class | PstItem | Represents a PST item of unknown type.
Public class | PstItemCollection | Provides properties and methods for examining the collection of PstItem objects.
Public class | PstMessage | Represents a Message item.
 | PstReader | Provides methods for parsing Outlook .PST message database file into a collection of folders and items.
Public class | PstRss | Represents an RSS item.
Public class | PstTask | Represents a Task item.
Delegates
 | Delegate | Description
Public delegate | ByteToStringConversionHandler | Defines the signature of a method supplied by the application in order to get string from SINGLE bytes data when making MSG-to-EML conversion.
Public delegate | HtmlToRtfConversionHandler | Defines the signature of a method supplied by the application in order to get RTF text from HTML body when making EML-to-MSG conversion.
Enumerations
 | Enumeration | Description
Public enumeration | HtmlToRtfConversionMethod | Defines supported methods of HTML-to-RTF transformation to be performed during EML-to-MSG conversion.
Public enumeration | PstItemType | Defines types of PST objects.
Public enumeration | RtfInEmlStorageMethod | Defines supported methods of placing RTF body of the source .MSG message into resulting .EML message.


MailBeeOutlookMsgBuildingException Class

MailBeeOutlookMsgBuildingException Class
The exception that is thrown when the OLE2 building error occurs (for instance, when it's not possible to create Outlook .MSG file from the source data).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeeOutlookMsgException
MailBee.OutlookMailBeeOutlookMsgBuildingException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeOutlookMsgBuildingException : MailBeeOutlookMsgException
<SerializableAttribute>
Public Class MailBeeOutlookMsgBuildingException
    Inherits MailBeeOutlookMsgException

The MailBeeOutlookMsgBuildingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeOutlookMsgBuildingException | Initializes a new instance of the MailBeeOutlookMsgBuildingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Outlook Namespace


MailBeeOutlookMsgBuildingException Constructor

MailBeeOutlookMsgBuildingException Constructor
Initializes a new instance of the MailBeeOutlookMsgBuildingException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeOutlookMsgBuildingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeOutlookMsgBuildingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgBuildingException Methods

MailBeeOutlookMsgBuildingException Methods

The MailBeeOutlookMsgBuildingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgBuildingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgBuildingException Properties

MailBeeOutlookMsgBuildingException Properties

The MailBeeOutlookMsgBuildingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgBuildingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgBuildingException Events

MailBeeOutlookMsgBuildingException Events

The MailBeeOutlookMsgBuildingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgBuildingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgException Class

MailBeeOutlookMsgException Class
An abstract parent for all exceptions which can be thrown during parsing OLE2 documents (like Outlook .MSG files).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeeOutlookMsgException
MailBee.OutlookMailBeeOutlookMsgBuildingException
MailBee.OutlookMailBeeOutlookMsgNotFoundException
MailBee.OutlookMailBeeOutlookMsgParsingException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public abstract class MailBeeOutlookMsgException : MailBeeLocalException
<SerializableAttribute>
Public MustInherit Class MailBeeOutlookMsgException
    Inherits MailBeeLocalException

The MailBeeOutlookMsgException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeOutlookMsgException | Initializes a new instance of the MailBeeOutlookMsgException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Outlook Namespace


MailBeeOutlookMsgException Constructor

MailBeeOutlookMsgException Constructor
Initializes a new instance of the MailBeeOutlookMsgException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeOutlookMsgException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeOutlookMsgException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgException Methods

MailBeeOutlookMsgException Methods

The MailBeeOutlookMsgException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgException Properties

MailBeeOutlookMsgException Properties

The MailBeeOutlookMsgException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgException Events

MailBeeOutlookMsgException Events

The MailBeeOutlookMsgException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgNotFoundException Class

MailBeeOutlookMsgNotFoundException Class
The exception that is thrown on an attempt to parse a file which is not OLE2 document (and thus not Outlook .MSG).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeeOutlookMsgException
MailBee.OutlookMailBeeOutlookMsgNotFoundException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeOutlookMsgNotFoundException : MailBeeOutlookMsgException
<SerializableAttribute>
Public Class MailBeeOutlookMsgNotFoundException
    Inherits MailBeeOutlookMsgException

The MailBeeOutlookMsgNotFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeOutlookMsgNotFoundException | Initializes a new instance of the MailBeeOutlookMsgNotFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Outlook Namespace


MailBeeOutlookMsgNotFoundException Constructor

MailBeeOutlookMsgNotFoundException Constructor
Initializes a new instance of the MailBeeOutlookMsgNotFoundException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeOutlookMsgNotFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeOutlookMsgNotFoundException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgNotFoundException Methods

MailBeeOutlookMsgNotFoundException Methods

The MailBeeOutlookMsgNotFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgNotFoundException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgNotFoundException Properties

MailBeeOutlookMsgNotFoundException Properties

The MailBeeOutlookMsgNotFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgNotFoundException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgNotFoundException Events

MailBeeOutlookMsgNotFoundException Events

The MailBeeOutlookMsgNotFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgNotFoundException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgParsingException Class

MailBeeOutlookMsgParsingException Class
The exception that is thrown when the OLE2 parsing error occurs (for instance, Outlook .MSG file has errors in its OLE2 structure).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeeOutlookMsgException
MailBee.OutlookMailBeeOutlookMsgParsingException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeOutlookMsgParsingException : MailBeeOutlookMsgException
<SerializableAttribute>
Public Class MailBeeOutlookMsgParsingException
    Inherits MailBeeOutlookMsgException

The MailBeeOutlookMsgParsingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeOutlookMsgParsingException | Initializes a new instance of the MailBeeOutlookMsgParsingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Outlook Namespace


MailBeeOutlookMsgParsingException Constructor

MailBeeOutlookMsgParsingException Constructor
Initializes a new instance of the MailBeeOutlookMsgParsingException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeOutlookMsgParsingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeOutlookMsgParsingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgParsingException Methods

MailBeeOutlookMsgParsingException Methods

The MailBeeOutlookMsgParsingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgParsingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgParsingException Properties

MailBeeOutlookMsgParsingException Properties

The MailBeeOutlookMsgParsingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgParsingException Class
MailBee.Outlook Namespace


MailBeeOutlookMsgParsingException Events

MailBeeOutlookMsgParsingException Events

The MailBeeOutlookMsgParsingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeOutlookMsgParsingException Class
MailBee.Outlook Namespace


MailBeePstException Class

MailBeePstException Class
An abstract parent for all exceptions which can be thrown during parsing .PST files.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeePstException
MailBee.OutlookMailBeePstNotFoundException
MailBee.OutlookMailBeePstParsingException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeePstException : MailBeeLocalException
Public MustInherit Class MailBeePstException
    Inherits MailBeeLocalException

The MailBeePstException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePstException | Initializes a new instance of the MailBeePstException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Outlook Namespace


MailBeePstException Constructor

MailBeePstException Constructor
Initializes a new instance of the MailBeePstException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePstException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePstException Class
MailBee.Outlook Namespace


MailBeePstException Methods

MailBeePstException Methods

The MailBeePstException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstException Class
MailBee.Outlook Namespace


MailBeePstException Properties

MailBeePstException Properties

The MailBeePstException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstException Class
MailBee.Outlook Namespace


MailBeePstException Events

MailBeePstException Events

The MailBeePstException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstException Class
MailBee.Outlook Namespace


MailBeePstNotFoundException Class

MailBeePstNotFoundException Class
The exception that is thrown on an attempt to parse a file which is not .PST file.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeePstException
MailBee.OutlookMailBeePstNotFoundException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailBeePstNotFoundException : MailBeePstException
Public Class MailBeePstNotFoundException
    Inherits MailBeePstException

The MailBeePstNotFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePstNotFoundException | Initializes a new instance of the MailBeePstNotFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Outlook Namespace


MailBeePstNotFoundException Constructor

MailBeePstNotFoundException Constructor
Initializes a new instance of the MailBeePstNotFoundException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePstNotFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePstNotFoundException Class
MailBee.Outlook Namespace


MailBeePstNotFoundException Methods

MailBeePstNotFoundException Methods

The MailBeePstNotFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstNotFoundException Class
MailBee.Outlook Namespace


MailBeePstNotFoundException Properties

MailBeePstNotFoundException Properties

The MailBeePstNotFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstNotFoundException Class
MailBee.Outlook Namespace


MailBeePstNotFoundException Events

MailBeePstNotFoundException Events

The MailBeePstNotFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstNotFoundException Class
MailBee.Outlook Namespace


MailBeePstParsingException Class

MailBeePstParsingException Class
The exception that is thrown when a .PST parsing error occurs (for instance, Outlook .PST file has errors in its structure).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.OutlookMailBeePstException
MailBee.OutlookMailBeePstParsingException

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailBeePstParsingException : MailBeePstException
Public Class MailBeePstParsingException
    Inherits MailBeePstException

The MailBeePstParsingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePstParsingException | Initializes a new instance of the MailBeePstParsingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
"Unrecognised PST File version: 36." error means that you're trying to open .OST file produced by Outlook 2013 or higher. This format is not supported.
See Also

Reference

MailBee.Outlook Namespace


MailBeePstParsingException Constructor

MailBeePstParsingException Constructor
Initializes a new instance of the MailBeePstParsingException class

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePstParsingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePstParsingException Class
MailBee.Outlook Namespace


MailBeePstParsingException Methods

MailBeePstParsingException Methods

The MailBeePstParsingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstParsingException Class
MailBee.Outlook Namespace


MailBeePstParsingException Properties

MailBeePstParsingException Properties

The MailBeePstParsingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstParsingException Class
MailBee.Outlook Namespace


MailBeePstParsingException Events

MailBeePstParsingException Events

The MailBeePstParsingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePstParsingException Class
MailBee.Outlook Namespace


PST Item Classes

For ease of browsing the documentation, all classes representing individual types of PST items (like messages and contacts) are brought together in the group which is separate from other classes.

Send feedback to AfterLogic


PstActivity Class

PstActivity Class
Represents an Activity item.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstActivity

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstActivity : PstItem
Public Class PstActivity
    Inherits PstItem

The PstActivity type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets the PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstActivity Methods

PstActivity Methods

The PstActivity type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstActivity Class
MailBee.Outlook Namespace


PstActivity.GetAsMailMessage Method

PstActivityGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Activity" headers set.
Remarks
This method is useful if you want to work with this Activity item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers.
See Also

Reference

PstActivity Class
MailBee.Outlook Namespace


PstActivity Properties

PstActivity Properties

The PstActivity type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets the PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
See Also

Reference

PstActivity Class
MailBee.Outlook Namespace


PstActivity.PstFields Property

PstActivityPstFields Property
Gets the PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for Activity items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
LogType | String
LogStart | DateTime
LogDuration | Int32
LogEnd | DateTime
LogFlags | Int32
DocumentPrinted | Boolean
DocumentSaved | Boolean
DocumentRouted | Boolean
DocumentPosted | Boolean
LogTypeDesc | String

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Activity-" + PstFieldName headers. Example is "X-Activity-LogType". Each field value will be converted into a string.

See Also

Reference

PstActivity Class
MailBee.Outlook Namespace


PstActivity.PstID Property

PstActivityPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstActivity Class
MailBee.Outlook Namespace


PstActivity.PstType Property

PstActivityPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Activity.
See Also

Reference

PstActivity Class
MailBee.Outlook Namespace


PstAppointment Class

PstAppointment Class
Represents an Appointment item.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstMessage
MailBee.OutlookPstAppointment

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstAppointment : PstMessage
Public Class PstAppointment
    Inherits PstMessage

The PstAppointment type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstMessageGetAsMailMessage.)
Public method | GetAsMailMessage(Boolean) | Gets this PST object as MailMessage object with or without "X-Msg" headers. (Inherited from PstMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstMessagePstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstMessagePstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstMessagePstType.)
Public property | RtfInEmlMethod | Gets or sets whether RTF text body should be converted into attachment or body part of .EML message. (Inherited from PstMessage.)
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstAppointment Methods

PstAppointment Methods

The PstAppointment type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstMessageGetAsMailMessage.)
Public method | GetAsMailMessage(Boolean) | Gets this PST object as MailMessage object with or without "X-Msg" headers. (Inherited from PstMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstAppointment Class
MailBee.Outlook Namespace


PstAppointment.GetAsMailMessage Method

PstAppointmentGetAsMailMessage Method
Gets this PST object as MailMessage object.
Overload List
 | Name | Description
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstMessageGetAsMailMessage.)
Public method | GetAsMailMessage(Boolean) | Gets this PST object as MailMessage object with or without "X-Msg" headers. (Inherited from PstMessage.)
Top
See Also

Reference

PstAppointment Class
MailBee.Outlook Namespace


PstAppointment.GetAsMailMessage Method

PstAppointmentGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Appointment" headers set.
Remarks
This method is useful if you want to work with this Appointment item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers.
See Also

Reference

PstAppointment Class
GetAsMailMessage Overload
MailBee.Outlook Namespace


PstAppointment Properties

PstAppointment Properties

The PstAppointment type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstMessagePstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstMessagePstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstMessagePstType.)
Public property | RtfInEmlMethod | Gets or sets whether RTF text body should be converted into attachment or body part of .EML message. (Inherited from PstMessage.)
Top
See Also

Reference

PstAppointment Class
MailBee.Outlook Namespace


PstAppointment.PstFields Property

PstAppointmentPstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for Appointment items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
SendAsIcal | Boolean
ShowAsBusy | Boolean
Location | String
StartTime | DateTime
EndTime | DateTime
Duration | Int32
Color | Int32
SubType | Boolean
MeetingStatus | Int32
ResponseStatus | Int32
RecurrenceBase | DateTime
RecurrenceType | Int32
RecurrencePattern | String
Timezone | String
AllAttendees | String
ToAttendees | String
CCAttendees | String
OnlineMeeting | Boolean
NetMeetingType | Int32
NetMeetingServer | String
NetMeetingOrganizerAlias | String
NetMeetingAutostart | Boolean
ConferenceServerAllowExternal | Boolean
NetMeetingDocumentPathName | String
NetShowURL | String
ConferenceServerPassword | String
AppointmentCounterProposal | Boolean

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Appointment-" + PstFieldName headers. Example is "X-Appointment-StartTime". Each field value will be converted into a string.

See Also

Reference

PstAppointment Class
MailBee.Outlook Namespace


PstAppointment.PstID Property

PstAppointmentPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstAppointment Class
MailBee.Outlook Namespace


PstAppointment.PstType Property

PstAppointmentPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Appointment.
See Also

Reference

PstAppointment Class
MailBee.Outlook Namespace


PstContact Class

PstContact Class
Represents a Contact item.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstContact

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstContact : PstItem
Public Class PstContact
    Inherits PstItem

The PstContact type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstContact Methods

PstContact Methods

The PstContact type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstContact Class
MailBee.Outlook Namespace


PstContact.GetAsMailMessage Method

PstContactGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Contact" headers set.
Remarks
This method is useful if you want to work with this Contact item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers.
See Also

Reference

PstContact Class
MailBee.Outlook Namespace


PstContact Properties

PstContact Properties

The PstContact type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
See Also

Reference

PstContact Class
MailBee.Outlook Namespace


PstContact.PstFields Property

PstContactPstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for Contact items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
Account | String
CallbackTelephoneNumber | String
Generation | String
GivenName | String
GovernmentIdNumber | String
BusinessTelephoneNumber | String
HomeTelephoneNumber | String
Initials | String
Keyword | String
Language | String
Location | String
MhsCommonName | String
OrganizationalIdNumber | String
Surname | String
OriginalDisplayName | String
PostalAddress | String
CompanyName | String
Title | String
DepartmentName | String
OfficeLocation | String
PrimaryTelephoneNumber | String
Business2TelephoneNumber | String
MobileTelephoneNumber | String
RadioTelephoneNumber | String
CarTelephoneNumber | String
OtherTelephoneNumber | String
TransmittableDisplayName | String
PagerTelephoneNumber | String
PrimaryFaxNumber | String
BusinessFaxNumber | String
HomeFaxNumber | String
BusinessAddressCountry | String
BusinessAddressCity | String
BusinessAddressStateOrProvince | String
BusinessAddressStreet | String
BusinessPostalCode | String
BusinessPoBox | String
TelexNumber | String
IsdnNumber | String
AssistantTelephoneNumber | String
Home2TelephoneNumber | String
Assistant | String
Hobbies | String
MiddleName | String
DisplayNamePrefix | String
Profession | String
PreferredByName | String
SpouseName | String
ComputerNetworkName | String
CustomerId | String
TtytddPhoneNumber | String
FtpSite | String
ManagerName | String
Nickname | String
PersonalHomePage | String
BusinessHomePage | String
CompanyMainPhoneNumber | String
ChildrensNames | String
HomeAddressCity | String
HomeAddressCountry | String
HomeAddressPostalCode | String
HomeAddressStateOrProvince | String
HomeAddressStreet | String
HomeAddressPostOfficeBox | String
OtherAddressCity | String
OtherAddressCountry | String
OtherAddressPostalCode | String
OtherAddressStateOrProvince | String
OtherAddressStreet | String
OtherAddressPostOfficeBox | String
FileUnder | String
HomeAddress | String
WorkAddress | String
OtherAddress | String
PostalAddressId | String
Html | String
WorkAddressStreet | String
WorkAddressState | String
WorkAddressPostalCode | String
WorkAddressCountry | String
InstantMessagingAddress | String
Email1DisplayName | String
Email1AddressType | String
Email1EmailAddress | String
Email1OriginalDisplayName | String
Email1EmailType | String
Email2DisplayName | String
Email2AddressType | String
Email2EmailAddress | String
Email2OriginalDisplayName | String
Email3DisplayName | String
Email3AddressType | String
Email3EmailAddress | String
Email3OriginalDisplayName | String
Fax1AddressType | String
Fax1EmailAddress | String
Fax1OriginalDisplayName | String
Fax2AddressType | String
Fax2EmailAddress | String
Fax2OriginalDisplayName | String
Fax3AddressType | String
Fax3EmailAddress | String
Fax3OriginalDisplayName | String
Note | String

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Contact-" + PstFieldName headers. Example is "X-Contact-CallbackTelephoneNumber". Each field value will be converted into a string.

See Also

Reference

PstContact Class
MailBee.Outlook Namespace


PstContact.PstID Property

PstContactPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstContact Class
MailBee.Outlook Namespace


PstContact.PstType Property

PstContactPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Contact.
See Also

Reference

PstContact Class
MailBee.Outlook Namespace


PstDistList Class

PstDistList Class
Represents a distribution list.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstDistList

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstDistList : PstItem
Public Class PstDistList
    Inherits PstItem

The PstDistList type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMembers | Gets the DistList members.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DisplayName | Gets the Display Name of the distribution list.
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstDistList Methods

PstDistList Methods

The PstDistList type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMembers | Gets the DistList members.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList.GetAsMailMessage Method

PstDistListGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-DistList" headers set.
Remarks
This method is useful if you want to work with this DistList item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers. This method also stores all DistList members into BodyPlainText property, one entry per line.
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList.GetMembers Method

PstDistListGetMembers Method
Gets the DistList members.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection GetMembers()
Public Function GetMembers As EmailAddressCollection

Return Value

Type: EmailAddressCollection
The collection of all members of this distribution list.
Remarks
Each member includes its display name and e-mail address.
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList Properties

PstDistList Properties

The PstDistList type exposes the following members.

Properties
 | Name | Description
Public property | DisplayName | Gets the Display Name of the distribution list.
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList.DisplayName Property

PstDistListDisplayName Property
Gets the Display Name of the distribution list.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string DisplayName { get; }
Public ReadOnly Property DisplayName As String
    Get

Property Value

Type: String
The Display Name of the distribution list.
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList.PstFields Property

PstDistListPstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for DistList items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
DisplayName | String

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-DistList-" + PstFieldName headers. Example is "X-DistList-DisplayName". Each field value will be converted into a string.

See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList.PstID Property

PstDistListPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstDistList.PstType Property

PstDistListPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns DistList.
See Also

Reference

PstDistList Class
MailBee.Outlook Namespace


PstFolder Class

PstFolder Class
Represents a folder of .PST database folder tree.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstFolder

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstFolder
Public Class PstFolder

The PstFolder type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetPstSubFolders(Boolean) | Gets the list of sub-folders of the given folder.
Public method | GetPstSubFolders(Boolean, String) | Gets the list of sub-folders of the given folder with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Items | Gets the collection of all items in this folder which are not sub-folders.
Public property | Name | Gets the full name of the folder including parent folder names if any.
Public property | PstID | Gets the PST ID of this folder.
Public property | SafeName | Gets the safe full name (which can be created on the file system) of the folder including parent folder names if any.
Public property | SafeShortName | Gets the safe short name (which can be created on the file system) (without parent folder names if any) of the folder.
Public property | ShortName | Gets the short name (without parent folder names if any) of the folder.
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstFolder Methods

PstFolder Methods

The PstFolder type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetPstSubFolders(Boolean) | Gets the list of sub-folders of the given folder.
Public method | GetPstSubFolders(Boolean, String) | Gets the list of sub-folders of the given folder with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace


PstFolder.GetPstSubFolders Method

PstFolderGetPstSubFolders Method
Gets the list of sub-folders of the given folder.
Overload List
 | Name | Description
Public method | GetPstSubFolders(Boolean) | Gets the list of sub-folders of the given folder.
Public method | GetPstSubFolders(Boolean, String) | Gets the list of sub-folders of the given folder with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.
Top
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace


PstFolder.GetPstSubFolders Method (Boolean)

PstFolderGetPstSubFolders Method (Boolean)
Gets the list of sub-folders of the given folder.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstFolderCollection GetPstSubFolders(
    bool includeSubFolders
)
Public Function GetPstSubFolders (
    includeSubFolders As Boolean
) As PstFolderCollection

Parameters

includeSubFolders
Type: SystemBoolean
If true, subfolders from ALL levels will be included in the resulting list; otherwise, only direct child folders of the current level.

Return Value

Type: PstFolderCollection
A PstFolderCollection object containing the sub-folders.
Remarks
The delimiter which is used to separate levels of folder names is: "\".
See Also

Reference

PstFolder Class
GetPstSubFolders Overload
MailBee.Outlook Namespace


PstFolder.GetPstSubFolders Method (Boolean, String)

PstFolderGetPstSubFolders Method (Boolean, String)
Gets the list of sub-folders of the given folder with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstFolderCollection GetPstSubFolders(
    bool includeSubFolders,
    string delimiter
)
Public Function GetPstSubFolders (
    includeSubFolders As Boolean,
    delimiter As String
) As PstFolderCollection

Parameters

includeSubFolders
Type: SystemBoolean
If true, subfolders from ALL levels will be included in the resulting list; otherwise, only direct child folders of the current level.
delimiter
Type: SystemString
The string used to separate levels of hierarchy of folder names.

Return Value

Type: PstFolderCollection
A PstFolderCollection object containing the sub-folders.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | delimiter is a null reference (Nothing in Visual Basic).
See Also

Reference

PstFolder Class
GetPstSubFolders Overload
MailBee.Outlook Namespace


PstFolder Properties

PstFolder Properties

The PstFolder type exposes the following members.

Properties
 | Name | Description
Public property | Items | Gets the collection of all items in this folder which are not sub-folders.
Public property | Name | Gets the full name of the folder including parent folder names if any.
Public property | PstID | Gets the PST ID of this folder.
Public property | SafeName | Gets the safe full name (which can be created on the file system) of the folder including parent folder names if any.
Public property | SafeShortName | Gets the safe short name (which can be created on the file system) (without parent folder names if any) of the folder.
Public property | ShortName | Gets the short name (without parent folder names if any) of the folder.
Top
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace


PstFolder.Items Property

PstFolderItems Property
Gets the collection of all items in this folder which are not sub-folders.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstItemCollection Items { get; }
Public ReadOnly Property Items As PstItemCollection
    Get

Property Value

Type: PstItemCollection
A PstItemCollection object containing the non-folder items in this folder.
Remarks

This collection includes elements of typed derived from PstItem. This includes PstMessage, PstContact, PstAppointment, etc. Sub-folders of this folders are not included in this list.

To get sub-folders rather than other items like messages, use GetPstSubFolders(Boolean) method.

See Also

Reference

PstFolder Class
MailBee.Outlook Namespace


PstFolder.Name Property

PstFolderName Property
Gets the full name of the folder including parent folder names if any.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; }
Public ReadOnly Property Name As String
    Get

Property Value

Type: String
The string containing the full name of the folder including parent folder names if any.
Remarks
The delimiter which is used to separate levels of folder names is: "\".
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace
PstFolderShortName
PstFolderSafeName


PstFolder.PstID Property

PstFolderPstID Property
Gets the PST ID of this folder.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int PstID { get; }
Public ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this folder in the .PST file.
Remarks
You can use GetFolderByID(Int32) method to directly access this item via ID.
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace


PstFolder.SafeName Property

PstFolderSafeName Property
Gets the safe full name (which can be created on the file system) of the folder including parent folder names if any.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SafeName { get; }
Public ReadOnly Property SafeName As String
    Get

Property Value

Type: String
The string containing the full name of the folder including parent folder names if any.
Remarks
The delimiter which is used to separate folder levels is: "\". All characters which are not valid on the file system are replaced with "_".
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace
PstFolderShortName
PstFolderName


PstFolder.SafeShortName Property

PstFolderSafeShortName Property
Gets the safe short name (which can be created on the file system) (without parent folder names if any) of the folder.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SafeShortName { get; }
Public ReadOnly Property SafeShortName As String
    Get

Property Value

Type: String
The string containing the folder's short name without any delimiters or parent folder names.
Remarks
If the folder is the top level folder, its short name is equal to its full name. All characters which are not valid on the file system are replaced with "_".
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace
PstFolderName
PstFolderSafeShortName


PstFolder.ShortName Property

PstFolderShortName Property
Gets the short name (without parent folder names if any) of the folder.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ShortName { get; }
Public ReadOnly Property ShortName As String
    Get

Property Value

Type: String
The string containing the folder's short name without any delimiters or parent folder names.
Remarks
If the folder is a top level folder, its short name is equal to its full name.
See Also

Reference

PstFolder Class
MailBee.Outlook Namespace
PstFolderName
PstFolderSafeShortName


PstFolderCollection Class

PstFolderCollection Class
Provides properties and methods for examining the collection of PstFolder objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.OutlookPstFolderCollection

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstFolderCollection : CollectionBase
Public Class PstFolderCollection
    Inherits CollectionBase

The PstFolderCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the PstFolder object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.Outlook Namespace


PstFolderCollection Methods

PstFolderCollection Methods

The PstFolderCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstFolderCollection Class
MailBee.Outlook Namespace


PstFolderCollection Properties

PstFolderCollection Properties

The PstFolderCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the PstFolder object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

PstFolderCollection Class
MailBee.Outlook Namespace


PstFolderCollection.Item Property

PstFolderCollectionItem Property
Gets or sets the PstFolder object at the specified zero-based index in the collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstFolder this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As PstFolder
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index number of the element in the collection.

Property Value

Type: PstFolder
An PstFolder object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

PstFolderCollection Class
MailBee.Outlook Namespace


PstItem Class

PstItem Class
Represents a PST item of unknown type.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
More...

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstItem
Public Class PstItem

The PstItem type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | MakeStringSafeForFileName | Replaces all those characters in the supplied string which cannot be used in filenames, with "_" symbols.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item.
Public property | PstFields | Gets PST object fields collection.
Public property | PstID | Gets the PST ID of this item.
Public property | PstType | Gets the PST type of this object.
Top
Remarks
.PST files files can contain PST object of different types. Well-defined types (like PstContact) are listed in PstItemType enumeration. For them, MailBee defines classes derived from PstItem. If it encounters an item which does not correspond to any of the predefined types, such item will have PstItem type.
See Also

Reference

MailBee.Outlook Namespace
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstActivity
MailBee.OutlookPstContact
MailBee.OutlookPstDistList
MailBee.OutlookPstMessage
MailBee.OutlookPstRss
MailBee.OutlookPstTask


PstItem Methods

PstItem Methods

The PstItem type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | MakeStringSafeForFileName | Replaces all those characters in the supplied string which cannot be used in filenames, with "_" symbols.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem.GetAsMailMessage Method

PstItemGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual MailMessage GetAsMailMessage()
Public Overridable Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Pst" headers set.
Remarks
This method is useful if you want to work with this item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers.
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem.MakeStringSafeForFileName Method

PstItemMakeStringSafeForFileName Method
Replaces all those characters in the supplied string which cannot be used in filenames, with "_" symbols.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string MakeStringSafeForFileName(
    string str
)
Public Shared Function MakeStringSafeForFileName (
    str As String
) As String

Parameters

str
Type: SystemString
A string which may contain symbols not allowed in filenames.

Return Value

Type: String
A string safe to use as a filename, or an empty string if str is empty.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | str is a null reference (Nothing in Visual Basic).
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem Properties

PstItem Properties

The PstItem type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item.
Public property | PstFields | Gets PST object fields collection.
Public property | PstID | Gets the PST ID of this item.
Public property | PstType | Gets the PST type of this object.
Top
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem.Keywords Property

PstItemKeywords Property
Gets ";"-separated list of keywords associated with this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Keywords { get; }
Public ReadOnly Property Keywords As String
    Get

Property Value

Type: String
A ";"-separated list of keywords associated with this item, or an empty string if no keywords are defined or can be extracted.
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem.PstFields Property

PstItemPstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual Hashtable PstFields { get; }
Public Overridable ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys which are not specific to items of concrete PST types (like PstContact). Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Key Name | Type
MessageClass | String
DisplayName | String
AddrType | String
EmailAddress | String
Comment | String
CreationTime | DateTime
LastModificationTime | DateTime

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Pst-" + PstFieldName headers. Example is "X-Pst-MessageClass". Each field value will be converted into a string.

See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem.PstID Property

PstItemPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual int PstID { get; }
Public Overridable ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItem.PstType Property

PstItemPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual PstItemType PstType { get; }
Public Overridable ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Other if this item is exactly an object of PstItem class. If this item is an object of a class derived from PstItem, the return value is PstItemType value which corresponds to that class.
See Also

Reference

PstItem Class
MailBee.Outlook Namespace


PstItemCollection Class

PstItemCollection Class
Provides properties and methods for examining the collection of PstItem objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.OutlookPstItemCollection

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstItemCollection : CollectionBase
Public Class PstItemCollection
    Inherits CollectionBase

The PstItemCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Gets the enumerator for the collection.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets approximate number of emails.
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the PstItemCollection object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

MailBee.Outlook Namespace


PstItemCollection Methods

PstItemCollection Methods

The PstItemCollection type exposes the following members.

Methods
 | Name | Description
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Gets the enumerator for the collection.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstItemCollection Class
MailBee.Outlook Namespace


PstItemCollection.GetEnumerator Method

PstItemCollectionGetEnumerator Method
Gets the enumerator for the collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IEnumerator GetEnumerator()
Public Function GetEnumerator As IEnumerator

Return Value

Type: IEnumerator
A reference to the enumerator.
See Also

Reference

PstItemCollection Class
MailBee.Outlook Namespace


PstItemCollection Properties

PstItemCollection Properties

The PstItemCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets approximate number of emails.
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets the PstItemCollection object at the specified zero-based index in the collection.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

PstItemCollection Class
MailBee.Outlook Namespace


PstItemCollection.Count Property

PstItemCollectionCount Property
Gets approximate number of emails.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Count { get; }
Public ReadOnly Property Count As Integer
    Get

Property Value

Type: Int32
Remarks
Use foreach statement for full-collection running over.
See Also

Reference

PstItemCollection Class
MailBee.Outlook Namespace


PstItemCollection.Item Property

PstItemCollectionItem Property
Gets the PstItemCollection object at the specified zero-based index in the collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstItem this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As PstItem
    Get

Parameters

index
Type: SystemInt32
The zero-based index number of the element in the collection.

Property Value

Type: PstItem
An PstItemCollection object having the specified zero-based index in the collection.
Exceptions
Exception | Condition
ArgumentOutOfRangeException | The specified index does not exist.
See Also

Reference

PstItemCollection Class
MailBee.Outlook Namespace


PstMessage Class

PstMessage Class
Represents a Message item.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstMessage
MailBee.OutlookPstAppointment

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstMessage : PstItem
Public Class PstMessage
    Inherits PstItem

The PstMessage type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetAsMailMessage(Boolean) | Gets this PST object as MailMessage object with or without "X-Msg" headers.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Public property | RtfInEmlMethod | Gets or sets whether RTF text body should be converted into attachment or body part of .EML message.
Top
Remarks

Message item corresponds to a MailMessage.

Use PstReader class to parse .PST files and extract data from them.

See Also

Reference

MailBee.Outlook Namespace


PstMessage Methods

PstMessage Methods

The PstMessage type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetAsMailMessage(Boolean) | Gets this PST object as MailMessage object with or without "X-Msg" headers.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstMessage.GetAsMailMessage Method

PstMessageGetAsMailMessage Method
Gets this PST object as MailMessage object.
Overload List
 | Name | Description
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetAsMailMessage(Boolean) | Gets this PST object as MailMessage object with or without "X-Msg" headers.
Top
See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstMessage.GetAsMailMessage Method

PstMessageGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Msg" headers set.
Remarks
This method is useful if you want to work with this Message item as a MailMessage object and have all the special message properties (which are stored in .PST file) be available as message headers. If you want to work with these values separately and do not include them into the message headers, use PstFields property to access these values and GetAsMailMessage(Boolean) overload to get the mail message without special headers.
See Also

Reference

PstMessage Class
GetAsMailMessage Overload
MailBee.Outlook Namespace


PstMessage.GetAsMailMessage Method (Boolean)

PstMessageGetAsMailMessage Method (Boolean)
Gets this PST object as MailMessage object with or without "X-Msg" headers.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage GetAsMailMessage(
    bool includeHeaders
)
Public Function GetAsMailMessage (
    includeHeaders As Boolean
) As MailMessage

Parameters

includeHeaders
Type: SystemBoolean
If true, "X-Msg" headers will be included in the resulting message; otherwise, not.

Return Value

Type: MailMessage
A MailMessage object representing an e-mail exracted from .PST file.
Remarks

"X-Msg" headers are PstFields values converted into strings and added to the message as "X-Msg-" + PstFieldName headers. You can access PstFields separately and specify includeHeaders as false if you do not want to add these values as the message headers (useful if you want to keep the message in its original form).

Using PstFields instead of accessing "X-Msg" headers has another benefit. "X-Msg" headers are already converted to strings while PstFields values keep their original data types. The only reason to have "X-Msg" headers in the message is if you want to transfer the message to another system or save it into a file/stream/.XML and process the message later.

See Also

Reference

PstMessage Class
GetAsMailMessage Overload
MailBee.Outlook Namespace


PstMessage Properties

PstMessage Properties

The PstMessage type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Public property | RtfInEmlMethod | Gets or sets whether RTF text body should be converted into attachment or body part of .EML message.
Top
See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstMessage.PstFields Property

PstMessagePstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for Message items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
MessageClass | String
ClientSubmitTime | DateTime
ReceivedByName | String
SentRepresentingName | String
SentRepresentingAddressType | String
SentRepresentingEmailAddress | String
ConversationTopic | String
ReceivedByAddressType | String
ReceivedByAddress | String
TransportMessageHeaders | String
Read | Boolean
Unmodified | Boolean
Submitted | Boolean
Unsent | Boolean
FromMe | Boolean
Associated | Boolean
Resent | Boolean
AcknowledgementMode | Int32
OriginatorDeliveryReportRequested | Boolean
ReadReceiptRequested | Boolean
RecipientReassignmentProhibited | Boolean
OriginalSensitivity | String
Sensitivity | Int32
RcvdRepresentingName | String
OriginalSubject | String
ReplyRecipientNames | String
MessageToMe | Boolean
MessageCcMe | Boolean
MessageRecipMe | String
ResponseRequested | Boolean
SentRepresentingAddrtype | String
OriginalDisplayBcc | String
OriginalDisplayCc | String
OriginalDisplayTo | String
RcvdRepresentingAddrtype | String
RcvdRepresentingEmailAddress | String
NonReceiptNotificationRequested | Boolean
OriginatorNonDeliveryReportRequested | Boolean
RecipientType | Int32
ReplyRequested | Boolean
SenderName | String
SenderAddrtype | String
SenderEmailAddress | String
MessageSize | Int64
AttachSize | Int32
AttachNum | Int32
InternetArticleNumber | Int32
URLCompNamePostfix | Int32
ObjectType | Int32
DeleteAfterSubmit | Boolean
Responsibility | Boolean
RtfInSync | Boolean
UrlCompNameSet | Boolean
DisplayBcc | String
DisplayCc | String
DisplayTo | String
MessageDeliveryTime | DateTime
RtfSyncBodyCrc | Int32
RtfSyncBodyCount | Int32
RtfSyncBodyTag | String
RtfSyncPrefixCount | Int32
RtfSyncTrailingCount | Int32
InternetMessageId | String
InReplyToId | String
ReturnPath | String
IconIndex | Int32
ActionFlag | Int32
ActionDate | DateTime
DisableFullFidelity | Boolean
URLCompName | String
AttrHidden | Boolean
AttrSystem | Boolean
AttrReadonly | Boolean
TaskStartDate | DateTime
TaskDueDate | DateTime
Flagged | Boolean
HasForwarded | Boolean
HasReplied | Boolean

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Msg-" + PstFieldName headers. Example is "X-Msg-MessageToMe". Each field value will be converted into a string.

See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstMessage.PstID Property

PstMessagePstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstMessage.PstType Property

PstMessagePstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Message.
See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstMessage.RtfInEmlMethod Property

PstMessageRtfInEmlMethod Property
Gets or sets whether RTF text body should be converted into attachment or body part of .EML message.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RtfInEmlStorageMethod RtfInEmlMethod { get; set; }
Public Property RtfInEmlMethod As RtfInEmlStorageMethod
    Get
    Set

Property Value

Type: RtfInEmlStorageMethod
The default value is None which means that rtf part will not be added to .EML message.
Remarks
If property assigned to AsAttachment, RTF (rich-text format) body of message is converted into .RTF attachment named "richbody.rtf" which is added to the resulting .EML message into Attachments collection. If you, however, need this body to be added to BodyParts collection, where plain-text and HTML bodies usually reside, set this property value to AsBodyPart before making the conversion. This is useful if you need to get the contents of the RTF body as a string (for instance, if you assign its value to Rtf property to display it in the RichTextBox control).
See Also

Reference

PstMessage Class
MailBee.Outlook Namespace


PstRss Class

PstRss Class
Represents an RSS item.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstRss

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstRss : PstItem
Public Class PstRss
    Inherits PstItem

The PstRss type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstRss Methods

PstRss Methods

The PstRss type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstRss Class
MailBee.Outlook Namespace


PstRss.GetAsMailMessage Method

PstRssGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Rss" headers set.
Remarks
This method is useful if you want to work with this RSS item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers.
See Also

Reference

PstRss Class
MailBee.Outlook Namespace


PstRss Properties

PstRss Properties

The PstRss type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
See Also

Reference

PstRss Class
MailBee.Outlook Namespace


PstRss.PstFields Property

PstRssPstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for RSS items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
PostRssChannel | String
PostRssChannelLink | String
PostRssItemLink | String
PostRssItemHash | Int32
PostRssItemGuid | String
PostRssItemXml | String
PostRssSubscription | String

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Rss-" + PstFieldName headers. Example is "X-Rss-PostRssChannel". Each field value will be converted into a string.

See Also

Reference

PstRss Class
MailBee.Outlook Namespace


PstRss.PstID Property

PstRssPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstRss Class
MailBee.Outlook Namespace


PstRss.PstType Property

PstRssPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Rss.
See Also

Reference

PstRss Class
MailBee.Outlook Namespace


PstTask Class

PstTask Class
Represents a Task item.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstItem
MailBee.OutlookPstTask

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstTask : PstItem
Public Class PstTask
    Inherits PstItem

The PstTask type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
Remarks
Use PstReader class to parse .PST files and extract data from them.
See Also

Reference

MailBee.Outlook Namespace


PstTask Methods

PstTask Methods

The PstTask type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAsMailMessage | Gets this PST object as MailMessage object. (Overrides PstItemGetAsMailMessage.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstTask Class
MailBee.Outlook Namespace


PstTask.GetAsMailMessage Method

PstTaskGetAsMailMessage Method
Gets this PST object as MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override MailMessage GetAsMailMessage()
Public Overrides Function GetAsMailMessage As MailMessage

Return Value

Type: MailMessage
A MailMessage object with "X-Task" headers set.
Remarks
This method is useful if you want to work with this Task item as a MailMessage object (for instance, if you want to save it into an .EML file). This method produces an empty mail message and adds all the PstFields as the message headers.
See Also

Reference

PstTask Class
MailBee.Outlook Namespace


PstTask Properties

PstTask Properties

The PstTask type exposes the following members.

Properties
 | Name | Description
Public property | Keywords | Gets ";"-separated list of keywords associated with this item. (Inherited from PstItem.)
Public property | PstFields | Gets PST object fields collection. (Overrides PstItemPstFields.)
Public property | PstID | Gets the PST ID of this item. (Overrides PstItemPstID.)
Public property | PstType | Gets the PST type of this object. (Overrides PstItemPstType.)
Top
See Also

Reference

PstTask Class
MailBee.Outlook Namespace


PstTask.PstFields Property

PstTaskPstFields Property
Gets PST object fields collection.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override Hashtable PstFields { get; }
Public Overrides ReadOnly Property PstFields As Hashtable
    Get

Property Value

Type: Hashtable
Remarks

The below are PST fields keys for Task items. Each key represents a particular property of this PST item. Most values are optional so that you need to check if the particular key exists with ContainsKey(Object) method (Hashtable.ContainsKey).

Name | Type
TaskStatus | Int32
PercentComplete | Double
TeamTask | Boolean
TaskDateCompleted | DateTime
TaskActualEffort | Int32
TaskEstimatedEffort | Int32
TaskVersion | Int32
TaskComplete | Boolean
TaskOwner | String
TaskAssigner | String
TaskLastUser | String
TaskOrdinal | Int32
TaskFRecurring | Boolean
TaskRole | String
TaskOwnership | Int32
AcceptanceState | Int32

When you get this PST object as MailMessage using GetAsMailMessage method, these fields will be added to the resulting message as "X-Task-" + PstFieldName headers. Example is "X-Task-TaskStatus". Each field value will be converted into a string.

See Also

Reference

PstTask Class
MailBee.Outlook Namespace


PstTask.PstID Property

PstTaskPstID Property
Gets the PST ID of this item.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override int PstID { get; }
Public Overrides ReadOnly Property PstID As Integer
    Get

Property Value

Type: Int32
The integer value which uniquely identifies this item in the .PST file.
Remarks
You can use GetItemByID(Int32) method to directly access this item via ID.
See Also

Reference

PstTask Class
MailBee.Outlook Namespace


PstTask.PstType Property

PstTaskPstType Property
Gets the PST type of this object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public override PstItemType PstType { get; }
Public Overrides ReadOnly Property PstType As PstItemType
    Get

Property Value

Type: PstItemType
Returns Task.
See Also

Reference

PstTask Class
MailBee.Outlook Namespace


ByteToStringConversionHandler Delegate

ByteToStringConversionHandler Delegate
Defines the signature of a method supplied by the application in order to get string from SINGLE bytes data when making MSG-to-EML conversion.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate string ByteToStringConversionHandler(
    byte[] data
)
Public Delegate Function ByteToStringConversionHandler (
    data As Byte()
) As String

Parameters

data
Type: SystemByte
A byte array for conversion to string.

Return Value

Type: String
A string after conversion from bytes with user-defined encoding.
See Also

Reference

MailBee.Outlook Namespace


HtmlToRtfConversionHandler Delegate

HtmlToRtfConversionHandler Delegate
Defines the signature of a method supplied by the application in order to get RTF text from HTML body when making EML-to-MSG conversion.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate string HtmlToRtfConversionHandler(
    MailMessage sourceMsg,
    string sourceHtml
)
Public Delegate Function HtmlToRtfConversionHandler (
    sourceMsg As MailMessage,
    sourceHtml As String
) As String

Parameters

sourceMsg
Type: MailBee.MimeMailMessage
The MailMessage object for which the converter is executed.
sourceHtml
Type: SystemString
The HTML text for conversion.

Return Value

Type: String
A string with RTF text.
Remarks

If you decided to use custom HTML-to-RTF conversion in your application (see HtmlToRtfConversionMethod topic for details), then your application must implement a method with HtmlToRtfConversionHandler signature which deals with sourceHtml string, converts its contents into RTF and returns it to MailBee. You can also use sourceMsg object if you need other information from the source .EML message. You can also modify that message (for instance, if your process of HTML-to-RTF conversion also implies changing the message like adding or removing attachments or whatever). All your changes will take effect on the resulting .MSG message.

To let MailBee know which HtmlToRtfConversionHandler delegate to execute, use OnHtmlToRtfConversion property.

Note Note
Using custom HTML-to-RTF conversion is an advanced topic which assumes you have a tool (such as third-party component) which can perform such a conversion with a very high quality (because MailBee already provides basic-level HTML-to-RTF conversion). Also, it assumes you actually need RTF body in .MSG message and HTML body is not enough for your case. Most Outlook versions can open .MSG with HTML (and no RTF) just fine.
See Also

Reference

MailBee.Outlook Namespace
MailBee.OutlookHtmlToRtfConversionMethod


HtmlToRtfConversionMethod Enumeration

HtmlToRtfConversionMethod Enumeration
Defines supported methods of HTML-to-RTF transformation to be performed during EML-to-MSG conversion.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum HtmlToRtfConversionMethod
Public Enumeration HtmlToRtfConversionMethod
Members
Member name | Value | Description
None | 0 | Do not use HTML-to-RTF conversion. The resulting .MSG will not contain Rich-Text-Format part. Outlook will show HTML part (if available) or plain-text part.
Internal | 1 | Internal converter is used for HTML-to-RTF conversion. It provides only basic level of transformation so most advanced HTML formatting may be lost in the resulting RTF. Not supported in .NET Core and UWP.
UseDelegate | 2 | Use the application-supplied OnHtmlToRtfConversion callback function to perform HTML-to-RTF conversion. You can also use this method when you need to create RTF body even for .EML which does not have HTML body part. The callback will be called for any .EML source, regardless if it actually has HTML part or not.
Remarks

.MSG files may have up to 3 alternative versions of the text body: plain-text, HTML, RTF (Rich-Text-format). By default, RTF body is displayed if present. However, .EML messages do not have RTF body. If, for some reason, you need to generate .MSG file with RTF body (HTML in .MSG is not enough for your purpose), the conversion between HTML and RTF must be performed. Such conversion is very complex because HTML and RTF formats are very different and both have very sophisticated formatting mechanisms, so it's not practically possible to match all the features of one format with another. MailBee provides only basic level of such conversions. If you, however, have a tool which is capable of making a better HTML-to-RTF conversion, you can use it with MailBee.

You can specify any of the values defined by HtmlToRtfConversionMethod type through HtmlToRtfMethod property.

OnHtmlToRtfConversion property allows you to specify the handler for performing custom HTML-to-RTF conversions.

See Also

Reference

MailBee.Outlook Namespace
MailBee.OutlookHtmlToRtfConversionHandler


MsgConvert Class

MsgConvert Class
Provides methods for parsing and converting Outlook .MSG files/streams (in OLE2 format) into MailMessage objects and files/streams in .EML format (RFC822 MIME), and for building .MSG files/streams from MailMessage objects and .EML files/streams.
Inheritance Hierarchy
SystemObject
MailBee.OutlookMsgConvert

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MsgConvert
Public Class MsgConvert

The MsgConvert type exposes the following members.

Constructors
 | Name | Description
Public method | MsgConvert | Creates an instance of MsgConvert class.
Public method | MsgConvert(String) | Creates and unlocks an instance of MsgConvert class.
Top
Methods
 | Name | Description
Public method | EmlToMsg(Stream, Stream) | Converts .EML data (in RFC822 text format) into a stream in Outlook .MSG (OLE2) format with 8-bit encoding.
 | EmlToMsg(String, String) | Converts .EML data (in RFC822 text format) into a file in Outlook .MSG (OLE2) format with 8-bit encoding.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | MailMessageToMsg(MailMessage, Stream) | Saves the specified MailMessage into a stream in Outlook .MSG (OLE2) format.
Public method | MailMessageToMsg(MailMessage, String) | Saves the specified MailMessage as Outlook .MSG file.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | MsgToEml(Stream, Stream) | Converts Outlook .MSG data (in OLE2 binary format) into .EML data (in RFC822 MIME format).
 | MsgToEml(String, String) | Converts Outlook .MSG file (in OLE2 binary format) into .EML file (in RFC822 MIME format).
 | MsgToMailMessage(Stream) | Parses Outlook .MSG data stream into MailMessage object.
Public method | MsgToMailMessage(String) | Parses Outlook .MSG file into MailMessage object.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | HtmlToRtfMethod | Gets or sets which HTML-to-RTF conversion method to use when making .MSG out of .EML source.
 | LicenseKey | Obsolete. Assigns the license key.
Public property | MsgAsDraft | Gets or sets whether the resulting .MSG message should be saved as "Draft" (editable) or "Sent" (read-only).
Public property | MsgAsUnicode | Gets or sets whether string values during .EML-to-.MSG transformation will be saved as Unicode (allows using international characters).
Public property | MsgIsFromMe | Gets or sets whether MSGFLAG_FROMME flag will set in the resuling .MSG message.
Public property | OnByteToStringConversion | Gets or sets the application-supplied callback MailBee will execute in order to convert bytes to string when making .EML from .MSG source.
Public property | OnHtmlToRtfConversion | Gets or sets the application-supplied callback MailBee will execute in order to convert HTML-to-RTF when making .MSG out of .EML source.
Public property | PreferAddressesFromInternetHeaders | Gets or sets whether From/To/CC/BCC addresses must be loaded from Internet headers of the .MSG message.
Public property | PreferRtfBodyToHtml | Gets or sets whether the HTML body of the resulting .EML should be taken from RTF part (instead of HTML part) of the source .MSG message, if it has both RTF and HTML part.
 | RtfInEmlMethod | Gets or sets if RTF text body from .MSG message should be added as an attachment or as a body part into the resulting .EML message, or not added at all.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
Remarks
You can perform the following operations using this class:
  • Convert a .EML (MIME) source from a file, stream or MailMessage object into Outlook .MSG stream or file
  • Convert an Outlook .MSG file or stream into MailMessage object or .EML (MIME) file or stream
  • Select whether to use ANSI or Unicode encoding for produced Outlook .MSG data
  • Save Outlook .MSG data as Draft or read-only items
  • Perform simple conversion of HTML into RTF when converting .EML into .MSG, or use an external high-quality HTML-to-RTF converter supplied by your application
  • Select whether (and how) to store RTF data in the .EML output when converting .MSG data into .EML data
  • Extract HTML body from .MSG source during .MSG to .EML conversion (if the source contains such body)

Prior to creating instances of this class, the correct license key must be set. See MailBee.Global.LicenseKey property for details.

Note Note
This class can only deal with OLE2 .MSG files. XML mail messages (can be created by Outlook 2007 and higher) are not supported.
Examples
This sample converts .MSG file into MailMessage object and then saves the resulting converted message to .EML file. It's assumed MailBee.Global.LicenseKey is already assigned (for instance, in app.config or web.config file).
Note Note
This sample shows how to use streams and MailMessage objects within the conversion (this also allows you to modify the resulting mail message prior to saving it into a file. If you only need to convert .MSG file into .EML (or vice versa), you can simply use MsgToEml(String, String) or EmlToMsg(String, String) methods.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System.IO;
using MailBee.Outlook;
using MailBee.Mime;

// The actual code (put it into a method of your class).
FileStream fs = new FileStream(@"C:\Mail\test.msg", FileMode.Open);
MsgConvert conv = new MsgConvert();
MailMessage msg = conv.MsgToMailMessage(fs);
fs.Close();
msg.SaveMessage(@"C:\Mail\test.eml");
' To use the code below, import these namespaces at the top of your code.
Imports System.IO
Imports MailBee.Outlook
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim fs As FileStream = New FileStream("C:\Mail\test.msg", FileMode.Open)
Dim conv As MsgConvert = New MsgConvert
Dim msg As MailMessage = conv.MsgToMailMessage(fs)
fs.Close()
msg.SaveMessage("C:\Mail\test.eml")
See Also

Reference

MailBee.Outlook Namespace


MsgConvert Constructor

MsgConvert Constructor
Creates an instance of MsgConvert class.
Overload List
 | Name | Description
Public method | MsgConvert | Creates an instance of MsgConvert class.
Public method | MsgConvert(String) | Creates and unlocks an instance of MsgConvert class.
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert Constructor

MsgConvert Constructor
Creates an instance of MsgConvert class.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MsgConvert()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Outlook Converter not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

MsgConvert Class
MsgConvert Overload
MailBee.Outlook Namespace


MsgConvert Constructor (String)

MsgConvert Constructor (String)
Creates and unlocks an instance of MsgConvert class.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MsgConvert(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Outlook Converter not licensed and the supplied license key is invalid.
See Also

Reference

MsgConvert Class
MsgConvert Overload
MailBee.Outlook Namespace


MsgConvert Methods

MsgConvert Methods

The MsgConvert type exposes the following members.

Methods
 | Name | Description
Public method | EmlToMsg(Stream, Stream) | Converts .EML data (in RFC822 text format) into a stream in Outlook .MSG (OLE2) format with 8-bit encoding.
 | EmlToMsg(String, String) | Converts .EML data (in RFC822 text format) into a file in Outlook .MSG (OLE2) format with 8-bit encoding.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | MailMessageToMsg(MailMessage, Stream) | Saves the specified MailMessage into a stream in Outlook .MSG (OLE2) format.
Public method | MailMessageToMsg(MailMessage, String) | Saves the specified MailMessage as Outlook .MSG file.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | MsgToEml(Stream, Stream) | Converts Outlook .MSG data (in OLE2 binary format) into .EML data (in RFC822 MIME format).
 | MsgToEml(String, String) | Converts Outlook .MSG file (in OLE2 binary format) into .EML file (in RFC822 MIME format).
 | MsgToMailMessage(Stream) | Parses Outlook .MSG data stream into MailMessage object.
Public method | MsgToMailMessage(String) | Parses Outlook .MSG file into MailMessage object.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.EmlToMsg Method

MsgConvertEmlToMsg Method
Converts RFC822 .EML file or stream into Outlook .MSG file or stream.
Overload List
 | Name | Description
Public method | EmlToMsg(Stream, Stream) | Converts .EML data (in RFC822 text format) into a stream in Outlook .MSG (OLE2) format with 8-bit encoding.
 | EmlToMsg(String, String) | Converts .EML data (in RFC822 text format) into a file in Outlook .MSG (OLE2) format with 8-bit encoding.
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.EmlToMsg Method (Stream, Stream)

MsgConvertEmlToMsg Method (Stream, Stream)
Converts .EML data (in RFC822 text format) into a stream in Outlook .MSG (OLE2) format with 8-bit encoding.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void EmlToMsg(
    Stream emlStream,
    Stream msgStream
)
Public Sub EmlToMsg (
    emlStream As Stream,
    msgStream As Stream
)

Parameters

emlStream
Type: System.IOStream
Source stream to read .EML data from.
msgStream
Type: System.IOStream
Destination stream to write .MSG (OLE2) data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emlStream or msgStream is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during reading, parsing or saving message data.
Remarks
If you need to have RTF body in the resulting MSG, see HtmlToRtfMethod property for the available options.
See Also

Reference

MsgConvert Class
EmlToMsg Overload
MailBee.Outlook Namespace


MsgConvert.EmlToMsg Method (String, String)

MsgConvertEmlToMsg Method (String, String)
Converts .EML data (in RFC822 text format) into a file in Outlook .MSG (OLE2) format with 8-bit encoding.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void EmlToMsg(
    string emlFilename,
    string msgFilename
)
Public Sub EmlToMsg (
    emlFilename As String,
    msgFilename As String
)

Parameters

emlFilename
Type: SystemString
The path to the source .EML file.
msgFilename
Type: SystemString
The path to the target Outlook .MSG file.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | emlFilename or msgFilename is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during reading, parsing or saving message data.
Remarks
If you need to have RTF body in the resulting MSG, see HtmlToRtfMethod property for the available options.
Examples
This sample converts .EML file into .MSG file.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using MailBee;
using MailBee.Outlook;

// The actual code (put it into a method of your class).
MsgConvert conv = new MsgConvert();
conv.EmlToMsg(@"C:\Temp\test.eml", @"C:\Temp\test.msg");
' To use the code below, import these namespaces at the top of your code.
Imports MailBee
Imports MailBee.Outlook

' The actual code (put it into a method of your class).
Dim conv As MsgConvert = New MsgConvert
conv.EmlToMsg("C:\Temp\test.eml", "C:\Temp\test.msg")
See Also

Reference

MsgConvert Class
EmlToMsg Overload
MailBee.Outlook Namespace


MsgConvert.MailMessageToMsg Method

MsgConvertMailMessageToMsg Method
Saves the specified MailMessage into Outlook .MSG file or stream.
Overload List
 | Name | Description
Public method | MailMessageToMsg(MailMessage, Stream) | Saves the specified MailMessage into a stream in Outlook .MSG (OLE2) format.
Public method | MailMessageToMsg(MailMessage, String) | Saves the specified MailMessage as Outlook .MSG file.
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.MailMessageToMsg Method (MailMessage, Stream)

MsgConvertMailMessageToMsg Method (MailMessage, Stream)
Saves the specified MailMessage into a stream in Outlook .MSG (OLE2) format.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void MailMessageToMsg(
    MailMessage msg,
    Stream msgStream
)
Public Sub MailMessageToMsg (
    msg As MailMessage,
    msgStream As Stream
)

Parameters

msg
Type: MailBee.MimeMailMessage
MailMessage to be saved.
msgStream
Type: System.IOStream
The target stream where to save message data in Outlook .MSG format.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or msgStream is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during saving message data.
Remarks
If you need to have RTF body in the resulting MSG, see HtmlToRtfMethod property for the available options.
See Also

Reference

MsgConvert Class
MailMessageToMsg Overload
MailBee.Outlook Namespace


MsgConvert.MailMessageToMsg Method (MailMessage, String)

MsgConvertMailMessageToMsg Method (MailMessage, String)
Saves the specified MailMessage as Outlook .MSG file.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void MailMessageToMsg(
    MailMessage msg,
    string msgFilename
)
Public Sub MailMessageToMsg (
    msg As MailMessage,
    msgFilename As String
)

Parameters

msg
Type: MailBee.MimeMailMessage
MailMessage to be saved.
msgFilename
Type: SystemString
The path to the target .MSG file.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or msgFilename is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during saving message data.
Remarks
If you need to have RTF body in the resulting MSG, see HtmlToRtfMethod property for the available options.
See Also

Reference

MsgConvert Class
MailMessageToMsg Overload
MailBee.Outlook Namespace


MsgConvert.MsgToEml Method

MsgConvertMsgToEml Method
Converts Outlook .MSG file or stream into RFC822 .EML file or stream.
Overload List
 | Name | Description
Public method | MsgToEml(Stream, Stream) | Converts Outlook .MSG data (in OLE2 binary format) into .EML data (in RFC822 MIME format).
 | MsgToEml(String, String) | Converts Outlook .MSG file (in OLE2 binary format) into .EML file (in RFC822 MIME format).
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.MsgToEml Method (Stream, Stream)

MsgConvertMsgToEml Method (Stream, Stream)
Converts Outlook .MSG data (in OLE2 binary format) into .EML data (in RFC822 MIME format).

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void MsgToEml(
    Stream msgStream,
    Stream emlStream
)
Public Sub MsgToEml (
    msgStream As Stream,
    emlStream As Stream
)

Parameters

msgStream
Type: System.IOStream
Source stream containing .MSG (OLE2) data.
emlStream
Type: System.IOStream
Destination stream to write .EML data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msgStream or emlStream is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during reading, parsing or saving message data.
See Also

Reference

MsgConvert Class
MsgToEml Overload
MailBee.Outlook Namespace


MsgConvert.MsgToEml Method (String, String)

MsgConvertMsgToEml Method (String, String)
Converts Outlook .MSG file (in OLE2 binary format) into .EML file (in RFC822 MIME format).

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void MsgToEml(
    string msgFilename,
    string emlFilename
)
Public Sub MsgToEml (
    msgFilename As String,
    emlFilename As String
)

Parameters

msgFilename
Type: SystemString
The path to the source Outlook .MSG file.
emlFilename
Type: SystemString
The path to the target .EML file.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msgFilename or emlFilename is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during reading, parsing or saving message data.
Examples
This sample converts .MSG file into .EML file.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using MailBee;
using MailBee.Outlook;

// The actual code (put it into a method of your class).
MsgConvert conv = new MsgConvert();
conv.MsgToEml(@"C:\Temp\test.msg", @"C:\Temp\test.eml");
' To use the code below, import these namespaces at the top of your code.
Imports MailBee
Imports MailBee.Outlook

' The actual code (put it into a method of your class).
Dim conv As MsgConvert = New MsgConvert
conv.MsgToEml("C:\Temp\test.msg", "C:\Temp\test.eml")
See Also

Reference

MsgConvert Class
MsgToEml Overload
MailBee.Outlook Namespace


MsgConvert.MsgToMailMessage Method

MsgConvertMsgToMailMessage Method
Parses Outlook .MSG file or stream into MailMessage object.
Overload List
 | Name | Description
 | MsgToMailMessage(Stream) | Parses Outlook .MSG data stream into MailMessage object.
Public method | MsgToMailMessage(String) | Parses Outlook .MSG file into MailMessage object.
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.MsgToMailMessage Method (Stream)

MsgConvertMsgToMailMessage Method (Stream)
Parses Outlook .MSG data stream into MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MsgToMailMessage(
    Stream msgStream
)
Public Function MsgToMailMessage (
    msgStream As Stream
) As MailMessage

Parameters

msgStream
Type: System.IOStream
The source stream containing Outlook .MSG data.

Return Value

Type: MailMessage
MailMessage object containing the parsed mail message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msgStream is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during reading or parsing message data.
Examples
You can find the example in MsgConvert topic.
See Also

Reference

MsgConvert Class
MsgToMailMessage Overload
MailBee.Outlook Namespace


MsgConvert.MsgToMailMessage Method (String)

MsgConvertMsgToMailMessage Method (String)
Parses Outlook .MSG file into MailMessage object.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MsgToMailMessage(
    string msgFilename
)
Public Function MsgToMailMessage (
    msgFilename As String
) As MailMessage

Parameters

msgFilename
Type: SystemString
The path to the source Outlook .MSG file.

Return Value

Type: MailMessage
MailMessage object containing the parsed mail message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msgFilename is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred during reading or parsing message data.
See Also

Reference

MsgConvert Class
MsgToMailMessage Overload
MailBee.Outlook Namespace


MsgConvert Properties

MsgConvert Properties

The MsgConvert type exposes the following members.

Properties
 | Name | Description
Public property | HtmlToRtfMethod | Gets or sets which HTML-to-RTF conversion method to use when making .MSG out of .EML source.
 | LicenseKey | Obsolete. Assigns the license key.
Public property | MsgAsDraft | Gets or sets whether the resulting .MSG message should be saved as "Draft" (editable) or "Sent" (read-only).
Public property | MsgAsUnicode | Gets or sets whether string values during .EML-to-.MSG transformation will be saved as Unicode (allows using international characters).
Public property | MsgIsFromMe | Gets or sets whether MSGFLAG_FROMME flag will set in the resuling .MSG message.
Public property | OnByteToStringConversion | Gets or sets the application-supplied callback MailBee will execute in order to convert bytes to string when making .EML from .MSG source.
Public property | OnHtmlToRtfConversion | Gets or sets the application-supplied callback MailBee will execute in order to convert HTML-to-RTF when making .MSG out of .EML source.
Public property | PreferAddressesFromInternetHeaders | Gets or sets whether From/To/CC/BCC addresses must be loaded from Internet headers of the .MSG message.
Public property | PreferRtfBodyToHtml | Gets or sets whether the HTML body of the resulting .EML should be taken from RTF part (instead of HTML part) of the source .MSG message, if it has both RTF and HTML part.
 | RtfInEmlMethod | Gets or sets if RTF text body from .MSG message should be added as an attachment or as a body part into the resulting .EML message, or not added at all.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.HtmlToRtfMethod Property

MsgConvertHtmlToRtfMethod Property
Gets or sets which HTML-to-RTF conversion method to use when making .MSG out of .EML source.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToRtfConversionMethod HtmlToRtfMethod { get; set; }
Public Property HtmlToRtfMethod As HtmlToRtfConversionMethod
    Get
    Set

Property Value

Type: HtmlToRtfConversionMethod
The default value is None which means no RTF body will be added during .EML into .MSG conversion.
Remarks
If you certainly need RTF body be added and HTML body is not an option, you can either use MailBee's internal converter or supply your own. However, because MailBee's internal converter cannot transform all the HTML formatting into RTF formatting (this would be an extremely complex task because both formats have lots of formatting mechanisms and they are very different), the formatting of the resulting RTF won't be perfect. Also, if you strictly need RTF and MailBee's converter is not suitable for you, you can plug your own converter in (for instance, if you have a dedicated component for HTML-to-RTF conversion). See HtmlToRtfConversionMethod topic for details.
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.LicenseKey Property

MsgConvertLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.MsgAsDraft Property

MsgConvertMsgAsDraft Property
Gets or sets whether the resulting .MSG message should be saved as "Draft" (editable) or "Sent" (read-only).

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MsgAsDraft { get; set; }
Public Property MsgAsDraft As Boolean
    Get
    Set

Property Value

Type: Boolean
The default value is false.
Remarks
This property makes sense only for EML-to-MSG conversion. MSG-to-EML conversion is not affected.
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.MsgAsUnicode Property

MsgConvertMsgAsUnicode Property
Gets or sets whether string values during .EML-to-.MSG transformation will be saved as Unicode (allows using international characters).

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MsgAsUnicode { get; set; }
Public Property MsgAsUnicode As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, string values .EML-to-.MSG transformation will be saved as Unicode (allows using international characters); otherwise, as 8-bit ANSI strings. The default is true.
Remarks
HTML body encoding is not affected by this property because HTML body is neither Unicode nor ANSI (it's usually UTF-8).
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.MsgIsFromMe Property

MsgConvertMsgIsFromMe Property
Gets or sets whether MSGFLAG_FROMME flag will set in the resuling .MSG message.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MsgIsFromMe { get; set; }
Public Property MsgIsFromMe As Boolean
    Get
    Set

Property Value

Type: Boolean
The default value is false.
Remarks

The messaging user sending was the messaging user receiving the message. Normally you'll leave this flag in its default state. Setting it to true may help if you encounter "You are not allowed to send this message because you are trying to send on behalf of another sender without permission to do so." or similar issues when sending this message to MS Exchange.

This property makes sense only for EML-to-MSG conversion. MSG-to-EML conversion is not affected.

See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.OnByteToStringConversion Property

MsgConvertOnByteToStringConversion Property
Gets or sets the application-supplied callback MailBee will execute in order to convert bytes to string when making .EML from .MSG source.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ByteToStringConversionHandler OnByteToStringConversion { get; set; }
Public Property OnByteToStringConversion As ByteToStringConversionHandler
    Get
    Set

Property Value

Type: ByteToStringConversionHandler
The default value is a null reference (Nothing in Visual Basic).
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.OnHtmlToRtfConversion Property

MsgConvertOnHtmlToRtfConversion Property
Gets or sets the application-supplied callback MailBee will execute in order to convert HTML-to-RTF when making .MSG out of .EML source.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToRtfConversionHandler OnHtmlToRtfConversion { get; set; }
Public Property OnHtmlToRtfConversion As HtmlToRtfConversionHandler
    Get
    Set

Property Value

Type: HtmlToRtfConversionHandler
The default value is a null reference (Nothing in Visual Basic).
Remarks
MailBee will execute this callback whenever you convert .EML into .MSG and HtmlToRtfMethod is UseDelegate. For more information on RTF in .MSG files and HTML-to-RTF conversions, see HtmlToRtfConversionMethod topic.
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.PreferAddressesFromInternetHeaders Property

MsgConvertPreferAddressesFromInternetHeaders Property
Gets or sets whether From/To/CC/BCC addresses must be loaded from Internet headers of the .MSG message.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool PreferAddressesFromInternetHeaders { get; set; }
Public Property PreferAddressesFromInternetHeaders As Boolean
    Get
    Set

Property Value

Type: Boolean
The default value is true which means From/To/CC/BCC addresses will be taken from Internet headers if they are available. Otherwise, they will be taken from the designated properties of the .MSG structure (if they are available).
Remarks

.MSG messages store sender and recipients in two places - Internet headers and separate properties. Usually, they match. Sometimes, they don't. If you need a specific set of these values, you can change this property value to false. In this case MailBee will overwite From/To/CC/BCC values obtained from Internet headers with their versions from separate .MSG properties (if they are available).

If the .MSG message doesn't have Internet headers at all (i.e. it's a draft which has never been sent), it won't have Internet headers anyway and From/To/CC/BCC will be obtained from their designated properties only. The value of PreferAddressesFromInternetHeaders property won't matter in this case.

The same way, if the .MSG message does have Internet headers but doesn't have From/To/CC/BCC in separate properties, only values from Internet headers will be used regardless of PreferAddressesFromInternetHeaders property value. Shortly speaking, this property has effect only if both Internet headers and separate properties exist in the message so there is an ambiguity which one to use.

See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.PreferRtfBodyToHtml Property

MsgConvertPreferRtfBodyToHtml Property
Gets or sets whether the HTML body of the resulting .EML should be taken from RTF part (instead of HTML part) of the source .MSG message, if it has both RTF and HTML part.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool PreferRtfBodyToHtml { get; set; }
Public Property PreferRtfBodyToHtml As Boolean
    Get
    Set

Property Value

Type: Boolean
The default value is false which means HTML body is preferred.
Remarks
Sometimes, .MSG-to-.EML codepage transform will work better when HTML body is taken from RTF part. If .MSG contains only RTF part or only HTML part, RTF (or HTML, respectively) will be used regardless of the value of this property.
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.RtfInEmlMethod Property

MsgConvertRtfInEmlMethod Property
Gets or sets if RTF text body from .MSG message should be added as an attachment or as a body part into the resulting .EML message, or not added at all.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public RtfInEmlStorageMethod RtfInEmlMethod { get; set; }
Public Property RtfInEmlMethod As RtfInEmlStorageMethod
    Get
    Set

Property Value

Type: RtfInEmlStorageMethod
The default value is None which means that RTF part will not be added to the .EML message.
Remarks
If you set this property to AsAttachment, MailBee will add RTF (rich-text format) body of .MSG message as .RTF attachment named "richbody.rtf" to the resulting .EML message (into its Attachments collection). If you, however, need this body to be added to BodyParts collection where plain-text and HTML bodies usually reside, set this property value to AsBodyPart before making the conversion. This is useful if you need to get the contents of the RTF body as a string (for instance, if you assign its value to Rtf (System.Windows.Forms.RichTextBox.Rtf) property to display it in a RichTextBox control).
Note Note
This property makes sense only for ".MSG to .EML" direction of conversion. It's not used for ".EML to .MSG" conversions.
Examples
This sample displays RTF body of .MSG message in RichTextBox ((System.Windows.Forms.RichTextBox)) control of a WinForms application. It's assumed MailBee.Global.LicenseKey is already assigned (for instance, in app.config or web.config file) and the application form contains richTextBox1 control.
Note Note
If you prefer to open RTF with WordPAD (or with another program which opens .RTF files in your system) instead of feeding RTF data to the RichTextBox control, you should rather set RtfInEmlMethod property to AsAttachment, perform the conversion, then save "richbody.rtf" in Attachments collection of the resulting MailMessage into a file, and open that file in WordPAD.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using MailBee.Outlook;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MsgConvert conv = new MsgConvert();
conv.RtfInEmlMethod = RtfInEmlStorageMethod.AsBodyPart;
MailMessage msg = conv.MsgToMailMessage("test.msg");

if (msg.BodyParts["text/rtf"] != null)
{
    richTextBox1.Rtf = msg.BodyParts["text/rtf"].Text;
}
' To use the code below, import these namespaces at the top of your code.
Imports MailBee.Outlook
Imports MailBee.Mime

Dim conv As MsgConvert = New MsgConvert
conv.RtfInEmlMethod = RtfInEmlStorageMethod.AsBodyPart
Dim msg As MailMessage = conv.MsgToMailMessage("test.msg")

If Not msg.BodyParts("text/rtf") Is Nothing Then
    richTextBox1.Rtf = msg.BodyParts("text/rtf").Text
End If
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


MsgConvert.TrialDaysLeft Property

MsgConvertTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value indicating the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

MsgConvert Class
MailBee.Outlook Namespace


PstItemType Enumeration

PstItemType Enumeration
Defines types of PST objects.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum PstItemType
Public Enumeration PstItemType
Members
Member name | Value | Description
Message | 0 | The PST object is Message.
Contact | 1 | The PST object is Contact information.
Rss | 2 | The PST object is RSS stream.
Task | 3 | The PST object is Task.
Appointment | 4 | The PST object is Appointment.
Activity | 5 | The PST object is Activity.
Other | 6 | The PST object is of other type (not listed above).
DistList | 7 | This PST object is Distribution List.
See Also

Reference

MailBee.Outlook Namespace


PstReader Class

PstReader Class
Provides methods for parsing Outlook .PST message database file into a collection of folders and items.
Inheritance Hierarchy
SystemObject
MailBee.OutlookPstReader

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class PstReader
Public Class PstReader

The PstReader type exposes the following members.

Constructors
 | Name | Description
Public method | PstReader(Stream) | Creates an instance of PstReader class and loads .PST database from a stream.
Public method | PstReader(String) | Creates an instance of PstReader class and opens the specified .PST file.
Public method | PstReader(Stream, String) | Creates a new .PST reader and loads .PST database from a stream.
Public method | PstReader(String, String) | Creates a new .PST reader, unlocks it and loads .PST database from the specified file.
Top
Methods
 | Name | Description
Public method | Close | Closes the opened .PST stream.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetFolderByID | Gets the PST folder by its ID.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetItemByID | Gets the PST item by its ID.
 | GetPstRootFolders(Boolean) | Gets the list of root folders which are present in the .PST file or stream.
Public method | GetPstRootFolders(Boolean, String) | Gets the list of root folders which are present in the .PST file or stream with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | LicenseKey | Obsolete. Assigns the license key.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
Remarks

PstReader class parses a .PST file, extracts its tree-like structure (folders and other items like messages, contacts, tasks, etc), and provides access to the extracted data.

You can parse very large .PST files with this method as it does not parse the file at once. Instead, it allows you to iterate though the collection of folders or items at any nesting level, processing items one-by-one and thus reducing memory usage.

Prior to creating instances of this class, the correct license key must be set. See MailBee.Global.LicenseKey property for details.

Examples
This sample enumerates Outlook .PST file as a folder tree and then saves all objects as .EML files in their respective folders. This way, you get the same filesystem structure as you had in .PST file.
Note Note
In this sample, it's assumed the license key is already set outside (such as in app.config file). Otherwise, use MailBee.Global.LicenseKey property to unlock the component.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using System.IO;
using MailBee.Outlook;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        PstReader reader = new PstReader(@"C:\OutlookMessageBase\Outlook.pst");

        string outPath = @"C:\OutlookMessageBase\PstOutputDir";

        PstFolderCollection pstColl = reader.GetPstRootFolders(true);

        foreach (PstFolder fItem in pstColl)
        {
            int i = 0;
            Console.WriteLine(":::    " + fItem.Name);

            string folderPath = Path.Combine(outPath, fItem.SafeName);
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            foreach (PstItem item in fItem.Items)
            {
                if (item != null && item.PstType == PstItemType.Message)
                {
                    MailMessage msg = ((PstMessage) item).GetAsMailMessage();

                    Console.WriteLine(msg.Subject);

                    string fileName = Path.Combine(folderPath, string.Format("{0}_{1}.eml",
                        PstMessage.MakeStringSafeForFileName(msg.Subject), i++));

                    // Charset fix.
                    msg.Parser.CharsetMetaTagMode = CharsetMetaTagProcessing.RemoveCharsetMetaTag;
                    msg.Charset = "UTF-8";
                    msg.EncodeAllHeaders(System.Text.Encoding.UTF8, HeaderEncodingOptions.None);

                    msg.SaveMessage(fileName);

                    //msg = null;
                    //GC.Collect(); // For big amount of large messages
                }
            }
        }
    }
}
' To use the code below, import these namespaces at the top of your code.
Imports System
Imports System.IO
Imports MailBee.Outlook
Imports MailBee.Mime

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim reader As PstReader = New PstReader("C:\OutlookMessageBase\Outlook.pst")

        Dim outPath As String = "C:\OutlookMessageBase\PstOutputDir"

        Dim pstColl As PstFolderCollection = reader.GetPstRootFolders(True)

        Dim fItem As PstFolder
        For Each fItem In pstColl
            Dim i As Integer = 0
            Console.WriteLine(":::    " & fItem.Name)

            Dim folderPath As String = Path.Combine(outPath, fItem.SafeName)
            If Not Directory.Exists(folderPath) Then
                Directory.CreateDirectory(folderPath)
            End If

            Dim item As PstItem
            For Each item In fItem.Items
                If Not item Is Nothing And item.PstType = PstItemType.Message Then
                    Dim msg As MailMessage = (CType(item, PstMessage)).GetAsMailMessage()

                    Console.WriteLine(msg.Subject)

                    i = i + 1
                    Dim fileName As String = Path.Combine(folderPath, String.Format("{0}_{1}.eml", _
                     PstMessage.MakeStringSafeForFileName(msg.Subject), i))

                    ' Charset fix.
                    msg.Parser.CharsetMetaTagMode = CharsetMetaTagProcessing.RemoveCharsetMetaTag
                    msg.Charset = "UTF-8"
                    msg.EncodeAllHeaders(System.Text.Encoding.UTF8, HeaderEncodingOptions.None)

                    msg.SaveMessage(fileName)

                    'msg = Nothing
                    'GC.Collect() 'For big amount of large messages
                End If
            Next
        Next
    End Sub
End Class
See Also

Reference

MailBee.Outlook Namespace


PstReader Constructor

PstReader Constructor
Creates an instance of PstReader class.
Overload List
 | Name | Description
Public method | PstReader(Stream) | Creates an instance of PstReader class and loads .PST database from a stream.
Public method | PstReader(String) | Creates an instance of PstReader class and opens the specified .PST file.
Public method | PstReader(Stream, String) | Creates a new .PST reader and loads .PST database from a stream.
Public method | PstReader(String, String) | Creates a new .PST reader, unlocks it and loads .PST database from the specified file.
Top
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


PstReader Constructor (Stream)

PstReader Constructor (Stream)
Creates an instance of PstReader class and loads .PST database from a stream.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstReader(
    Stream pstStream
)
Public Sub New (
    pstStream As Stream
)

Parameters

pstStream
Type: System.IOStream
The stream containing the .PST database.
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Outlook Converter not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

PstReader Class
PstReader Overload
MailBee.Outlook Namespace


PstReader Constructor (String)

PstReader Constructor (String)
Creates an instance of PstReader class and opens the specified .PST file.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstReader(
    string pstFilePath
)
Public Sub New (
    pstFilePath As String
)

Parameters

pstFilePath
Type: SystemString
The path to the file containing the .PST database.
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Outlook Converter not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

PstReader Class
PstReader Overload
MailBee.Outlook Namespace


PstReader Constructor (Stream, String)

PstReader Constructor (Stream, String)
Creates a new .PST reader and loads .PST database from a stream.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstReader(
    Stream pstStream,
    string licenseKey
)
Public Sub New (
    pstStream As Stream,
    licenseKey As String
)

Parameters

pstStream
Type: System.IOStream
The stream containing the .PST database.
licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | pstStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred.
MailBeeLicenseException | MailBee.NET Outlook Converter not licensed and the supplied license key is invalid.
See Also

Reference

PstReader Class
PstReader Overload
MailBee.Outlook Namespace


PstReader Constructor (String, String)

PstReader Constructor (String, String)
Creates a new .PST reader, unlocks it and loads .PST database from the specified file.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstReader(
    string pstFilePath,
    string licenseKey
)
Public Sub New (
    pstFilePath As String,
    licenseKey As String
)

Parameters

pstFilePath
Type: SystemString
The path to the file containing the .PST database.
licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | pstFilePath is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | An I/O error occurred.
MailBeeLicenseException | MailBee.NET Outlook Converter not licensed and the supplied license key is invalid.
See Also

Reference

PstReader Class
PstReader Overload
MailBee.Outlook Namespace


PstReader Methods

PstReader Methods

The PstReader type exposes the following members.

Methods
 | Name | Description
Public method | Close | Closes the opened .PST stream.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetFolderByID | Gets the PST folder by its ID.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetItemByID | Gets the PST item by its ID.
 | GetPstRootFolders(Boolean) | Gets the list of root folders which are present in the .PST file or stream.
Public method | GetPstRootFolders(Boolean, String) | Gets the list of root folders which are present in the .PST file or stream with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


PstReader.Close Method

PstReaderClose Method
Closes the opened .PST stream.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Close()
Public Sub Close
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


PstReader.GetFolderByID Method

PstReaderGetFolderByID Method
Gets the PST folder by its ID.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstFolder GetFolderByID(
    int pstID
)
Public Function GetFolderByID (
    pstID As Integer
) As PstFolder

Parameters

pstID
Type: SystemInt32
The PST ID value of the folder to be retrieved.

Return Value

Type: PstFolder
A PstFolder object representing the folder.
Remarks
To learn the ID value of certain folder (so that you can later pass it to this method), you can use its PstID property.
See Also

Reference

PstReader Class
MailBee.Outlook Namespace
PstFolderPstID


PstReader.GetItemByID Method

PstReaderGetItemByID Method
Gets the PST item by its ID.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstItem GetItemByID(
    int pstID
)
Public Function GetItemByID (
    pstID As Integer
) As PstItem

Parameters

pstID
Type: SystemInt32
The PST ID value of the item to be retrieved.

Return Value

Type: PstItem
A PST item representing the item.
Remarks

The possible types of the returned value are: PstMessage, PstAppointment, PstContact, PstTask, PstActivity, PstRss, PstDistList, and generic PstItem for unknown types.

To learn the ID value of certain item (so that you can later pass it to this method), you can use its PstID property (such as PstID).

See Also

Reference

PstReader Class
MailBee.Outlook Namespace
PstItemPstID


PstReader.GetPstRootFolders Method

PstReaderGetPstRootFolders Method
Gets the list of root folders which are present in the .PST file or stream.
Overload List
 | Name | Description
 | GetPstRootFolders(Boolean) | Gets the list of root folders which are present in the .PST file or stream.
Public method | GetPstRootFolders(Boolean, String) | Gets the list of root folders which are present in the .PST file or stream with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.
Top
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


PstReader.GetPstRootFolders Method (Boolean)

PstReaderGetPstRootFolders Method (Boolean)
Gets the list of root folders which are present in the .PST file or stream.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstFolderCollection GetPstRootFolders(
    bool includeSubFolders
)
Public Function GetPstRootFolders (
    includeSubFolders As Boolean
) As PstFolderCollection

Parameters

includeSubFolders
Type: SystemBoolean
If true, all subfolders will be included in the resulting list; otherwise, only the top level folders without their own sub-folders.

Return Value

Type: PstFolderCollection
A PstFolderCollection object representing the folder collection.
Remarks

The returned folders may contain their own sub-folders and other items like e-mail messages, contacts, appointments, tasks, etc.

includeSubFolders is true, you'll get all the folders on all nesting levels as a single flat list. When iterating through this list, you can use Name property to get full folder name including all parent folder names. ShortName gives you the name of the folder itself.

If you're not using flat list and specified includeSubFolders as false, you can still get the list of sub-folders for each folder using its GetPstSubFolders(Boolean) method (and then recursively repeat the same if sub-folders have their own sub-folders, etc).

The delimiter which is used to separate levels of folder names is: "\".

Examples
The example is available in PstReader topic. That example specifies includeSubFolders as true and thus all folders and sub-folders are returned as a single flat list. Thus, there is no need to use recursion in order to traverse through the entire folder tree.
See Also

Reference

PstReader Class
GetPstRootFolders Overload
MailBee.Outlook Namespace


PstReader.GetPstRootFolders Method (Boolean, String)

PstReaderGetPstRootFolders Method (Boolean, String)
Gets the list of root folders which are present in the .PST file or stream with specified delimiter which is used as a hierarchy delimiter of separate levels of folder names.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PstFolderCollection GetPstRootFolders(
    bool includeSubFolders,
    string delimiter
)
Public Function GetPstRootFolders (
    includeSubFolders As Boolean,
    delimiter As String
) As PstFolderCollection

Parameters

includeSubFolders
Type: SystemBoolean
If true, all subfolders will be included in the resulting list; otherwise, only the top level folders without their own sub-folders.
delimiter
Type: SystemString
The string used to separate levels of hierarchy of folder names.

Return Value

Type: PstFolderCollection
A PstFolderCollection object representing the folder collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | delimiter is a null reference (Nothing in Visual Basic).
See Also

Reference

PstReader Class
GetPstRootFolders Overload
MailBee.Outlook Namespace


PstReader Properties

PstReader Properties

The PstReader type exposes the following members.

Properties
 | Name | Description
 | LicenseKey | Obsolete. Assigns the license key.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


PstReader.LicenseKey Property

PstReaderLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


PstReader.TrialDaysLeft Property

PstReaderTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value indicating the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

PstReader Class
MailBee.Outlook Namespace


RtfInEmlStorageMethod Enumeration

RtfInEmlStorageMethod Enumeration
Defines supported methods of placing RTF body of the source .MSG message into resulting .EML message.

Namespace: MailBee.Outlook
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum RtfInEmlStorageMethod
Public Enumeration RtfInEmlStorageMethod
Members
Member name | Value | Description
None | 0 | RTF body will not be added into the produced .EML message. The .EML message will have only plain-text part unless the source .MSG message explicitly included HTML part.
AsAttachment | 1 | RTF body will be added as "richbody.rtf" attachment of the resulting .EML message.
AsBodyPart | 2 | RTF body will be added as a text part of content-type "text/rtf" of the resulting .EML message.
See Also

Reference

MailBee.Outlook Namespace


MailBee.Pdf Namespace

MailBee.Pdf Namespace

MailBee.Pdf namespace provides HtmlToPdf class which lets you perform HTML to PDF conversion. PDF functionality resides in separate DLLs. If you're using Nuget, you'll also need to install MailBee.NET.PDF package (it installs MailBee.NET.PDF.dll, HtmlAgilityPack 1.4.9.5 and iTextSharp LGPL 4.1.6).

PDF feature is only supported in classic .NET Framework. It's not available in .NET Core and UWP.

Classes
Class | Description
HtmlToPdf | Provides methods and properties for HTML to PDF conversion.
Delegates
 | Delegate | Description
Public delegate | ConvertXmlNodeToPdfDelegate | Defines the delegate for fine-tuning of HTML to PDF conversion.
Public delegate | ProcessImagePathDelegate | Defines the delegate for processing of absent images or images with incorrect path.
Enumerations
Enumeration | Description
PdfSourceType | Defines the available values for HtmlToPdf.SourceType property to specify the type of source data for conversion to PDF document.


ConvertXmlNodeToPdfDelegate Delegate

ConvertXmlNodeToPdfDelegate Delegate
Defines the delegate for fine-tuning of HTML to PDF conversion.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate IElement ConvertXmlNodeToPdfDelegate(
    XmlNode xmlNode,
    IElement pdfChunk
)
Public Delegate Function ConvertXmlNodeToPdfDelegate (
    xmlNode As XmlNode,
    pdfChunk As IElement
) As IElement

Parameters

xmlNode
Type: System.XmlXmlNode
An XmlNode object for the current document node.
pdfChunk
Type: IElement
An iTextSharp.text.IElement object for the current document node, processed by Html to Pdf converter

Return Value

Type: IElement
An iTextSharp.text.IElement object with processed part of .pdf document
Remarks

You can use it if you want to add processing of CSS or change default behaviour of the converter.

To set this delegate, use OnConvertXmlNodeToPdf property.

See Also

Reference

MailBee.Pdf Namespace


HtmlToPdf Class

HtmlToPdf Class
Provides methods and properties for HTML to PDF conversion.
Inheritance Hierarchy
SystemObject
MailBee.PdfHtmlToPdf

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class HtmlToPdf
Public Class HtmlToPdf

The HtmlToPdf type exposes the following members.

Constructors
 | Name | Description
 | HtmlToPdf | Creates an instance of HtmlToPdf class.
Public method | HtmlToPdf(String) | Creates and unlocks an instance of HtmlToPdf class.
 | HtmlToPdf(Boolean, Encoding, String, String) | Creates an instance of HtmlToPdf class for use with international charsets.
Top
Methods
 | Name | Description
 | Convert(Stream, Stream) | Writes an HTML or plain-text string into a stream in PDF format.
 | Convert(Stream, String) | Writes an HTML or plain-text string into the file in PDF format.
 | Convert(String, Stream) | Writes an HTML or plain-text string into a stream in PDF format.
 | Convert(String, String) | Writes an HTML or plain-text string into the file in PDF format.
 | Convert(Uri, Stream) | Converts HTML, plain text or XML document denoted by the specified URI into the stream in PDF format.
 | Convert(Uri, String) | Converts HTML, plain text or XML document denoted by the specified URI into the file in PDF format.
 | ConvertFile(String, Stream) | Writes the file with HTML or plain-text string into a stream in PDF format.
 | ConvertFile(String, String) | Writes the file with HTML or plain-text string into the file in PDF format.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DefaultFont | Gets or sets default font for creating .pdf document with specified name or filename, encoding and size as iTextSharp.text.Font object.
Public property | DefaultFontSize | Gets or sets font size for the internal default font.
 | LicenseKey | Obsolete. Assigns the license key.
 | OnConvertXmlNodeToPdf | Gets or sets the application-supplied method for fine-tuning of source to PDF conversion.
Public property | OnProcessImagePath | Gets or sets the application-supplied method for changing path or URI or URL to the image.
Public property | PageRectangle | Gets or sets page size of .pdf document as iTextSharp.text.Rectangle object.
Public property | SourceType | Gets or sets the format of the input data for the conversion.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | UseBlackAndWhiteStyle | Enables conversion of colored HTML document to black and white PDF document.
Top
Remarks

This class is capable of converting table-based HTML/XHTML documents (like invoices and reports) or plain-text into PDF format. For HTML, only the most common CSS styles are supported. The component, however, provides OnConvertXmlNodeToPdf delegate which allows you to fine-tune the conversion process by adjusting colors, alignment, fonts, or with direct emitting PDF content.

Prior to creating instances of this class, the correct license key must be set. See MailBee.Global.LicenseKey property for details.

Note Note
This class uses iTextSharp and HtmlAgilityPack open source libraries to make HTML be XHTML compliant and build actual PDF content. If you're using HtmlToPdf class, you'll also need to copy the corresponding .DLLs with your application. By default, iTextSharp and HtmlAgilityPack .DLLs reside at the same location where MailBee.NET.dll itself.
Note Note
This class is not supported in .NET Core and UWP apps.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

MailBee.Pdf Namespace


HtmlToPdf Constructor

HtmlToPdf Constructor
Creates an instance of HtmlToPdf class.
Overload List
 | Name | Description
 | HtmlToPdf | Creates an instance of HtmlToPdf class.
Public method | HtmlToPdf(String) | Creates and unlocks an instance of HtmlToPdf class.
 | HtmlToPdf(Boolean, Encoding, String, String) | Creates an instance of HtmlToPdf class for use with international charsets.
Top
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf Constructor

HtmlToPdf Constructor
Creates an instance of HtmlToPdf class.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPdf()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET PDF not licensed.
Remarks

This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).

To use international charsets or the fonts besides built-in ones, use HtmlToPdf(bool, Encoding, string, string) overload. See DefaultFont property for the list of built-in fonts.

Examples

All the samples assume LicenseKey property is set.

The first sample shows how to convert HTML invoice without CSS to .pdf file and send it via e-mail.

Please save the HTML code below as "C:\Temp\invoice543.html". It's used by the code samples.

C#
VB
Copy
using System;
using System.IO;
using System.Xml;
using MailBee.Pdf;
using MailBee.Mime;
using MailBee.SmtpMail;
using iTextSharp.text;

class Sample
{
    static void Main(string[] args)
    {
        HtmlToPdf conv = new HtmlToPdf();

        conv.DefaultFontSize = 7;

        // Uncomment to use black-and-white colors only.

        //conv.UseBlackAndWhiteStyle = true;

        // Uncomment to use Windows fonts instead of built-in fonts (requires permissions to access Windows folder).

        //FontFactory.RegisterDirectory(Environment.SystemDirectory + @"\..\Fonts");
        //conv.DefaultFont = FontFactory.GetFont("Arial", "windows-1252", true, (float)8, iTextSharp.text.Font.NORMAL);
        //conv.DefaultFont = FontFactory.GetFont("Times New Roman", "windows-1255", true, (float)8, iTextSharp.text.Font.NORMAL);

        // To save .pdf file use this code.
        conv.ConvertFile(@"C:\Temp\invoice543.html", @"C:\Temp\invoice543.pdf");

        // Or uncomment to send .pdf file as message attachment.

        /*MemoryStream memStream = new MemoryStream();
        conv.ConvertFile(@"C:\Temp\invoice543.html", memStream);

        MailMessage msg = new MailMessage();

        msg.From = new EmailAddress("bill1@domain1.com", "Bill Goodwin");
        msg.To.AddFromString("John Smith <john@host.com>");
        msg.Subject = "Invoice 534";
        msg.BodyPlainText = "See attached invoice";

        msg.Attachments.Add(memStream, "invoice543.pdf", null, "application/pdf", null,
            NewAttachmentOptions.None, MailTransferEncoding.Base64);

        Smtp mailer = new Smtp();

        mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret");

        mailer.Message = msg;

        mailer.Send();*/
    }
}
Imports System.IO
Imports System.Xml
Imports MailBee.Pdf
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports iTextSharp.text

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim conv As New HtmlToPdf

        conv.DefaultFontSize = 7

        ' Uncomment to use black-and-white colors only.

        'conv.UseBlackAndWhiteStyle = True

        ' Uncomment to use Windows fonts instead of built-in fonts (requires permissions to access Windows folder).

        'FontFactory.RegisterDirectory(Environment.SystemDirectory & "\..\Fonts")
        'conv.DefaultFont = FontFactory.GetFont("Arial", "windows-1252", True, CSng(8), iTextSharp.text.Font.NORMAL)
        'conv.DefaultFont = FontFactory.GetFont("Times New Roman", "windows-1255", True, CSng(8), iTextSharp.text.Font.NORMAL)

        ' To save .pdf file use this code.
        conv.ConvertFile("C:\Temp\invoice543.html", "C:\Temp\invoice543.pdf")

        ' Or uncomment to send .pdf file as message attachment.

        'Dim memStream As New MemoryStream()
        'conv.ConvertFile("C:\Temp\invoice543.html", memStream)

        'Dim msg As New MailMessage()

        'msg.From = New EmailAddress("bill1@domain1.com", "Bill Goodwin")
        'msg.[To].AddFromString("John Smith <john@host.com>")
        'msg.Subject = "Invoice 534"
        'msg.BodyPlainText = "See attached invoice"

        'msg.Attachments.Add(memStream, "invoice543.pdf", Nothing, "application/pdf", Nothing, NewAttachmentOptions.None, _
        ' MailTransferEncoding.Base64)

        'Dim mailer As New Smtp()

        'mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret")

        'mailer.Message = msg

        'mailer.Send()
    End Sub
End Class
Copy
<body>
<h1>Invoice Samples</h1>
<p>
<strong>HTML Invoice (with shading)</strong>
</p>
<br />
<p>
<!-- begin invoice -->
<div>        <table width="620" border="0" cellpadding="5" cellspacing="0">
<tbody>
<tr bgcolor="#FFBF00">
    <td>

    </td>
</tr>
<tr bgcolor="#FFBF00">
    <td align="center" valign="middle">
    <table width="600" border="0" cellpadding="3" cellspacing="2" style="color:black;">
    <tbody>
        <tr><td colspan="5"><img src="http://www.afterlogic.com/images/logo-transparent.png" border="0"></td></tr>
        <tr bgcolor="#FFBF00">
            <td width="300" colspan="3">
                <strong>AfterLogic Inc. </strong>
            </td>
            <td width="300" colspan="2" align="right">
                <strong>Invoice #543</strong>
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="3">
                1234 Main St.
            </td>
            <td align="right" colspan="2">
                Apr 12, 2011
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="3">
                Seattle, WA 98103
            </td>
            <td align="right" colspan="2">
                Client: John Smith
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="3">
                206-123-4567
            </td>
            <td align="right" colspan="2"></td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="3">

            </td>
            <td align="right" colspan="2">
                Terms: Due On Receipt
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">

            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">
                <b>Project:</b> Smith Remodel
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">

            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">
                <b>Hours Detail:</b> (4.00 Hours)
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">

            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td width="125">
                <strong>Date</strong>
            </td>
            <td width="250">
                <strong>Description</strong>
            </td>
            <td width="75">
                <strong>Hours</strong>
            </td>
            <td width="75">
                <strong>Price</strong>
            </td>
            <td width="75" align="right">
                <strong>Amount</strong>
            </td>
        </tr>
        <tr bgcolor="#999999" style="">
            <td valign="top">
                Jun 2, 2011
            </td>
            <td valign="top">
                Software project development. WebMail customization for ISP.
            </td>
            <td valign="top">
                4.00
            </td>
            <td valign="top">
                $100.00
            </td>
            <td valign="top" align="right">
                $400.00
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">

            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">
                <b>Items Detail:</b> (1.00 Items)
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">

            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td width="125">
                <strong>Date</strong>
            </td>
            <td width="250">
                <strong>Description</strong>
            </td>
            <td width="75">
                <strong>Quantity</strong>
            </td>
            <td width="75">
                <strong>Price</strong>
            </td>
            <td width="75" align="right">
                <strong>Amount</strong>
            </td>
        </tr>
        <tr bgcolor="#999999">
            <td valign="top">
                Oct 15, 2011
            </td>
            <td valign="top">
                12v Halogen bulbs
            </td>
            <td valign="top">
                4.00
            </td>
            <td valign="top">
                $3.99
            </td>
            <td valign="top" align="right">
                $15.96
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="5">

            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="2" width="300">

            </td>
            <td colspan="2" width="225" align="right">
                <strong>Subtotal:</strong>
            </td>
            <td width="75" align="right">
                <strong>$415.96</strong>
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="2" width="300">

            </td>
            <td colspan="2" width="225" align="right">
                <strong>Discount -5.00%:</strong>
            </td>
            <td width="75" align="right">
                <strong>($20.80)</strong>
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="4" width="525" align="right">
                <strong>Total:</strong>
            </td>
            <td width="75" align="right">
                <strong>$395.16</strong>
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="2" width="300">
                <dl>
                    <dt>
                        <strong>Payment Details:</strong>
                    </dt>
                    <dd>
                        May 20, 2011 Check #11223 - $2000.00
                    </dd>
                </dl>
            </td>
            <td colspan="2" width="225" align="right" valign="bottom">
                <strong>Total Payments:</strong>
            </td>
            <td width="75" align="right" valign="bottom">
                <strong>$2000.00</strong>
            </td>
        </tr>
        <tr bgcolor="#FFBF00">
            <td colspan="2" width="300">
                Thanks for your business!
            </td>
            <td colspan="2" width="225" align="right">
                <strong>Amount Due:</strong>
            </td>
            <td width="75" align="right">
                <strong>$195.16</strong>
            </td>
        </tr>
    </tbody>
    </table>
    </td>
</tr>
</tbody>
</table></div>
<!-- end invoice -->

</p>
<p>
<strong>HTML Invoice (without shading)</strong>
</p>
<br />
<p>
<!-- begin invoice -->
<div>        <table width="600" border="0" cellpadding="3" cellspacing="2" style="color:black;">
<tbody>
    <tr><td colspan="5"><img src="http://www.afterlogic.com/images/logo-transparent.png" border="0"></td></tr>
    <tr bgcolor="#FFFFFF">
        <td width="300" colspan="3">
            <strong>AfterLogic Inc. </strong>
        </td>
        <td width="300" colspan="2" align="right">
            <strong>Invoice #543</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="3">
            1234 Main St.
        </td>
        <td align="right" colspan="2">
            Apr 12, 2011
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="3">
            Seattle, WA 98103
        </td>
        <td align="right" colspan="2">
            Client: John Smith
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="3">
            206-123-4567
        </td>
        <td align="right" colspan="2"></td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="3">

        </td>
        <td align="right" colspan="2">
            Terms: Due On Receipt
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">

        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">
            <b>Project:</b> Smith Remodel
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">

        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">
            <b>Hours Detail:</b> (20.00 Hours)
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">

        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td width="125">
            <strong>Date</strong>
        </td>
        <td width="250">
            <strong>Description</strong>
        </td>
        <td width="75">
            <strong>Hours</strong>
        </td>
        <td width="75">
            <strong>Price</strong>
        </td>
        <td width="75" align="right">
            <strong>Amount</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td valign="top">
            Jun 2, 2011
        </td>
        <td valign="top">
            Software project development. WebMail customization for ISP.
        </td>
        <td valign="top">
            4.00
        </td>
        <td valign="top">
            $100.00
        </td>
        <td valign="top" align="right">
            $400.00
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">

        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">
            <b>Items Detail:</b> (1.00 Items)
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">

        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td width="125">
            <strong>Date</strong>
        </td>
        <td width="250">
            <strong>Description</strong>
        </td>
        <td width="75">
            <strong>Quantity</strong>
        </td>
        <td width="75">
            <strong>Price</strong>
        </td>
        <td width="75" align="right">
            <strong>Amount</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td valign="top">
            Oct 15, 2011
        </td>
        <td valign="top">
            12v Halogen bulbs
        </td>
        <td valign="top">
            4.00
        </td>
        <td valign="top">
            $3.99
        </td>
        <td valign="top" align="right">
            $15.96
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="5">

        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="2" width="300">

        </td>
        <td colspan="2" width="225" align="right">
            <strong>Subtotal:</strong>
        </td>
        <td width="75" align="right">
            <strong>$415.96</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="2" width="300">

        </td>
        <td colspan="2" width="225" align="right">
            <strong>Discount -5.00%:</strong>
        </td>
        <td width="75" align="right">
            <strong>($20.80)</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="4" width="525" align="right">
            <strong>Total:</strong>
        </td>
        <td width="75" align="right">
            <strong>$395.16</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="2" width="300">
            <dl>
                <dt>
                    <strong>Payment Details:</strong>
                </dt>
                <dd>
                    May 20, 2011 Check #11223 - $2000.00
                </dd>
            </dl>
        </td>
        <td colspan="2" width="225" align="right" valign="bottom">
            <strong>Total Payments:</strong>
        </td>
        <td width="75" align="right" valign="bottom">
            <strong>$2000.00</strong>
        </td>
    </tr>
    <tr bgcolor="#FFFFFF">
        <td colspan="2" width="300">
            Thanks for your business!
        </td>
        <td colspan="2" width="225" align="right">
            <strong>Amount Due:</strong>
        </td>
        <td width="75" align="right">
            <strong>$195.16</strong>
        </td>
    </tr>
</tbody>
</table></div>
<!-- end invoice -->
</p>
</body>
Examples
This sample shows how to convert HTML invoice with CSS to .pdf file and save it to file. Please save the HTML code below as "C:\Temp\table1.html". It's used by the code samples.
C#
VB
Copy
using System;
using System.IO;
using System.Xml;
using System.Drawing;
using MailBee.Pdf;
using MailBee.Mime;
using MailBee.SmtpMail;
using iTextSharp.text;
using iTextSharp.text.pdf;

class Program
{
    static IElement ProcessDelegate(XmlNode xmlNode, IElement pdfChunk)
    {
        if (pdfChunk is PdfPCell)
        {
            ((PdfPCell)pdfChunk).BorderColor = iTextSharp.text.Color.WHITE;
            ((PdfPCell)pdfChunk).BorderWidth = 2;

            ((PdfPCell)pdfChunk).VerticalAlignment = Element.ALIGN_MIDDLE;
            ((PdfPCell)pdfChunk).HorizontalAlignment = Element.ALIGN_CENTER;

            if (xmlNode.Attributes["rowspan"] != null &&
                xmlNode.Attributes["rowspan"].Value == "2")
            {
                ((PdfPCell)pdfChunk).VerticalAlignment = Element.ALIGN_TOP;
                ((PdfPCell)pdfChunk).BackgroundColor = new iTextSharp.text.Color(0xF2F3EF);
            }
            if (xmlNode.Name == "th")
            {
                ((PdfPCell)pdfChunk).BackgroundColor = new iTextSharp.text.Color(0xF2F3EF);
            }
            else
            {
                ((PdfPCell)pdfChunk).FixedHeight = 15f;

                if (xmlNode.Attributes["colspan"] != null &&
                    xmlNode.Attributes["colspan"].Value == "17")
                {
                    ((PdfPCell)pdfChunk).BackgroundColor = iTextSharp.text.Color.WHITE;
                    ((PdfPCell)pdfChunk).HorizontalAlignment = Element.ALIGN_LEFT;
                }
                else if (xmlNode.Attributes["class"] != null &&
                    xmlNode.Attributes["class"].Value == "comp test")
                {
                    ((PdfPCell)pdfChunk).BackgroundColor = new iTextSharp.text.Color(0xBBBBBB);
                }
                else if (xmlNode.InnerText == "No")
                {
                    ((PdfPCell)pdfChunk).BackgroundColor = new iTextSharp.text.Color(0xCB000F);
                }
                else if (xmlNode.InnerText == "Yes")
                {
                    ((PdfPCell)pdfChunk).BackgroundColor = new iTextSharp.text.Color(0x00882D);
                }
                else if (xmlNode.InnerText.StartsWith("Incom"))
                {
                    ((PdfPCell)pdfChunk).BorderWidthLeft = 1;
                    ((PdfPCell)pdfChunk).BorderWidthRight = 2;
                    ((PdfPCell)pdfChunk).BorderWidthTop = 1;
                    ((PdfPCell)pdfChunk).BorderWidthBottom = 2;

                    ((PdfPCell)pdfChunk).BorderColorLeft = new iTextSharp.text.Color(0x00882D);
                    ((PdfPCell)pdfChunk).BorderColorRight = new iTextSharp.text.Color(0x00882D);
                    ((PdfPCell)pdfChunk).BorderColorTop = new iTextSharp.text.Color(0x00882D);
                    ((PdfPCell)pdfChunk).BorderColorBottom = new iTextSharp.text.Color(0x00882D);
                }
                else if (xmlNode.InnerText.StartsWith("Incor"))
                {
                    ((PdfPCell)pdfChunk).BorderWidthLeft = 1;
                    ((PdfPCell)pdfChunk).BorderWidthRight = 2;
                    ((PdfPCell)pdfChunk).BorderWidthTop = 1;
                    ((PdfPCell)pdfChunk).BorderWidthBottom = 2;

                    ((PdfPCell)pdfChunk).BorderColorLeft = new iTextSharp.text.Color(0xCB000F);
                    ((PdfPCell)pdfChunk).BorderColorRight = new iTextSharp.text.Color(0xCB000F);
                    ((PdfPCell)pdfChunk).BorderColorTop = new iTextSharp.text.Color(0xCB000F);
                    ((PdfPCell)pdfChunk).BorderColorBottom = new iTextSharp.text.Color(0xCB000F);
                }
            }
        }
        else if (pdfChunk is PdfPTable)
        {
            ((PdfPTable)pdfChunk).SetWidthPercentage(new float[] {
                                                                     40, 20, 20, 20,
                                                                     20, 20, 20, 20,
                                                                     20, 20, 30, 30,
                                                                     30, 30, 30, 30,
                                                                     30, 50}, PageSize.A4);
        }
        else if (pdfChunk is Anchor)
        {
            ((Anchor)pdfChunk).Font.Color = iTextSharp.text.Color.BLUE;
            ((Anchor)pdfChunk).Font.SetStyle(iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE);
        }

        return pdfChunk;
    }

    static void Main(string[] args)
    {
        HtmlToPdf conv = new HtmlToPdf();

        conv.OnConvertXmlNodeToPdf = new ConvertXmlNodeToPdfDelegate(ProcessDelegate);

        FontFactory.RegisterDirectory(Environment.SystemDirectory + @"\..\Fonts");
        conv.DefaultFont = FontFactory.GetFont("Arial", "windows-1252", true, 5, iTextSharp.text.Font.NORMAL);

        // Uncomment to change page size from default A4 format.

        //conv.PageRectangle = PageSize.A3;
        //conv.PageRectangle = new iTextSharp.text.Rectangle(500, 400);

        // Save .pdf file to disk.
        conv.ConvertFile(@"C:\Temp\table1.html", @"C:\Temp\table1.pdf");

        // To send .pdf file as message attachment uncomment the following block of code.

        /*MemoryStream memStream = new MemoryStream();
        conv.ConvertFile(@"C:\Temp\table1.html", memStream);

        MailMessage msg = new MailMessage();

        msg.From = new EmailAddress("bill1@domain1.com", "Bill Goodwin");
        msg.To.AddFromString("John Smith <john@host.com>");
        msg.Subject = "Comparison table 1";
        msg.BodyPlainText = "See attached table";

        memStream.Position = 0;
        msg.Attachments.Add(memStream, "table1.pdf", null, "application/pdf", null,
            NewAttachmentOptions.None, MailTransferEncoding.Base64);

        Smtp mailer = new Smtp();

        mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret");

        mailer.Message = msg;

        mailer.Send();*/
    }
}
Imports System.IO
Imports System.Xml
Imports System.Drawing
Imports MailBee.Pdf
Imports MailBee.Mime
Imports MailBee.SmtpMail
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Class Program
    Private Shared Function ProcessDelegate(ByVal xmlNode As XmlNode, ByVal pdfChunk As IElement) As IElement
        If TypeOf pdfChunk Is PdfPCell Then
            DirectCast(pdfChunk, PdfPCell).BorderColor = iTextSharp.text.Color.WHITE
            DirectCast(pdfChunk, PdfPCell).BorderWidth = 2

            DirectCast(pdfChunk, PdfPCell).VerticalAlignment = Element.ALIGN_MIDDLE
            DirectCast(pdfChunk, PdfPCell).HorizontalAlignment = Element.ALIGN_CENTER

            If xmlNode.Attributes("rowspan") IsNot Nothing AndAlso xmlNode.Attributes("rowspan").Value = "2" Then
                DirectCast(pdfChunk, PdfPCell).VerticalAlignment = Element.ALIGN_TOP
                DirectCast(pdfChunk, PdfPCell).BackgroundColor = New iTextSharp.text.Color(&HF2F3EF)
            End If
            If xmlNode.Name = "th" Then
                DirectCast(pdfChunk, PdfPCell).BackgroundColor = New iTextSharp.text.Color(&HF2F3EF)
            Else
                DirectCast(pdfChunk, PdfPCell).FixedHeight = 15.0F

                If xmlNode.Attributes("colspan") IsNot Nothing AndAlso xmlNode.Attributes("colspan").Value = "17" Then
                    DirectCast(pdfChunk, PdfPCell).BackgroundColor = iTextSharp.text.Color.WHITE
                    DirectCast(pdfChunk, PdfPCell).HorizontalAlignment = Element.ALIGN_LEFT
                ElseIf xmlNode.Attributes("class") IsNot Nothing AndAlso xmlNode.Attributes("class").Value = "comp test" Then
                    DirectCast(pdfChunk, PdfPCell).BackgroundColor = New iTextSharp.text.Color(&HBBBBBB)
                ElseIf xmlNode.InnerText = "No" Then
                    DirectCast(pdfChunk, PdfPCell).BackgroundColor = New iTextSharp.text.Color(&HCB000F)
                ElseIf xmlNode.InnerText = "Yes" Then
                    DirectCast(pdfChunk, PdfPCell).BackgroundColor = New iTextSharp.text.Color(&H882D)
                ElseIf xmlNode.InnerText.StartsWith("Incom") Then
                    DirectCast(pdfChunk, PdfPCell).BorderWidthLeft = 1
                    DirectCast(pdfChunk, PdfPCell).BorderWidthRight = 2
                    DirectCast(pdfChunk, PdfPCell).BorderWidthTop = 1
                    DirectCast(pdfChunk, PdfPCell).BorderWidthBottom = 2

                    DirectCast(pdfChunk, PdfPCell).BorderColorLeft = New iTextSharp.text.Color(&H882D)
                    DirectCast(pdfChunk, PdfPCell).BorderColorRight = New iTextSharp.text.Color(&H882D)
                    DirectCast(pdfChunk, PdfPCell).BorderColorTop = New iTextSharp.text.Color(&H882D)
                    DirectCast(pdfChunk, PdfPCell).BorderColorBottom = New iTextSharp.text.Color(&H882D)
                ElseIf xmlNode.InnerText.StartsWith("Incor") Then
                    DirectCast(pdfChunk, PdfPCell).BorderWidthLeft = 1
                    DirectCast(pdfChunk, PdfPCell).BorderWidthRight = 2
                    DirectCast(pdfChunk, PdfPCell).BorderWidthTop = 1
                    DirectCast(pdfChunk, PdfPCell).BorderWidthBottom = 2

                    DirectCast(pdfChunk, PdfPCell).BorderColorLeft = New iTextSharp.text.Color(&HCB000F)
                    DirectCast(pdfChunk, PdfPCell).BorderColorRight = New iTextSharp.text.Color(&HCB000F)
                    DirectCast(pdfChunk, PdfPCell).BorderColorTop = New iTextSharp.text.Color(&HCB000F)
                    DirectCast(pdfChunk, PdfPCell).BorderColorBottom = New iTextSharp.text.Color(&HCB000F)
                End If
            End If
        ElseIf TypeOf pdfChunk Is PdfPTable Then
            DirectCast(pdfChunk, PdfPTable).SetWidthPercentage(New Single() {40, 20, 20, 20, 20, 20, _
             20, 20, 20, 20, 30, 30, _
             30, 30, 30, 30, 30, 50}, PageSize.A4)
        ElseIf TypeOf pdfChunk Is Anchor Then
            DirectCast(pdfChunk, Anchor).Font.Color = iTextSharp.text.Color.BLUE
            DirectCast(pdfChunk, Anchor).Font.SetStyle(iTextSharp.text.Font.BOLD Or iTextSharp.text.Font.UNDERLINE)
        End If

        Return pdfChunk
    End Function

    Shared Sub Main(ByVal args As String())
        Dim conv As New HtmlToPdf

        conv.OnConvertXmlNodeToPdf = New ConvertXmlNodeToPdfDelegate(AddressOf ProcessDelegate)

        FontFactory.RegisterDirectory(Environment.SystemDirectory & "\..\Fonts")
        conv.DefaultFont = FontFactory.GetFont("Arial", "windows-1252", True, 5, iTextSharp.text.Font.NORMAL)

        ' Uncomment to change page size from default A4 format.

        'conv.PageRectangle = PageSize.A3
        'conv.PageRectangle = New iTextSharp.text.Rectangle(500, 400)

        ' Save .pdf file to disk.
        conv.ConvertFile("C:\Temp\table1.html", "C:\Temp\table1.pdf")

        ' To send .pdf file as message attachment uncomment the following block of code.

        'Dim memStream As New MemoryStream()
        'conv.ConvertFile("C:\Temp\table1.html", memStream)

        'Dim msg As New MailMessage()

        'msg.From = New EmailAddress("bill1@domain1.com", "Bill Goodwin")
        'msg.[To].AddFromString("John Smith <john@host.com>")
        'msg.Subject = "Comparison table 1"
        'msg.BodyPlainText = "See attached table"

        'memStream.Position = 0
        'msg.Attachments.Add(memStream, "table1.pdf", Nothing, "application/pdf", Nothing, NewAttachmentOptions.None, _
        ' MailTransferEncoding.Base64)

        'Dim mailer As New Smtp()

        'mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret")

        'mailer.Message = msg

        'mailer.Send()
    End Sub
End Class
Copy
<style>
/* COMPATIBILITY TABLES */

table.compatibility {
margin-left: -233px;
margin-right: -30em;
line-height: 140%;
border-bottom: 1px dotted #9198C1;
border-spacing: 0.5em;
position: relative;
    /* for IE6; if this declaration isn't there the links in
        the leftmost tds are unclickable */
}

table.compatibility caption {
border-top: 1px dotted #9198C1;
padding: 10px 0;
text-align: left;
}

table.compatibility caption select {
width: 221px;
margin-left: 5px;
margin-right: 7px;
border: 1px dotted #9198C1;
}

tr {
width: 100%;
}

table.compatibility ul,table.compatibility ol {
border: none;
margin-bottom: 0;
}

table.compatibility td {
vertical-align: top;
}

col {
width: 2em;
}

col[span="5"] {
width: 2.5em;
}

col[span="4"] {
width: 3em;
}

col[span="3"] {
width: 4em;
}

col[span="2"] {
width: 6em;
}

col[span="1"] {
width: 12em;
}

tr.compheader {
background-color: #F2F3EF;
}

tr.compheader th {
font-weight: normal;
font-size: 80%;
color: #666666;
border-top: 1px solid #666666;
}

tr.compheader th:first-child {
text-align: right;
padding: 1em;
}

tr.compheader th[colspan] {
text-align: center;
}

tr.compheader:last-child th {
border: none;
}

td.header {
background-color: #F2F3EF;
padding: 0.3em;
}

td.header h3,td.header h4 {
margin-top: 0.5em;
text-align: center;
}

td.declaration {
background-color: #F2F3EF;
text-align: right;
padding-right: 10px;
color: #666666;
width: 209px;
}

td.declaration a {
text-decoration: none;
}

div.name {
width: 209px;
font-weight: bold;
margin-bottom: 1em;
margin-top: 1em;
}

td.comp {
font-family: verdana,sans-serif;
font-size: 95%;
text-transform: lowercase;
text-align: center;
height: 3em;
vertical-align: middle !important;
}

table.keepCaps td.comp {
text-transform: none;
}

td.yes {
background-color: #00882D;
color: #ffffff;
}

td.almost {
background-color: #40A662;
color: #ffffff;
}

td.incomplete {
color: #00882D;
border: 1px solid #00882D;
}

td.alternative {
color: #666666;
border: 1px solid #666666;
}

td.untestable {
color: #006699;
}

td.minimal {
color: #CB000F;
}

td.incorrect {
color: #CB000F;
border: 1px solid #CB000F;
}

td.toomany {    /* for events comp table */
background-color: #CCE7D5;
}

td.buggy {
background-color: #DA4C57;
color: #ffffff;
}

td.severebug {
background-color: #82000A;
color: #ffffff;
}

td.no {
background-color: #CB000F;
color: #ffffff;
}

td.crash {
background-color: #535353;
font-weight: bold;
text-transform: uppercase;
color: #ffffff;
}

td.test {
background-color: #bbbbbb;
color: #ffffff;
}

b.warning {
display: block;
color: #F2F3EF;
padding: 0.5em;
margin-right: -10px;
margin-top: 0.5em;
background-color: #999999;
}

td pre {
padding: 0;
}

td pre + p {
margin-top: 2px;
}

td th,td td {
padding: 1px !important;
vertical-align: top;
color: #666666;
}

td th {
text-align: left !important;
width: 8em;
}
</style>
<body>
<table class="compatibility wide" cellspacing="5">

<col />
<col span="5" class="IE" />
<col span="4" class="FF" />
<col span="2" class="Saf" />
<col span="2" class="Chrome" />
<col span="3" class="Op" />
<col span="1" class="Rest" />

<tr class="compheader">
    <th>Selector</th>
    <th>IE 5.5</th>
    <th>IE 6</th>
    <th>IE 7</th>
    <th>IE8</th>
    <th>IE9 pr3</th>
    <th>FF 3.0</th>
    <th>FF 3.5</th>
    <th>FF 3.6</th>
    <th>FF 4b1</th>
    <th>Saf 4.0 Win</th>
    <th>Saf 5.0 Win</th>
    <th>Chrome 4</th>
    <th>Chrome 5</th>
    <th>Opera 10.10</th>
    <th>Opera 10.53</th>
    <th>Opera 10.60</th>
    <th>Konqueror 4.x</th>
</tr>

<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#block" class="page">block</a></div>
    </td>
    <td class="comp yes" colspan="5">Yes</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17">&nbsp;</td>
</tr>
<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#inline" class="page">inline</a></div>
    </td>
    <td class="comp yes" colspan="5">Yes</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17">&nbsp;</td>
</tr>
<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#none" class="page">none</a></div-->
    </td>
    <td class="comp yes" colspan="5">Yes</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17">&nbsp;</td>
</tr>
<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#inlineblock" class="page">inline-block</a></div>
    </td>
    <td class="comp no">No</td>
    <td class="comp incomplete" colspan="2">Incom<wbr />plete</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17"><ul>
        <li>IE 6/7 accepts the value only on elements with a natural <code>display: inline</code>.</li>
    </ul>
    </td>
</tr>
<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#listitem" class="page">list-item</a></div>
    </td>
    <td class="comp no">No</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17"></td>
</tr>
<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#runin" class="page">run-in</a></div>
    </td>
    <td class="comp no" colspan="3">No</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp no" colspan="4">No</td>
    <td class="comp incorrect" colspan="1">Incor<wbr>rect</td>
    <td class="comp yes" colspan="1">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17">
    <ul>
    <li>Safari, Chrome and Konqueror also support run-in when it occurs before an element with display: inline.
    This should not happen.</li>
    </ul>
    </td>
</tr>
<tr>
    <td class="declaration" rowspan="2">
        <div class="name"><a href="#table" class="page">table</a></div>
    </td>
    <td class="comp no" colspan="3">No</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="4">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="2">Yes</td>
    <td class="comp yes" colspan="3">Yes</td>
    <td class="comp test">To be tested</td>
</tr>
<tr>
    <td colspan="17"><p>Safari 3 and Chrome 1 require elements with <code>display: table</code> and <code>display: table-row</code> to show the
    cells correctly. The other browsers, including Safari 4 and Chrome 2, don't.</p></td>
</tr>
<tr class="compheader">
    <th>Selector</th>
    <th>IE 5.5</th>
    <th>IE 6</th>
    <th>IE 7</th>
    <th>IE8</th>
    <th>IE9 pr3</th>
    <th>FF 3.0</th>
    <th>FF 3.5</th>
    <th>FF 3.6</th>
    <th>FF 4b1</th>
    <th>Saf 4.0 Win</th>
    <th>Saf 5.0 Win</th>
    <th>Chrome 4</th>
    <th>Chrome 5</th>
    <th>Opera 10.10</th>
    <th>Opera 10.53</th>
    <th>Opera 10.60</th>
    <th>Konqueror 4.x</th>
</tr>
</table>
</body>
See Also

Reference

HtmlToPdf Class
HtmlToPdf Overload
MailBee.Pdf Namespace


HtmlToPdf Constructor (String)

HtmlToPdf Constructor (String)
Creates and unlocks an instance of HtmlToPdf class.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPdf(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET PDF not licensed and the supplied license key is invalid.
See Also

Reference

HtmlToPdf Class
HtmlToPdf Overload
MailBee.Pdf Namespace


HtmlToPdf Constructor (Boolean, Encoding, String, String)

HtmlToPdf Constructor (Boolean, Encoding, String, String)
Creates an instance of HtmlToPdf class for use with international charsets.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public HtmlToPdf(
    bool autodetectSourceEncoding,
    Encoding sourceEncoding,
    string pdfCharset,
    string systemFontsFolder
)
Public Sub New (
    autodetectSourceEncoding As Boolean,
    sourceEncoding As Encoding,
    pdfCharset As String,
    systemFontsFolder As String
)

Parameters

autodetectSourceEncoding
Type: SystemBoolean
If true, MailBee will try to detect the encoding of the source HTML input from META tag first; otherwise, MailBee will always use sourceEncoding even if the encoding is specified directly in the source HTML with META tag.
sourceEncoding
Type: System.TextEncoding
Denotes the encoding of the input HTML or plain-text, or if a null reference (Nothing in Visual Basic), MailBee will use the default encoding of the current system. However, if autodetectSourceEncoding set to true, MailBee will try to auto-detect the source encoding and will fall back to sourceEncoding only if META tag is missing or does not contain charset declaration.
pdfCharset
Type: SystemString
The charset name for the default output font. UTF-8, UTF-7 as long as any other Unicode charsets are not allowed. If a null reference, will detect the output charset from the input encoding (which in turn can be autodetected, can be system's default, or can be manually set).
systemFontsFolder
Type: SystemString
The path to the Windows fonts folder. If a null reference, system fonts won't be available.
Remarks

This overload contains extra parameters which let you create PDF documents in non-English languages like Turkish, Hebrew, Cyrillic, and a few others. It also lets you use Windows fonts in addition to the built-in fonts which come with the library.

The default built-in fonts support only "windows-1252" charset which covers English and other Western European languages. If you need more languages or more fonts, you'll need to enable Windows fonts. Make sure that your application has permissions to read the fonts folder. Because this folder resides in Windows folder (somewhat like "C:\WINDOWS\Fonts") and your application may have limited access to it, you may need to copy the fonts you need to a separate folder which your application can read. This may be especially important for web applications.

To refer Windows fonts folder (assuming your application has permissions to read its contents), use Environment.SystemDirectory + @"\..\Fonts" in C# or Environment.SystemDirectory & "\..\Fonts" in VB.

autodetectSourceEncoding and sourceEncoding parameters lets you specify the encoding of the source data or auto-detect it if possible. pdfCharset parameter denotes the charset name of the encoding which will be used to produce the PDF document (such as "windows-1252", etc). Internally, this value is used to pick up the correct font to load. Currently, the component supports charsets specified as windows-125x (such as "windows-1251"). Charsets which cannot be specified this way are not yet supported (this includes Far East languages like Chinese and Japanese). Also, the component does not yet support right-to-left languages (Hebrew and Arabic).

In fact, pdfCharset and systemFontsFolder parameters specify how DefaultFont is created. MailBee uses systemFontsFolder when calling iTextSharp.text.FontFactory.RegisterDirectory and passes pdfCharset as second parameter when calling iTextSharp.text.FontFactory.GetFont.

The HtmlToPdf() overload of this constructor is equivalent to HtmlToPdf(true, Encoding.UTF8, null, null) (in C# syntax).

This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).

Examples
Examples are available in HtmlToPdf topic.
See Also

Reference

HtmlToPdf Class
HtmlToPdf Overload
MailBee.Pdf Namespace


HtmlToPdf Methods

HtmlToPdf Methods

The HtmlToPdf type exposes the following members.

Methods
 | Name | Description
 | Convert(Stream, Stream) | Writes an HTML or plain-text string into a stream in PDF format.
 | Convert(Stream, String) | Writes an HTML or plain-text string into the file in PDF format.
 | Convert(String, Stream) | Writes an HTML or plain-text string into a stream in PDF format.
 | Convert(String, String) | Writes an HTML or plain-text string into the file in PDF format.
 | Convert(Uri, Stream) | Converts HTML, plain text or XML document denoted by the specified URI into the stream in PDF format.
 | Convert(Uri, String) | Converts HTML, plain text or XML document denoted by the specified URI into the file in PDF format.
 | ConvertFile(String, Stream) | Writes the file with HTML or plain-text string into a stream in PDF format.
 | ConvertFile(String, String) | Writes the file with HTML or plain-text string into the file in PDF format.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.Convert Method

HtmlToPdfConvert Method
Converts HTML or plain-text to the PDF format.
Overload List
Name | Description
Convert(Stream, Stream) | Writes an HTML or plain-text string into a stream in PDF format.
Convert(Stream, String) | Writes an HTML or plain-text string into the file in PDF format.
Convert(String, Stream) | Writes an HTML or plain-text string into a stream in PDF format.
Convert(String, String) | Writes an HTML or plain-text string into the file in PDF format.
Convert(Uri, Stream) | Converts HTML, plain text or XML document denoted by the specified URI into the stream in PDF format.
Convert(Uri, String) | Converts HTML, plain text or XML document denoted by the specified URI into the file in PDF format.
Top
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.Convert Method (Stream, Stream)

HtmlToPdfConvert Method (Stream, Stream)
Writes an HTML or plain-text string into a stream in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Convert(
    Stream sourceStream,
    Stream outputStream
)
Public Sub Convert (
    sourceStream As Stream,
    outputStream As Stream
)

Parameters

sourceStream
Type: System.IOStream
The input stream containing HTML or plain-text data.
outputStream
Type: System.IOStream
The output stream to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | sourceStream or outputStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
Remarks
If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain text; otherwise, XMLized XHTML.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

HtmlToPdf Class
Convert Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.Convert Method (Stream, String)

HtmlToPdfConvert Method (Stream, String)
Writes an HTML or plain-text string into the file in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Convert(
    Stream sourceStream,
    string pdfFile
)
Public Sub Convert (
    sourceStream As Stream,
    pdfFile As String
)

Parameters

sourceStream
Type: System.IOStream
The input stream containing HTML or plain-text data.
pdfFile
Type: SystemString
The filename to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | sourceStream or pdfFile is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
Remarks
If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain text; otherwise, XMLized XHTML.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

HtmlToPdf Class
Convert Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.Convert Method (String, Stream)

HtmlToPdfConvert Method (String, Stream)
Writes an HTML or plain-text string into a stream in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Convert(
    string source,
    Stream outputStream
)
Public Sub Convert (
    source As String,
    outputStream As Stream
)

Parameters

source
Type: SystemString
The input string containing HTML or plain-text data.
outputStream
Type: System.IOStream
The output stream to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | source or outputStream is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
Remarks

If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain text; otherwise, XMLized XHTML.

If your source is BodyHtmlText and the message contains embedded pictures, you need to save them first (like in the example below).

Examples
This example loads an e-mail from file (we assume it's HTML e-mail), saves all embedded pictures (if any) into a temporary folder it creates, then generates a PDF file and removes the temp folder.
C#
VB
Copy
using System;
using System.IO;
using MailBee;
using MailBee.Mime;
using MailBee.Pdf;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\source.eml");
        HtmlToPdf htmlConv = new HtmlToPdf();
        FileStream fsPdf = new FileStream(@"C:\Temp\result.pdf", FileMode.Create);
        msg.Parser.WorkingFolder = System.IO.Path.GetTempPath();
        try
        {
            string htmlWithRealImgLinks = msg.GetHtmlAndSaveRelatedFiles(null, VirtualMappingType.NonWeb,
                MessageFolderBehavior.CreateAndDelete);
            htmlConv.Convert(htmlWithRealImgLinks, fsPdf);
        }
        finally
        {
            fsPdf.Close();
            msg.Dispose();
        }
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pdf
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(args As String())
        Dim msg As New MailMessage()
        msg.LoadMessage("C:\Temp\0.eml")
        Dim htmlConv As New HtmlToPdf()
        Dim fsPdf As New FileStream("C:\Temp\result.pdf", FileMode.Create)
        msg.Parser.WorkingFolder = System.IO.Path.GetTempPath()
        Try
            Dim htmlWithRealImgLinks As String = msg.GetHtmlAndSaveRelatedFiles(Nothing, _
                VirtualMappingType.NonWeb, MessageFolderBehavior.CreateAndDelete)
            htmlConv.Convert(htmlWithRealImgLinks, fsPdf)
        Finally
            fsPdf.Close()
            msg.Dispose()
        End Try
    End Sub
End Class
See Also

Reference

HtmlToPdf Class
Convert Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.Convert Method (String, String)

HtmlToPdfConvert Method (String, String)
Writes an HTML or plain-text string into the file in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Convert(
    string source,
    string pdfFile
)
Public Sub Convert (
    source As String,
    pdfFile As String
)

Parameters

source
Type: SystemString
The input string containing HTML or plain-text data.
pdfFile
Type: SystemString
The filename to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | source or pdfFile is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
Remarks

If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain-text; otherwise, XMLized XHTML.

If your source is BodyHtmlText and the message contains embedded pictures, you need to save them first (like in the example below).

Examples
This example loads an e-mail from file (we assume it's HTML e-mail), saves all embedded pictures (if any) into a temporary folder it creates, then generates a PDF file and removes the temp folder.
C#
VB
Copy
using System;
using System.IO;
using MailBee;
using MailBee.Mime;
using MailBee.Pdf;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Temp\source.eml");
        HtmlToPdf htmlConv = new HtmlToPdf();
        msg.Parser.WorkingFolder = Path.GetTempPath();
        try
        {
            string htmlWithRealImgLinks = msg.GetHtmlAndSaveRelatedFiles(null, VirtualMappingType.NonWeb,
                MessageFolderBehavior.CreateAndDelete);
            htmlConv.Convert(htmlWithRealImgLinks, @"C:\Temp\result.pdf");
        }
        finally
        {
            msg.Dispose();
        }
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pdf
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(args As String())
        Dim msg As New MailMessage()
        msg.LoadMessage("C:\Temp\source.eml")
        Dim htmlConv As New HtmlToPdf()
        msg.Parser.WorkingFolder = Path.GetTempPath()
        Try
            Dim htmlWithRealImgLinks As String = msg.GetHtmlAndSaveRelatedFiles(Nothing, _
                VirtualMappingType.NonWeb, MessageFolderBehavior.CreateAndDelete)
            htmlConv.Convert(htmlWithRealImgLinks, "C:\Temp\result.pdf")
        Finally
            msg.Dispose()
        End Try
    End Sub
End Class
See Also

Reference

HtmlToPdf Class
Convert Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.Convert Method (Uri, Stream)

HtmlToPdfConvert Method (Uri, Stream)
Converts HTML, plain text or XML document denoted by the specified URI into the stream in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Convert(
    Uri sourceUri,
    Stream outputStream
)
Public Sub Convert (
    sourceUri As Uri,
    outputStream As Stream
)

Parameters

sourceUri
Type: SystemUri
An Uri object with address of web page containing HTML or plain-text data.
outputStream
Type: System.IOStream
The output stream to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | sourceUri or outputStream is a null reference (Nothing in Visual Basic).
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
MailBeeWebException | HTTP connection error occurred.
Remarks
If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain text; otherwise, XMLized XHTML.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

HtmlToPdf Class
Convert Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.Convert Method (Uri, String)

HtmlToPdfConvert Method (Uri, String)
Converts HTML, plain text or XML document denoted by the specified URI into the file in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Convert(
    Uri sourceUri,
    string pdfFile
)
Public Sub Convert (
    sourceUri As Uri,
    pdfFile As String
)

Parameters

sourceUri
Type: SystemUri
An Uri oject with address of web page containing HTML or plain-text data.
pdfFile
Type: SystemString
The filename to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | sourceUri or pdfFile is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
MailBeeWebException | HTTP connection error occurred.
Remarks
If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain-text; otherwise, XMLized XHTML.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

HtmlToPdf Class
Convert Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.ConvertFile Method

HtmlToPdfConvertFile Method
Converts file with HTML or plain-text to the PDF format.
Overload List
Name | Description
ConvertFile(String, Stream) | Writes the file with HTML or plain-text string into a stream in PDF format.
ConvertFile(String, String) | Writes the file with HTML or plain-text string into the file in PDF format.
Top
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.ConvertFile Method (String, Stream)

HtmlToPdfConvertFile Method (String, Stream)
Writes the file with HTML or plain-text string into a stream in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ConvertFile(
    string sourceFile,
    Stream outputStream
)
Public Sub ConvertFile (
    sourceFile As String,
    outputStream As Stream
)

Parameters

sourceFile
Type: SystemString
The path to the file containing HTML or plain-text data.
outputStream
Type: System.IOStream
The output stream to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | sourceFile or outputStream is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
Remarks
If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain-text; otherwise, XMLized XHTML.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

HtmlToPdf Class
ConvertFile Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf.ConvertFile Method (String, String)

HtmlToPdfConvertFile Method (String, String)
Writes the file with HTML or plain-text string into the file in PDF format.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ConvertFile(
    string sourceFile,
    string pdfFile
)
Public Sub ConvertFile (
    sourceFile As String,
    pdfFile As String
)

Parameters

sourceFile
Type: SystemString
The path to the file containing HTML or plain-text data.
pdfFile
Type: SystemString
The filename to write .pdf data into.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | sourceFile or pdfFile is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeStreamException | A stream error occurred.
MailBeeIOException | An I/O error occurred.
Remarks
If SourceType is Html (default value), the input is considered HTML; if SourceType is Text the input is considered plain text; otherwise, XMLized XHTML.
Examples
See HtmlToPdf topic for examples.
See Also

Reference

HtmlToPdf Class
ConvertFile Overload
MailBee.Pdf Namespace
HtmlToPdfSourceType


HtmlToPdf Properties

HtmlToPdf Properties

The HtmlToPdf type exposes the following members.

Properties
 | Name | Description
Public property | DefaultFont | Gets or sets default font for creating .pdf document with specified name or filename, encoding and size as iTextSharp.text.Font object.
Public property | DefaultFontSize | Gets or sets font size for the internal default font.
 | LicenseKey | Obsolete. Assigns the license key.
 | OnConvertXmlNodeToPdf | Gets or sets the application-supplied method for fine-tuning of source to PDF conversion.
Public property | OnProcessImagePath | Gets or sets the application-supplied method for changing path or URI or URL to the image.
Public property | PageRectangle | Gets or sets page size of .pdf document as iTextSharp.text.Rectangle object.
Public property | SourceType | Gets or sets the format of the input data for the conversion.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | UseBlackAndWhiteStyle | Enables conversion of colored HTML document to black and white PDF document.
Top
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.DefaultFont Property

HtmlToPdfDefaultFont Property
Gets or sets default font for creating .pdf document with specified name or filename, encoding and size as iTextSharp.text.Font object.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Font DefaultFont { get; set; }
Public Property DefaultFont As Font
    Get
    Set

Property Value

Type: Font
The default font is "Helvetica" with size 8 and normal style.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

iTextSharp library contains the following fonts inside, which can be loaded by name:

  • Courier-Bold
  • Courier-BoldOblique
  • Courier-Oblique
  • Courier
  • Helvetica-Bold
  • Helvetica-BoldOblique
  • Helvetica-Oblique
  • Helvetica
  • Symbol
  • Times-Bold
  • Times-BoldItalic
  • Times-Italic
  • Times-Roman
  • ZapfDingbats

The internal fonts do not support multi-language encoding and thus the user should load the font which has proper encoding manually.

This property can be assigned in the following ways:

Copy
DefaultFont = FontFactory.GetFont("Helvetica", _defaultFontSize, iTextSharp.text.Font.NORMAL);
or
Copy
FontFactory.RegisterDirectory(Environment.SystemDirectory + @"\..\Fonts");
DefaultFont = FontFactory.GetFont("Arial", "windows-1255", <span style="color: blue;">true</span>, (<span style="color: blue;">float</span>)10, iTextSharp.text.Font.ITALIC);
or
Copy
BaseFont baseFont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
DefaultFont = <span style="color: blue;">new</span> iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.DefaultFontSize Property

HtmlToPdfDefaultFontSize Property
Gets or sets font size for the internal default font.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public float DefaultFontSize { get; set; }
Public Property DefaultFontSize As Single
    Get
    Set

Property Value

Type: Single
The default value is 8.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.LicenseKey Property

HtmlToPdfLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.OnConvertXmlNodeToPdf Property

HtmlToPdfOnConvertXmlNodeToPdf Property
Gets or sets the application-supplied method for fine-tuning of source to PDF conversion.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ConvertXmlNodeToPdfDelegate OnConvertXmlNodeToPdf { get; set; }
Public Property OnConvertXmlNodeToPdf As ConvertXmlNodeToPdfDelegate
    Get
    Set

Property Value

Type: ConvertXmlNodeToPdfDelegate
The reference to the delegate to be called in case of source to PDF conversion (where the source is HTML, XHTML, plain-text), or a null reference (Nothing in Visual Basic) if the delegate is not set.
Remarks

The ultimate source for the converter is XMLized XHTML as it's a well-structured XML document. For instance, when you convert HTML into PDF, the component first creates XML version of that HTML (actually, XHTML with XML headers) and then applies XML-to-PDF conversion. That XML is a tree of nodes which then get converted into PDF.

Whenever an XML node is about to be converted to PDF, this delegate is called so that you can adjust how the corresponding PDF node will be generated. Refer to PdfSourceType topic for details.
Examples
See 2nd sample in HtmlToPdf topic for example.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.OnProcessImagePath Property

HtmlToPdfOnProcessImagePath Property
Gets or sets the application-supplied method for changing path or URI or URL to the image.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ProcessImagePathDelegate OnProcessImagePath { get; set; }
Public Property OnProcessImagePath As ProcessImagePathDelegate
    Get
    Set

Property Value

Type: ProcessImagePathDelegate
The reference to the delegate to be called in case of image processing, or a null reference (Nothing in Visual Basic) if the delegate is not set.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.PageRectangle Property

HtmlToPdfPageRectangle Property
Gets or sets page size of .pdf document as iTextSharp.text.Rectangle object.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Rectangle PageRectangle { get; set; }
Public Property PageRectangle As Rectangle
    Get
    Set

Property Value

Type: Rectangle
The default value is iTextSharp.text.PageSize.A4.
Remarks
This property can be assigned with either iTextSharp.text.Rectangle constructor or iTextSharp.text.PageSize predefined constants.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.SourceType Property

HtmlToPdfSourceType Property
Gets or sets the format of the input data for the conversion.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public PdfSourceType SourceType { get; set; }
Public Property SourceType As PdfSourceType
    Get
    Set

Property Value

Type: PdfSourceType
The default value is Html.
Remarks

Set this property to Text if the input is plain-text.

If this value is Xhtml, you must guarantee that the input contains well-formed XHTML within XML container. HtmlAgilityPack will not be used to convert input HTML into XML with XHTML contents, and MailBee will directly pass this XML to the PDF generator. See PdfSourceType topic for details.

See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.TrialDaysLeft Property

HtmlToPdfTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value indicating the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


HtmlToPdf.UseBlackAndWhiteStyle Property

HtmlToPdfUseBlackAndWhiteStyle Property
Enables conversion of colored HTML document to black and white PDF document.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool UseBlackAndWhiteStyle { get; set; }
Public Property UseBlackAndWhiteStyle As Boolean
    Get
    Set

Property Value

Type: Boolean
true if the output .pdf file should be converted to black-and-white style; otherwise, false. The default value is false.
See Also

Reference

HtmlToPdf Class
MailBee.Pdf Namespace


PdfSourceType Enumeration

PdfSourceType Enumeration
Defines the available values for HtmlToPdf.SourceType property to specify the type of source data for conversion to PDF document.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum PdfSourceType
Public Enumeration PdfSourceType
Members
Member name | Value | Description
Html | 0 | Use HTML as input data source. HtmlAgilityPack will be used to make the input XHTML-compliant XML.
Xhtml | 1 | Use XHTML wrapped in XML (XMLized XHTML) as input data source. HtmlAgilityPack won't be used as the input is already expected to be XML-compliant XHTML.
Text | 2 | Use plain text as input data source. Will wrap plain-text into XMLized XHTML as shown in the second example above.
Remarks

Internally, the component always takes XML on input in order to produce PDF content. This XML is much like XHTML with <xml> element and some restrictions like the necessity to encode styles and javascript in CDATA blocks. MailBee automatically does all the required conversion of any HTML into this XHTML-over-XML format. However, your application can provide this XHTML-over-XML on input to avoid such conversion in MailBee. In this case, use Xhtml value for SourceType property.

This can be useful in case if you want to use OnConvertXmlNodeToPdf delegate to precisely control how some nodes of the input data are converted from XML to PDF. In this case, providing HTML input may not be sufficient as you may not know which nodes will exist in the document after HTML-to-XML conversion. Providing the input which can be consumed by the PDF producer without any additional conversion of HTML into XML solves this problem - OnConvertXmlNodeToPdf delegate will fire on the same nodes your document contains.

Note Note
PDF functionality resides in a separate MailBee.NET.PDF.dll. It's available for .NET Framework only (not available for .NET Core or UWP). It also depends on iTextSharp.dllHtmlAgilityPack.dll. In case of Nuget, you need to install a separate MailBee.NET.PDF package (includes all the required DLLs).
Examples
This C# code shows the logic of HTML-to-XML conversion. To use HtmlDocument, you must import HtmlAgilityPack namespace and reference its .DLL (shipped with the component). You can use this snippet to prepare your data or get the idea which data MailBee expects when SourceType is Xhtml.
C#
Copy
HtmlDocument html = new HtmlDocument();
html.OptionSupportOptionalEndTags = true;
html.LoadHtml(source);
html.OptionOutputAsXml = true;

StringWriter sw = new StringWriter();
html.Save(sw);

xml = sw.ToString();
In case if the input is plain-text, text-to-XML transformation is as follows:
C#
Copy
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?><span><html><body><pre>");
sb.Append(HttpUtility.HtmlEncode(source));
sb.Append("</pre></body></html></span>");
xml = sb.ToString();
See Also

Reference

MailBee.Pdf Namespace


ProcessImagePathDelegate Delegate

ProcessImagePathDelegate Delegate
Defines the delegate for processing of absent images or images with incorrect path.

Namespace: MailBee.Pdf
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate string ProcessImagePathDelegate(
    string imgPath
)
Public Delegate Function ProcessImagePathDelegate (
    imgPath As String
) As String

Parameters

imgPath
Type: SystemString
A string with URI or full path to the image.

Return Value

Type: String
A string with URI or full path to the image corrected by the application.
Remarks
To set this delegate, use OnProcessImagePath property.
See Also

Reference

MailBee.Pdf Namespace


MailBee.Pop3Mail Namespace

MailBee.Pop3Mail Namespace

MailBee.Pop3Mail namespace contains classes and enumerations which can be used by your applications to download mail messages from a POP3 server. Another supported operations are deleting mail from the server, sending custom commands to the server, authenticating using secure methods, and more.

MailBee supports POP3 PIPELINING, which greatly (up to 1000% and more) increases performance of downloading or deleting multiple messages.

Pop3Mail.Pop3 (main class of this namespace) is declared as a component, which means you can also just drop it onto your application form instead of creating an instance in the code.

"Quick" methods are also supported, which allows you to download mail from the server in a single line of code.

The component has built-in support for secure connections (TLS/SSL) and proxy servers (SOCKS4/SOCKS5/HTTP).

In UWP apps, use async methods. This platform has very limited sync I/O support.

Classes
 | Class | Description
Public class | MailBeePop3LoginBadCredentialsException | The exception that is thrown when the POP3 server reports the given user account name and/or password is incorrect.
Public class | MailBeePop3LoginBadMethodException | The exception that is thrown when the POP3 server reports the given SASL authentication method is not supported and use of another authentication methods is not allowed by the application.
Public class | MailBeePop3LoginNegativeResponseException | An abstract parent for all exceptions which indicate the POP3 server replied with a negative response during authentication of the user.
Public class | MailBeePop3NegativeResponseException | The exception that is thrown when the POP3 server responds with a negative reply (i.e. -ERR).
Public class | MailBeePop3OptionalCommandNotSupportedException | The exception that is thrown when the POP3 server responds with a negative reply to an optional POP3 command.
 | Pop3 | Provides properties and methods for connecting to a POP3 server and downloading and deleting e-mail messages from a user account inbox.
Public class | Pop3MessageDataChunkReceivedEventArgs | Contains the event data for MessageDataChunkReceived event.
Public class | Pop3MessageDownloadedEventArgs | Contains the event data for MessageDownloaded event.
Delegates
 | Delegate | Description
Public delegate | Pop3MessageDataChunkReceivedEventHandler | Represents the method that will handle MessageDataChunkReceived event.
Public delegate | Pop3MessageDownloadedEventHandler | Represents the method that will handle MessageDownloaded event.
Enumerations
 | Enumeration | Description
Public enumeration | Pop3InboxPreloadOptions | Specifies which elements of the mailbox statistics to download immediately after successful logging in the mailbox.


Pop3MessageDataChunkReceivedEventArgs Class

Pop3MessageDataChunkReceivedEventArgs Class
Contains the event data for MessageDataChunkReceived event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.Pop3MailPop3MessageDataChunkReceivedEventArgs

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Pop3MessageDataChunkReceivedEventArgs : CommonEventArgs
Public Class Pop3MessageDataChunkReceivedEventArgs
    Inherits CommonEventArgs

The Pop3MessageDataChunkReceivedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | BytesJustReceived | Gets the number of bytes received from the server during the operation which raised the current event.
Public property | EstimatedDataLength | Gets the expected length (in bytes) of the source data of the message being downloaded.
Public property | MessageNumber | Gets the message number (ordinal position in the mailbox) of the downloaded message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | TotalBytesReceived | Gets the total length (in bytes) of the already received data of the message currently being downloaded.
Top
See Also

Reference

MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventArgs Methods

Pop3MessageDataChunkReceivedEventArgs Methods

The Pop3MessageDataChunkReceivedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Pop3MessageDataChunkReceivedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventArgs Properties

Pop3MessageDataChunkReceivedEventArgs Properties

The Pop3MessageDataChunkReceivedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | BytesJustReceived | Gets the number of bytes received from the server during the operation which raised the current event.
Public property | EstimatedDataLength | Gets the expected length (in bytes) of the source data of the message being downloaded.
Public property | MessageNumber | Gets the message number (ordinal position in the mailbox) of the downloaded message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | TotalBytesReceived | Gets the total length (in bytes) of the already received data of the message currently being downloaded.
Top
See Also

Reference

Pop3MessageDataChunkReceivedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventArgs.BytesJustReceived Property

Pop3MessageDataChunkReceivedEventArgsBytesJustReceived Property
Gets the number of bytes received from the server during the operation which raised the current event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int BytesJustReceived { get; }
Public ReadOnly Property BytesJustReceived As Integer
    Get

Property Value

Type: Int32
The number of bytes received from the server during the operation which raised the current event.
See Also

Reference

Pop3MessageDataChunkReceivedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventArgs.EstimatedDataLength Property

Pop3MessageDataChunkReceivedEventArgsEstimatedDataLength Property
Gets the expected length (in bytes) of the source data of the message being downloaded.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int EstimatedDataLength { get; }
Public ReadOnly Property EstimatedDataLength As Integer
    Get

Property Value

Type: Int32
The expected length (in bytes) of the source data of the message being downloaded, or -1 if no estimation can be made.
Remarks
This property can be used to evaluate download progress of the current message being downloaded. However, its value is not 100% accurate because it's taken from the message size as reported by the server while actual length of the server response containing the message data is always greater (by 1-2%) due to presence some additional information in the response.
Note Note
If partial messages are downloaded (such as message headers), this property returns -1, since the POP3 protocol has no feature to learn the length of a message header without downloading it. Only lengths of entire messages can be obtained. However, usually it's not a problem - since a message header is usually short, it is, anyway, received in a single network operation (which usually delivers 4-8 Kbytes of data).
See Also

Reference

Pop3MessageDataChunkReceivedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventArgs.MessageNumber Property

Pop3MessageDataChunkReceivedEventArgsMessageNumber Property
Gets the message number (ordinal position in the mailbox) of the downloaded message.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageNumber { get; }
Public ReadOnly Property MessageNumber As Integer
    Get

Property Value

Type: Int32
An integer value in the range 1 to InboxMessageCount, representing the message number of the downloaded message.
See Also

Reference

Pop3MessageDataChunkReceivedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventArgs.TotalBytesReceived Property

Pop3MessageDataChunkReceivedEventArgsTotalBytesReceived Property
Gets the total length (in bytes) of the already received data of the message currently being downloaded.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TotalBytesReceived { get; }
Public ReadOnly Property TotalBytesReceived As Integer
    Get

Property Value

Type: Int32
The total length (in bytes) of the already received data of the message currently being downloaded, including the bytes just received.
See Also

Reference

Pop3MessageDataChunkReceivedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDataChunkReceivedEventHandler Delegate

Pop3MessageDataChunkReceivedEventHandler Delegate
Represents the method that will handle MessageDataChunkReceived event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void Pop3MessageDataChunkReceivedEventHandler(
    Object sender,
    Pop3MessageDataChunkReceivedEventArgs e
)
Public Delegate Sub Pop3MessageDataChunkReceivedEventHandler (
    sender As Object,
    e As Pop3MessageDataChunkReceivedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.Pop3MailPop3MessageDataChunkReceivedEventArgs
See Also

Reference

MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventArgs Class

Pop3MessageDownloadedEventArgs Class
Contains the event data for MessageDownloaded event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.Pop3MailPop3MessageDownloadedEventArgs

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Pop3MessageDownloadedEventArgs : CommonEventArgs
Public Class Pop3MessageDownloadedEventArgs
    Inherits CommonEventArgs

The Pop3MessageDownloadedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DataLength | Gets the length (in bytes) of the server response containing the downloaded message data.
Public property | DownloadedMessage | Gets or sets the mail message which had been downloaded.
Public property | MessageNumber | Gets the message number (ordinal position in the mailbox) of the downloaded message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventArgs Methods

Pop3MessageDownloadedEventArgs Methods

The Pop3MessageDownloadedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Pop3MessageDownloadedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventArgs Properties

Pop3MessageDownloadedEventArgs Properties

The Pop3MessageDownloadedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | DataLength | Gets the length (in bytes) of the server response containing the downloaded message data.
Public property | DownloadedMessage | Gets or sets the mail message which had been downloaded.
Public property | MessageNumber | Gets the message number (ordinal position in the mailbox) of the downloaded message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

Pop3MessageDownloadedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventArgs.DataLength Property

Pop3MessageDownloadedEventArgsDataLength Property
Gets the length (in bytes) of the server response containing the downloaded message data.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int DataLength { get; }
Public ReadOnly Property DataLength As Integer
    Get

Property Value

Type: Int32
The length (in bytes) of the server response containing the downloaded message data.
Remarks
The length of the server response containing the downloaded message data is always greater than the length of the message data itself (usually by 1-2%). This is due to presence some additional information in the response, which is then stripped away.
See Also

Reference

Pop3MessageDownloadedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventArgs.DownloadedMessage Property

Pop3MessageDownloadedEventArgsDownloadedMessage Property
Gets or sets the mail message which had been downloaded.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DownloadedMessage { get; set; }
Public Property DownloadedMessage As MailMessage
    Get
    Set

Property Value

Type: MailMessage
A reference to the mail message which had been just downloaded, or a null reference (Nothing in Visual Basic) if there had been no message data in the server response.
Remarks

When this property value is a null reference, this usually means the mail server replied with a negative response instead of a message data. For instance, this may happen on attempt to download a messsage which had already been marked as deleted during the current POP3 session. In this case, the corresponding method of Pop3 class which had been used to download message(s) will throw an exception after the method has finished receiving data from the POP3 server.

The developer can also manually set this property value to a null reference to avoid inclusion of this message into the resulting MailMessageCollection. For methods returning a single message (such as DownloadEntireMessage(Int32)), the result will be a null reference.

Setting this property to a null reference is also useful for downloading very large number of messages at once (when they won't fit in memory). In this case, the developer can save each message to database/disk in MessageDownloaded event handler and then set DownloadedMessage to a null reference to free the resources. This is efficient and memory conservative appoach.

See Also

Reference

Pop3MessageDownloadedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventArgs.MessageNumber Property

Pop3MessageDownloadedEventArgsMessageNumber Property
Gets the message number (ordinal position in the mailbox) of the downloaded message.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MessageNumber { get; }
Public ReadOnly Property MessageNumber As Integer
    Get

Property Value

Type: Int32
An integer value in the range 1 to InboxMessageCount, representing the message number of the downloaded message.
See Also

Reference

Pop3MessageDownloadedEventArgs Class
MailBee.Pop3Mail Namespace


Pop3MessageDownloadedEventHandler Delegate

Pop3MessageDownloadedEventHandler Delegate
Represents the method that will handle MessageDownloaded event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void Pop3MessageDownloadedEventHandler(
    Object sender,
    Pop3MessageDownloadedEventArgs e
)
Public Delegate Sub Pop3MessageDownloadedEventHandler (
    sender As Object,
    e As Pop3MessageDownloadedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.Pop3MailPop3MessageDownloadedEventArgs
See Also

Reference

MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException Class

MailBeePop3LoginBadCredentialsException Class
The exception that is thrown when the POP3 server reports the given user account name and/or password is incorrect.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.Pop3MailMailBeePop3NegativeResponseException
MailBee.Pop3MailMailBeePop3LoginNegativeResponseException
MailBee.Pop3MailMailBeePop3LoginBadCredentialsException

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeePop3LoginBadCredentialsException : MailBeePop3LoginNegativeResponseException,
    IMailBeeLoginBadCredentialsException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeePop3LoginBadCredentialsException
    Inherits MailBeePop3LoginNegativeResponseException
    Implements IMailBeeLoginBadCredentialsException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException

The MailBeePop3LoginBadCredentialsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePop3LoginBadCredentialsException | Initializes a new instance of the MailBeePop3LoginBadCredentialsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used during the authentication.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Password | Gets the account password which was used during the authentication.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException Constructor

MailBeePop3LoginBadCredentialsException Constructor
Initializes a new instance of the MailBeePop3LoginBadCredentialsException class

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePop3LoginBadCredentialsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePop3LoginBadCredentialsException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException Methods

MailBeePop3LoginBadCredentialsException Methods

The MailBeePop3LoginBadCredentialsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3LoginBadCredentialsException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException Properties

MailBeePop3LoginBadCredentialsException Properties

The MailBeePop3LoginBadCredentialsException type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used during the authentication.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Password | Gets the account password which was used during the authentication.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeePop3LoginBadCredentialsException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException.AccountName Property

MailBeePop3LoginBadCredentialsExceptionAccountName Property
Gets the account name which was used during the authentication.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; }
Public ReadOnly Property AccountName As String
    Get

Property Value

Type: String
The account name which was used during the authentication.

Implements

IMailBeeLoginBadCredentialsExceptionAccountName
See Also

Reference

MailBeePop3LoginBadCredentialsException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException.Password Property

MailBeePop3LoginBadCredentialsExceptionPassword Property
Gets the account password which was used during the authentication.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; }
Public ReadOnly Property Password As String
    Get

Property Value

Type: String
The account password which was used during the authentication.

Implements

IMailBeeLoginBadCredentialsExceptionPassword
See Also

Reference

MailBeePop3LoginBadCredentialsException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadCredentialsException Events

MailBeePop3LoginBadCredentialsException Events

The MailBeePop3LoginBadCredentialsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3LoginBadCredentialsException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadMethodException Class

MailBeePop3LoginBadMethodException Class
The exception that is thrown when the POP3 server reports the given SASL authentication method is not supported and use of another authentication methods is not allowed by the application.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.Pop3MailMailBeePop3NegativeResponseException
MailBee.Pop3MailMailBeePop3LoginNegativeResponseException
MailBee.Pop3MailMailBeePop3LoginBadMethodException

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeePop3LoginBadMethodException : MailBeePop3LoginNegativeResponseException,
    IMailBeeLoginBadMethodException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeePop3LoginBadMethodException
    Inherits MailBeePop3LoginNegativeResponseException
    Implements IMailBeeLoginBadMethodException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException

The MailBeePop3LoginBadMethodException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePop3LoginBadMethodException | Initializes a new instance of the MailBeePop3LoginBadMethodException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
By default, if a particular SASL authentication method is not supported by the server, MailBee switches to the previous method listed in authMethods parameter of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method. If no more methods left, MailBeeLoginNoSupportedMethodsException is thrown. However, if UseSingleMethodOnly flag is set in authOptions parameter of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method, MailBee will not try other methods. Instead, if will immediately throw MailBeePop3LoginBadMethodException.
Note Note
This exception does not indicate that authentication using the given method failed. Instead, it indicates the method itself is not supported by the server. When the method is supported but the authentication using this method fails (invalid account name/password), MailBee does not try another methods (there would be no sense if it did), and throws MailBeePop3LoginBadCredentialsException.
This exception may also occur if FipsMode is enabled and the given authentication method is not FIPS-compliant.
See Also

Reference

MailBee.Pop3Mail Namespace
MailBeeAuthenticationMethods
MailBeeAuthenticationOptions
MailBee.Pop3MailMailBeePop3LoginBadCredentialsException


MailBeePop3LoginBadMethodException Constructor

MailBeePop3LoginBadMethodException Constructor
Initializes a new instance of the MailBeePop3LoginBadMethodException class

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePop3LoginBadMethodException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePop3LoginBadMethodException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadMethodException Methods

MailBeePop3LoginBadMethodException Methods

The MailBeePop3LoginBadMethodException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3LoginBadMethodException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadMethodException Properties

MailBeePop3LoginBadMethodException Properties

The MailBeePop3LoginBadMethodException type exposes the following members.

Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeePop3LoginBadMethodException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadMethodException.BadMethod Property

MailBeePop3LoginBadMethodExceptionBadMethod Property
Gets the authentication method which was rejected by the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods BadMethod { get; }
Public ReadOnly Property BadMethod As AuthenticationMethods
    Get

Property Value

Type: AuthenticationMethods
A AuthenticationMethods value having only a single bit set, which indicates the method which is requested by the application but not supported by the server.

Implements

IMailBeeLoginBadMethodExceptionBadMethod
Remarks
Although AuthenticationMethods allows bitwise combination of its member values, the result returned by this property always contains a single member value indicating the specific method which was rejected.
See Also

Reference

MailBeePop3LoginBadMethodException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginBadMethodException Events

MailBeePop3LoginBadMethodException Events

The MailBeePop3LoginBadMethodException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3LoginBadMethodException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginNegativeResponseException Class

MailBeePop3LoginNegativeResponseException Class
An abstract parent for all exceptions which indicate the POP3 server replied with a negative response during authentication of the user.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.Pop3MailMailBeePop3NegativeResponseException
MailBee.Pop3MailMailBeePop3LoginNegativeResponseException
MailBee.Pop3MailMailBeePop3LoginBadCredentialsException
MailBee.Pop3MailMailBeePop3LoginBadMethodException

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeePop3LoginNegativeResponseException : MailBeePop3NegativeResponseException,
    IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public MustInherit Class MailBeePop3LoginNegativeResponseException
    Inherits MailBeePop3NegativeResponseException
    Implements IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The MailBeePop3LoginNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePop3LoginNegativeResponseException | Initializes a new instance of the MailBeePop3LoginNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Pop3Mail Namespace


MailBeePop3LoginNegativeResponseException Constructor

MailBeePop3LoginNegativeResponseException Constructor
Initializes a new instance of the MailBeePop3LoginNegativeResponseException class

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePop3LoginNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePop3LoginNegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginNegativeResponseException Methods

MailBeePop3LoginNegativeResponseException Methods

The MailBeePop3LoginNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3LoginNegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginNegativeResponseException Properties

MailBeePop3LoginNegativeResponseException Properties

The MailBeePop3LoginNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeePop3LoginNegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3LoginNegativeResponseException Events

MailBeePop3LoginNegativeResponseException Events

The MailBeePop3LoginNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3LoginNegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3NegativeResponseException Class

MailBeePop3NegativeResponseException Class
The exception that is thrown when the POP3 server responds with a negative reply (i.e. -ERR).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.Pop3MailMailBeePop3NegativeResponseException
MailBee.Pop3MailMailBeePop3LoginNegativeResponseException
MailBee.Pop3MailMailBeePop3OptionalCommandNotSupportedException

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeePop3NegativeResponseException : MailBeeEmailProtocolNegativeResponseException
<SerializableAttribute>
Public Class MailBeePop3NegativeResponseException
    Inherits MailBeeEmailProtocolNegativeResponseException

The MailBeePop3NegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePop3NegativeResponseException | Initializes a new instance of the MailBeePop3NegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Pop3Mail Namespace


MailBeePop3NegativeResponseException Constructor

MailBeePop3NegativeResponseException Constructor
Initializes a new instance of the MailBeePop3NegativeResponseException class

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePop3NegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePop3NegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3NegativeResponseException Methods

MailBeePop3NegativeResponseException Methods

The MailBeePop3NegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3NegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3NegativeResponseException Properties

MailBeePop3NegativeResponseException Properties

The MailBeePop3NegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeePop3NegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3NegativeResponseException Events

MailBeePop3NegativeResponseException Events

The MailBeePop3NegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3NegativeResponseException Class
MailBee.Pop3Mail Namespace


MailBeePop3OptionalCommandNotSupportedException Class

MailBeePop3OptionalCommandNotSupportedException Class
The exception that is thrown when the POP3 server responds with a negative reply to an optional POP3 command.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.Pop3MailMailBeePop3NegativeResponseException
MailBee.Pop3MailMailBeePop3OptionalCommandNotSupportedException

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailBeePop3OptionalCommandNotSupportedException : MailBeePop3NegativeResponseException
Public Class MailBeePop3OptionalCommandNotSupportedException
    Inherits MailBeePop3NegativeResponseException

The MailBeePop3OptionalCommandNotSupportedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeePop3OptionalCommandNotSupportedException | Initializes a new instance of the MailBeePop3OptionalCommandNotSupportedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is never thrown in the application code. Instead, MailBee catches it, and raises ErrorOccurred event passing the exception instance as the Reason parameter value.

This exception indicates the POP3 server does not support an optional POP3 command which was sent to the server by MailBee. For instance, MailBee may try to send CAPA command in order to learn the server capabilities. The POP3 server, however, may not support it. In this case, MailBee continues normal execution and tries another methods to perform the current task or disables POP3 extensions which could be supported if the failed command succeeded. However, ErrorOccurred event is still raised to let the application code know that some features will be disabled.

See Also

Reference

MailBee.Pop3Mail Namespace


MailBeePop3OptionalCommandNotSupportedException Constructor

MailBeePop3OptionalCommandNotSupportedException Constructor
Initializes a new instance of the MailBeePop3OptionalCommandNotSupportedException class

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeePop3OptionalCommandNotSupportedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeePop3OptionalCommandNotSupportedException Class
MailBee.Pop3Mail Namespace


MailBeePop3OptionalCommandNotSupportedException Methods

MailBeePop3OptionalCommandNotSupportedException Methods

The MailBeePop3OptionalCommandNotSupportedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3OptionalCommandNotSupportedException Class
MailBee.Pop3Mail Namespace


MailBeePop3OptionalCommandNotSupportedException Properties

MailBeePop3OptionalCommandNotSupportedException Properties

The MailBeePop3OptionalCommandNotSupportedException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeePop3OptionalCommandNotSupportedException Class
MailBee.Pop3Mail Namespace


MailBeePop3OptionalCommandNotSupportedException Events

MailBeePop3OptionalCommandNotSupportedException Events

The MailBeePop3OptionalCommandNotSupportedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeePop3OptionalCommandNotSupportedException Class
MailBee.Pop3Mail Namespace


Pop3 Class

Pop3 Class
Provides properties and methods for connecting to a POP3 server and downloading and deleting e-mail messages from a user account inbox.
Inheritance Hierarchy
SystemObject
MailBee.Pop3MailPop3

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Pop3 : IComponent, IDisposable
Public Class Pop3
    Implements IComponent, IDisposable

The Pop3 type exposes the following members.

Constructors
 | Name | Description
Public method | Pop3 | Creates an instance of Pop3 class.
Public method | Pop3(String) | Creates and unlocks an instance of Pop3 class.
Top
Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | BeginConnect | Obsolete. Begins an asynchronous request for a connecting to a POP3 server.
 | BeginDeleteMessage | Obsolete. Begins an asynchronous request for flagging the specified message for deletion from the server.
 | BeginDeleteMessages | Obsolete. Begins an asynchronous request for flagging the specified range of messages for deletion from the server.
Public method | BeginDisconnect | Obsolete. Begins an asynchronous request for a disconnection from the server.
 | BeginDownloadMessage | Obsolete. Begins an asynchronous request for downloading the specified message header or entire message from the server.
 | BeginDownloadMessages | Obsolete. Begins an asynchronous request for downloading the entire or partial messages in the specified range from the server.
 | BeginExecuteCustomCommand | Obsolete. Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.
 | BeginLogin | Obsolete. Begins an asynchronous request for a logging in an account on a POP3 server.
 | BeginStartTls | Obsolete. Begins an asynchronous request to start TLS/SSL negotiation with the server.
 | Connect(String) | Connects to a POP3 server on the standard POP3 port (110).
 | Connect(String, Int32) | Connects to a POP3 server.
 | Connect(String, Int32, Boolean) | Connects to a POP3 server.
Public method | ConnectAsync(String) | async/await version of Connect(String).
Public method | ConnectAsync(String, Int32) | async/await version of Connect(String, Int32).
Public method | ConnectAsync(String, Int32, Boolean) | async/await version of Connect(String, Int32, Boolean).
 | DeleteMessage | Flags the specified message for deletion from the server.
Public method | DeleteMessageAsync | async/await version of DeleteMessage(Int32).
 | DeleteMessages | Flags all the messages in the inbox for deletion from the server.
 | DeleteMessages(Int32, Int32) | Flags the specified range of messages for deletion from the server.
Public method | DeleteMessagesAsync | async/await version of DeleteMessages.
Public method | DeleteMessagesAsync(Int32, Int32) | async/await version of DeleteMessages(Int32, Int32).
 | Disconnect | Disconnects from the POP3 server and releases any used resources.
Public method | DisconnectAsync | async/await version of Disconnect.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
 | DownloadEntireMessage | Completely downloads the specified message from the server.
Public method | DownloadEntireMessageAsync | async/await version of DownloadEntireMessage(Int32).
 | DownloadEntireMessages | Completely downloads all the messages from the inbox on the server.
 | DownloadEntireMessages(Int32, Int32) | Completely downloads the messages in the specified range from the server.
Public method | DownloadEntireMessagesAsync | async/await version of DownloadEntireMessages.
Public method | DownloadEntireMessagesAsync(Int32, Int32) | async/await version of DownloadEntireMessages(Int32, Int32).
 | DownloadMessageHeader(Int32) | Downloads the header of the specified message from the server.
 | DownloadMessageHeader(Int32, Int32) | Downloads the header and the specified number of body lines of the message on the server.
Public method | DownloadMessageHeaderAsync(Int32) | async/await version of DownloadMessageHeader(Int32).
Public method | DownloadMessageHeaderAsync(Int32, Int32) | async/await version of DownloadMessageHeader(Int32, Int32).
 | DownloadMessageHeaders | Downloads headers of all messages in the inbox on the server.
 | DownloadMessageHeaders(Int32, Int32) | Downloads the header of each message in the specified range from the server.
 | DownloadMessageHeaders(Int32, Int32, Int32) | Downloads the header and the specified number of body lines of each message in the specified range from the server.
Public method | DownloadMessageHeadersAsync | async/await version of DownloadMessageHeaders.
Public method | DownloadMessageHeadersAsync(Int32, Int32) | async/await version of DownloadMessageHeaders(Int32, Int32).
Public method | DownloadMessageHeadersAsync(Int32, Int32, Int32) | async/await version of DownloadMessageHeaders(Int32, Int32, Int32).
Public method | EndConnect | Ends the pending asynchronous connection request.
Public method | EndDeleteMessage | Ends the pending asynchronous request for flagging the message for deletion.
Public method | EndDeleteMessages | Ends the pending asynchronous request for flagging the range of messages for deletion.
Public method | EndDisconnect | Ends a pending asynchronous disconnection request.
Public method | EndDownloadMessage | Ends the pending asynchronous request for downloading the message and returns the downloaded message.
Public method | EndDownloadMessages | Ends the pending asynchronous request for downloading the messages and returns the downloaded messages.
Public method | EndExecuteCustomCommand | Ends the pending asynchronous request for sending user-defined command to the server.
Public method | EndLogin | Ends the pending asynchronous login request.
Public method | EndStartTls | Ends a pending asynchronous TLS/SSL negotiation request.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | ExecuteCustomCommand | Sends user-defined command to the server and receives the server response to this command.
Public method | ExecuteCustomCommandAsync | async/await version of ExecuteCustomCommand(String, Boolean).
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetErrorDescription | Returns a textual description of the last error.
 | GetExtension | Returns the name or parameters of the specified POP3 capability.
 | GetExtensions | Returns a reference to the key-value list of the server capabilities.
Public method | GetExtensionsAsync | async/await version of GetExtensions.
Public method | GetExtensionValue | Returns the parameters of the specified POP3 capability, or an empty string if the capability has no parameters.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMessageIndexFromUid | Gets the message number of the message to which the specified Unique-ID is assigned.
Public method | GetMessageSize | Gets the length (in bytes) of the specified message in the inbox.
 | GetMessageSizes | Gets the array of lengths (in bytes) of all messages in the inbox. The array is zero-based.
Public method | GetMessageSizesAsync | async/await version of GetMessageSizes.
Public method | GetMessageUidFromIndex | Gets the Unique-ID string assigned to the specified message in the inbox on the server.
 | GetMessageUids | Gets the array of Unique-ID's of all messages in the inbox. The array is zero-based.
Public method | GetMessageUidsAsync | async/await version of GetMessageUids.
Public method | GetServerResponse | Returns the last response from the server.
Public method | GetSocket | Returns the underlying Socket MailBee uses for the current network connection.
Public method | GetSocketError | Returns a Win32 error code of the last socket-related error.
Public method | GetStream | Returns the underlying Stream MailBee uses for the current network connection.
 | GetSupportedAuthMethods | Returns a set of flags indicating which authentication methods are supported by the server.
Public method | GetSupportedAuthMethodsAsync | async/await version of GetSupportedAuthMethods.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | Last | Gets the message number of the last message ever accessed in this mailbox during actual or all prior POP3 sessions.
Public method | LastAsync | async/await version of Last.
 | Login(String, String) | Logs in a mailbox on the POP3 server.
 | Login(String, String, AuthenticationMethods) | Logs in a mailbox on the POP3 server.
 | Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mailbox on the POP3 server.
 | Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mailbox on the POP3 server.
Public method | LoginAsync(String, String) | async/await version of Login(String, String).
Public method | LoginAsync(String, String, AuthenticationMethods) | async/await version of Login(String, String, AuthenticationMethods).
Public method | LoginAsync(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Public method | LoginAsync(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Noop | Sends a NOOP command to the server.
Public method | Noop2 | Sends a command to the POP3 server to keep the connection alive.
Public method | Noop2Async | async/await version of Noop2.
Public method | NoopAsync | async/await version of Noop.
Protected method | OnConnected | Used by MailBee to raise Connected event.
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnDisconnected | Used by MailBee to raise Disconnected event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnHostResolved | Used by MailBee to raise HostResolved event.
Protected method | OnLoggedIn | Used by MailBee to raise LoggedIn event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnLowLevelDataReceived | Used by MailBee to raise LowLevelDataReceived event.
Protected method | OnLowLevelDataSent | Used by MailBee to raise LowLevelDataSent event.
Protected method | OnMessageDataChunkReceived | Used by MailBee to raise MessageDataChunkReceived event.
Protected method | OnMessageDownloaded | Used by MailBee to raise MessageDownloaded event.
Protected method | OnSocketConnected | Used by MailBee to raise SocketConnected event.
Protected method | OnSocketCreating | Used by MailBee to raise SocketCreating event.
Protected method | OnTlsStarted | Used by MailBee to raise TlsStarted event.
 | QuickDownloadMessage(String, String, String, Int32) | Completely downloads the specified message from the server, in a single line of code.
 | QuickDownloadMessage(String, String, String, Int32, Int32) | Downloads the specified message (entire message or message header only) from the server, in a single line of code.
 | QuickDownloadMessages(String, String, String) | Completely downloads all the messages in the inbox on the server, in a single line of code.
 | QuickDownloadMessages(String, String, String, Int32) | Downloads all the messages (entire messages or message headers only) in the inbox on the server, in a single line of code.
Public method | ResetDeletes | Resets the POP3 session, and cancels the deleted status for all messages flagged for deletion in the inbox.
Public method | ResetDeletesAsync | async/await version of ResetDeletes.
Public method | ResetState | Resets the internal state of the component.
 | StartTls | Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.
Public method | StartTlsAsync | async/await version of StartTls.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
Properties
 | Name | Description
Public property | EnableLastDownloaded | Gets or sets whether MailBee should save currently downloaded messages in LastDownloadedMessages property.
Public property | InboxMessageCount | Gets the number of messages in the inbox.
Public property | InboxPreloadOptions | Gets or sets the status of whether MailBee will download the list of message sizes and/or the list of message lengths during logging in the inbox.
Public property | InboxSize | Gets the total size (in bytes) occupied by all the messages in the inbox.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | IsConnected | Indicates whether the component is connected to the server.
Public property | IsLoggedIn | Indicates whether the component has already successfully authenticated on the server and logged in the user account.
Public property | IsSslConnection | Indicates whether the current connection (if any) iss secured with TLS/SSL layer.
 | LastDownloadedMessages | Gets the collection of the messages downloaded to the current moment.
Public property | LastResult | Gets a numeric code of the last error.
 | LicenseKey | Obsolete. Assigns the license key.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
 | Proxy | Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RaiseEventsViaMessageLoop | Gets or sets whether the events will be raised on the message loop of the application or not.
Public property | RequestEncoding | Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the server.
Public property | ResponseEncoding | Gets or sets the encoding used to convert a byte data received from the server into a string.
Public property | Site | Gets or sets the object to be used as a site for the component.
 | SslCertificates | Provides access to the client and server SSL certificate settings.
 | SslMode | Gets or sets how the component should establish TLS/SSL connection with the mail server.
Public property | SslProtocol | Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
Events
 | Name | Description
 | Connected | Occurs when the connection with the server is successfully established.
 | DataReceived | Occurs when data is received from the POP3 server.
 | DataSent | Occurs when data is sent to the POP3 server.
 | Disconnected | Occurs when the connection with the server gets closed.
Public event | Disposed | Occurs after the component was disposed.
 | ErrorOccurred | Occurs when the MailBeeException is thrown.
 | HostResolved | Occurs when the POP3 server name is successully resolved into IP address(es).
 | LoggedIn | Occurs when the component successfully authenticates the user on the server and logs in the user account.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Pop3.Log.MemoryLog is true).
 | LowLevelDataReceived | Occurs when data is received from the connected socket.
 | LowLevelDataSent | Occurs when data is sent to the connected socket.
 | MessageDataChunkReceived | Occurs on progress of downloading message source data from the server.
 | MessageDownloaded | Occurs when a message was downloaded from the server.
 | SocketConnected | Occurs when the POP3 server accepts the connection attempt and opens the transmission channel between the remote host (POP3 server) and the client (MailBee).
 | SocketCreating | Occurs when MailBee needs a new socket object for establishing a connection with the POP3 server.
 | TlsStarted | Occurs when the connection with the server becomes secure.
Top
Remarks
You can perform the following operations using this class:
  • Download entire messages with body and attachments
  • Download message headers (and optionally, the part of message bodies)
  • Delete messages from the POP3 server
  • Send user-defined commands to the POP3 server
  • Login to a user account using a number of authentication methods (including secure methods and OAuth2)
  • Take advantage of POP3 pipelining which dramatically speeds up batch retrieval or deleting messages
  • Collect inbox statistics like number of messages and total size of all messages
  • Download entire messages or message headers with a single line of code (using static methods)
  • Establish secure connection with TLS/SSL enabled POP3 server
  • Establish connection via a proxy server (SOCKS4, SOCKS5, and HTTP proxy are supported)
Examples
This sample connects to a POP3 server, logs in using the most secure method supported by this server, downloads headers for the first 10 messages in the inbox, and prints From:, To:, and Subject: field values for every message into Console.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
MailMessageCollection msgs = pop.DownloadMessageHeaders(1, 10);
foreach (MailMessage msg in msgs)
{
    Console.WriteLine("From: " + msg.From.Email + ", To: " + msg.To.AsString + ", Subject: " + msg.Subject);
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Dim msgs As MailMessageCollection = pop.DownloadMessageHeaders(1, 10)
For Each msg As MailMessage In msgs
    Console.WriteLine("From: " & msg.From.Email & ", To: " & msg.To.AsString & ", Subject: " & msg.Subject)
Next
pop.Disconnect()
See Also

Reference

MailBee.Pop3Mail Namespace


Pop3 Constructor

Pop3 Constructor
Creates an instance of Pop3 class.
Overload List
 | Name | Description
Public method | Pop3 | Creates an instance of Pop3 class.
Public method | Pop3(String) | Creates and unlocks an instance of Pop3 class.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3 Constructor

Pop3 Constructor
Creates an instance of Pop3 class.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Pop3()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET POP3 not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

Pop3 Class
Pop3 Overload
MailBee.Pop3Mail Namespace


Pop3 Constructor (String)

Pop3 Constructor (String)
Creates and unlocks an instance of Pop3 class.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Pop3(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET POP3 not licensed and the supplied license key is invalid.
See Also

Reference

Pop3 Class
Pop3 Overload
MailBee.Pop3Mail Namespace


Pop3 Methods

Pop3 Methods

The Pop3 type exposes the following members.

Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | BeginConnect | Obsolete. Begins an asynchronous request for a connecting to a POP3 server.
 | BeginDeleteMessage | Obsolete. Begins an asynchronous request for flagging the specified message for deletion from the server.
 | BeginDeleteMessages | Obsolete. Begins an asynchronous request for flagging the specified range of messages for deletion from the server.
Public method | BeginDisconnect | Obsolete. Begins an asynchronous request for a disconnection from the server.
 | BeginDownloadMessage | Obsolete. Begins an asynchronous request for downloading the specified message header or entire message from the server.
 | BeginDownloadMessages | Obsolete. Begins an asynchronous request for downloading the entire or partial messages in the specified range from the server.
 | BeginExecuteCustomCommand | Obsolete. Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.
 | BeginLogin | Obsolete. Begins an asynchronous request for a logging in an account on a POP3 server.
 | BeginStartTls | Obsolete. Begins an asynchronous request to start TLS/SSL negotiation with the server.
 | Connect(String) | Connects to a POP3 server on the standard POP3 port (110).
 | Connect(String, Int32) | Connects to a POP3 server.
 | Connect(String, Int32, Boolean) | Connects to a POP3 server.
Public method | ConnectAsync(String) | async/await version of Connect(String).
Public method | ConnectAsync(String, Int32) | async/await version of Connect(String, Int32).
Public method | ConnectAsync(String, Int32, Boolean) | async/await version of Connect(String, Int32, Boolean).
 | DeleteMessage | Flags the specified message for deletion from the server.
Public method | DeleteMessageAsync | async/await version of DeleteMessage(Int32).
 | DeleteMessages | Flags all the messages in the inbox for deletion from the server.
 | DeleteMessages(Int32, Int32) | Flags the specified range of messages for deletion from the server.
Public method | DeleteMessagesAsync | async/await version of DeleteMessages.
Public method | DeleteMessagesAsync(Int32, Int32) | async/await version of DeleteMessages(Int32, Int32).
 | Disconnect | Disconnects from the POP3 server and releases any used resources.
Public method | DisconnectAsync | async/await version of Disconnect.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
 | DownloadEntireMessage | Completely downloads the specified message from the server.
Public method | DownloadEntireMessageAsync | async/await version of DownloadEntireMessage(Int32).
 | DownloadEntireMessages | Completely downloads all the messages from the inbox on the server.
 | DownloadEntireMessages(Int32, Int32) | Completely downloads the messages in the specified range from the server.
Public method | DownloadEntireMessagesAsync | async/await version of DownloadEntireMessages.
Public method | DownloadEntireMessagesAsync(Int32, Int32) | async/await version of DownloadEntireMessages(Int32, Int32).
 | DownloadMessageHeader(Int32) | Downloads the header of the specified message from the server.
 | DownloadMessageHeader(Int32, Int32) | Downloads the header and the specified number of body lines of the message on the server.
Public method | DownloadMessageHeaderAsync(Int32) | async/await version of DownloadMessageHeader(Int32).
Public method | DownloadMessageHeaderAsync(Int32, Int32) | async/await version of DownloadMessageHeader(Int32, Int32).
 | DownloadMessageHeaders | Downloads headers of all messages in the inbox on the server.
 | DownloadMessageHeaders(Int32, Int32) | Downloads the header of each message in the specified range from the server.
 | DownloadMessageHeaders(Int32, Int32, Int32) | Downloads the header and the specified number of body lines of each message in the specified range from the server.
Public method | DownloadMessageHeadersAsync | async/await version of DownloadMessageHeaders.
Public method | DownloadMessageHeadersAsync(Int32, Int32) | async/await version of DownloadMessageHeaders(Int32, Int32).
Public method | DownloadMessageHeadersAsync(Int32, Int32, Int32) | async/await version of DownloadMessageHeaders(Int32, Int32, Int32).
Public method | EndConnect | Ends the pending asynchronous connection request.
Public method | EndDeleteMessage | Ends the pending asynchronous request for flagging the message for deletion.
Public method | EndDeleteMessages | Ends the pending asynchronous request for flagging the range of messages for deletion.
Public method | EndDisconnect | Ends a pending asynchronous disconnection request.
Public method | EndDownloadMessage | Ends the pending asynchronous request for downloading the message and returns the downloaded message.
Public method | EndDownloadMessages | Ends the pending asynchronous request for downloading the messages and returns the downloaded messages.
Public method | EndExecuteCustomCommand | Ends the pending asynchronous request for sending user-defined command to the server.
Public method | EndLogin | Ends the pending asynchronous login request.
Public method | EndStartTls | Ends a pending asynchronous TLS/SSL negotiation request.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | ExecuteCustomCommand | Sends user-defined command to the server and receives the server response to this command.
Public method | ExecuteCustomCommandAsync | async/await version of ExecuteCustomCommand(String, Boolean).
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetErrorDescription | Returns a textual description of the last error.
 | GetExtension | Returns the name or parameters of the specified POP3 capability.
 | GetExtensions | Returns a reference to the key-value list of the server capabilities.
Public method | GetExtensionsAsync | async/await version of GetExtensions.
Public method | GetExtensionValue | Returns the parameters of the specified POP3 capability, or an empty string if the capability has no parameters.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMessageIndexFromUid | Gets the message number of the message to which the specified Unique-ID is assigned.
Public method | GetMessageSize | Gets the length (in bytes) of the specified message in the inbox.
 | GetMessageSizes | Gets the array of lengths (in bytes) of all messages in the inbox. The array is zero-based.
Public method | GetMessageSizesAsync | async/await version of GetMessageSizes.
Public method | GetMessageUidFromIndex | Gets the Unique-ID string assigned to the specified message in the inbox on the server.
 | GetMessageUids | Gets the array of Unique-ID's of all messages in the inbox. The array is zero-based.
Public method | GetMessageUidsAsync | async/await version of GetMessageUids.
Public method | GetServerResponse | Returns the last response from the server.
Public method | GetSocket | Returns the underlying Socket MailBee uses for the current network connection.
Public method | GetSocketError | Returns a Win32 error code of the last socket-related error.
Public method | GetStream | Returns the underlying Stream MailBee uses for the current network connection.
 | GetSupportedAuthMethods | Returns a set of flags indicating which authentication methods are supported by the server.
Public method | GetSupportedAuthMethodsAsync | async/await version of GetSupportedAuthMethods.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | Last | Gets the message number of the last message ever accessed in this mailbox during actual or all prior POP3 sessions.
Public method | LastAsync | async/await version of Last.
 | Login(String, String) | Logs in a mailbox on the POP3 server.
 | Login(String, String, AuthenticationMethods) | Logs in a mailbox on the POP3 server.
 | Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mailbox on the POP3 server.
 | Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mailbox on the POP3 server.
Public method | LoginAsync(String, String) | async/await version of Login(String, String).
Public method | LoginAsync(String, String, AuthenticationMethods) | async/await version of Login(String, String, AuthenticationMethods).
Public method | LoginAsync(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Public method | LoginAsync(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Noop | Sends a NOOP command to the server.
Public method | Noop2 | Sends a command to the POP3 server to keep the connection alive.
Public method | Noop2Async | async/await version of Noop2.
Public method | NoopAsync | async/await version of Noop.
Protected method | OnConnected | Used by MailBee to raise Connected event.
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnDisconnected | Used by MailBee to raise Disconnected event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnHostResolved | Used by MailBee to raise HostResolved event.
Protected method | OnLoggedIn | Used by MailBee to raise LoggedIn event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnLowLevelDataReceived | Used by MailBee to raise LowLevelDataReceived event.
Protected method | OnLowLevelDataSent | Used by MailBee to raise LowLevelDataSent event.
Protected method | OnMessageDataChunkReceived | Used by MailBee to raise MessageDataChunkReceived event.
Protected method | OnMessageDownloaded | Used by MailBee to raise MessageDownloaded event.
Protected method | OnSocketConnected | Used by MailBee to raise SocketConnected event.
Protected method | OnSocketCreating | Used by MailBee to raise SocketCreating event.
Protected method | OnTlsStarted | Used by MailBee to raise TlsStarted event.
 | QuickDownloadMessage(String, String, String, Int32) | Completely downloads the specified message from the server, in a single line of code.
 | QuickDownloadMessage(String, String, String, Int32, Int32) | Downloads the specified message (entire message or message header only) from the server, in a single line of code.
 | QuickDownloadMessages(String, String, String) | Completely downloads all the messages in the inbox on the server, in a single line of code.
 | QuickDownloadMessages(String, String, String, Int32) | Downloads all the messages (entire messages or message headers only) in the inbox on the server, in a single line of code.
Public method | ResetDeletes | Resets the POP3 session, and cancels the deleted status for all messages flagged for deletion in the inbox.
Public method | ResetDeletesAsync | async/await version of ResetDeletes.
Public method | ResetState | Resets the internal state of the component.
 | StartTls | Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.
Public method | StartTlsAsync | async/await version of StartTls.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Abort Method

Pop3Abort Method
Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Abort()
Public Sub Abort
Remarks

A method which was in progress when Abort method has been called will throw MailBeeUserAbortException (unless ThrowExceptions is not false). If the component was not doing any work at the moment (IsBusy was false), the connection is aborted but no exception is thrown.

This method tries to abort the current network operation immediately, which works for all cases except of resolving a domain name into IP address. Due to .NET framework limitations, this operation cannot be aborted. Thus, sometimes you may experience a several seconds delay between calling this method and getting MailBeeUserAbortException (the time needed for DNS resolve to complete).

Note Note
No events will be raised after this method has been called.
To restore the component from the aborted state, the developer can use ResetState method.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3IsAborted
Pop3ResetState


Pop3.BeginConnect Method

Pop3BeginConnect Method

Note: This API is now obsolete.

Begins an asynchronous request for a connecting to a POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ConnectAsync instead.")]
public IAsyncResult BeginConnect(
    string serverName,
    int port,
    bool pipelining,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ConnectAsync instead.")>
Public Function BeginConnect (
    serverName As String,
    port As Integer,
    pipelining As Boolean,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard POP3 port is 110.
pipelining
Type: SystemBoolean
Specifies whether to use commands pipelining if it's supported by the server.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous connection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks

This method is an asynchronous version of Connect(String, Int32, Boolean).

A reference to the state object will be available in the events raised by this method through the State property value. This is also valid for the rest of asynchronous methods in MailBee.

Examples
Asynchronous connecting to a POP3 server in WinForms application. This sample also handles Connected event. Wait method is used to wait for the asynchronous method completion, since .NET's standard WaitOne(Int32, Boolean) cannot process events.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// Put the code below inside your class

// "Connected" event handler
private void OnConnected(object sender, ConnectedEventArgs e)
{
    MessageBox.Show("Connected to the server");
}

// The actual code
private void Form1_Load(object sender, System.EventArgs e)
{
    Pop3 pop = new Pop3();

    // Let MailBee process events
    pop.RaiseEventsViaMessageLoop = false;

    pop.Connected += new ConnectedEventHandler(OnConnected);

    // Initiate an asynchronous connection
    pop.BeginConnect("pop.somehost.com", 110, true, null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above
        pop.Wait(0);
    }

    // If the connection was not established during execution of the lengthy
    // work, wait until it's established
    pop.Wait();

    // End the connection request
    pop.EndConnect();

    // Connected to the server!

    // Disconnect from the server
    pop.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail

' Put the code below inside your class.

' "Connected" event handler
Private Sub OnConnected(ByVal sender As System.Object, ByVal e As ConnectedEventArgs)
    MsgBox("Connected to the server")
End Sub

' The actual code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As ConnectedEventArgs)
    Dim pop As New Pop3

    ' Let MailBee process events
    pop.RaiseEventsViaMessageLoop = False

    AddHandler pop.Connected, AddressOf OnConnected

    ' Initiate an asynchronous connection
    pop.BeginConnect("pop.somehost.com", 110, True, Nothing, Nothing)

    ' Simulate some lengthy work here...
    Dim i As Integer
    For i = 1 To 100
        ' Make a portion of the work
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above
        pop.Wait(0)
    Next

    ' If the connection was not established during execution of the lengthy
    ' work, wait until it's established
    pop.Wait()

    ' End the connection request
    pop.EndConnect()

    ' Connected to the server!

    ' Disconnect from the server
    pop.Disconnect()
End Sub
Examples
Asynchronous connecting to a POP3 server in non-WinForms application. Applications which do not have message loop (such as console or web applications) can raise events on any thread and do not require any special events processing.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // "Connected" event handler
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Connected to the server");
    }

    // The actual code
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        pop.Connected += new ConnectedEventHandler(OnConnected);

        // Initiate an asynchronous connection
        pop.BeginConnect("pop.somehost.com", 110, true, null, null);

        // Simulate some lengthy work here...
        System.Threading.Thread.Sleep(1000);

        // If the connection was not established during execution of the lengthy work,
        // wait until it's established, and end the connection request
        pop.EndConnect();

        // Connected to the server!

        // Disconnect from the server
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Public Class Sample
    ' "Connected" event handler
    Public Shared Sub OnConnected(ByVal sender As System.Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Connected to the server")
    End Sub

    ' The actual code
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3
        AddHandler pop.Connected, AddressOf OnConnected

        ' Initiate an asynchronous connection
        pop.BeginConnect("pop.somehost.com", 110, True, Nothing, Nothing)

        ' Simulate some lengthy work here...
        System.Threading.Thread.Sleep(1000)

        ' If the connection was not established during execution of the lengthy work,
        ' wait until it's established, and end the connection request
        pop.EndConnect()

        ' Connected to the server!

        ' Disconnect from the server
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Connect(String, Int32, Boolean)
Pop3RaiseEventsViaMessageLoop
Pop3Wait


Pop3.BeginDeleteMessage Method

Pop3BeginDeleteMessage Method

Note: This API is now obsolete.

Begins an asynchronous request for flagging the specified message for deletion from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DeleteMessageAsync instead.")]
public IAsyncResult BeginDeleteMessage(
    int index,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DeleteMessageAsync instead.")>
Public Function BeginDeleteMessage (
    index As Integer,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous flagging the message for deletion.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of DeleteMessage(Int32).
Examples
This WinForms sample demonstrates asynchronous flagging the last message for deletion and use of a callback function.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// Put the code below inside your class.

// A callback function.
private void DeleteMessageCallback(IAsyncResult result)
{
    Pop3 pop = (Pop3)result.AsyncState;
    pop.EndDeleteMessage();
    MessageBox.Show("Last message flagged as deleted");
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Pop3 pop = new Pop3();

    // Let MailBee process events.
    pop.RaiseEventsViaMessageLoop = false;

    pop.Connect("pop.somehost.com");
    pop.Login("jdoe", "secret");

    // Initiate an asynchronous deletion attempt.
    pop.BeginDeleteMessage(pop.InboxMessageCount, _
        new AsyncCallback(DeleteMessageCallback), pop);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        pop.Wait(0);
    }

    // If flagging the message is still in progress, wait until it's done.
    pop.Wait();

    // Disconnect from the server.
    pop.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' Put the code below inside your class.

' A callback function.
Private Sub DeleteMessageCallback(ByVal result As IAsyncResult)
    Dim pop As New Pop3
    pop = result.AsyncState
    pop.EndDeleteMessage()
    MsgBox("Last message flagged as deleted")
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim pop As New Pop3

    ' Let MailBee process events.
    pop.RaiseEventsViaMessageLoop = False

    pop.Connect("pop.somehost.com")
    pop.Login("jdoe", "secret")

    ' Initiate an asynchronous deletion attempt.
    pop.BeginDeleteMessage(pop.InboxMessageCount, _
        New AsyncCallback(AddressOf DeleteMessageCallback), pop)

    ' Simulate some lengthy work here...
    Dim i As Integer
    For i = 1 To 100
        ' Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above.
        pop.Wait(0)
    Next

    ' If flagging the message is still in progress, wait until it's done.
    pop.Wait()

    ' Disconnect from the server.
    pop.Disconnect()
End Sub
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DeleteMessage(Int32)
Pop3BeginDeleteMessages(Int32, Int32, AsyncCallback, Object)


Pop3.BeginDeleteMessages Method

Pop3BeginDeleteMessages Method

Note: This API is now obsolete.

Begins an asynchronous request for flagging the specified range of messages for deletion from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DeleteMessagesAsync instead.")]
public IAsyncResult BeginDeleteMessages(
    int startIndex,
    int count,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DeleteMessagesAsync instead.")>
Public Function BeginDeleteMessages (
    startIndex As Integer,
    count As Integer,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range being deleted.
count
Type: SystemInt32
Number of messages to be flagged for deletion, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be flagged for deletion.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous flagging the messages for deletion.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of DeleteMessages(Int32, Int32).
Examples
This WinForms sample demonstrates asynchronous flagging 5 last messages in the inbox for deletion. No callback function is used.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// Put the code below inside your class.

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Pop3 pop = new Pop3();

    // Let MailBee process events.
    pop.RaiseEventsViaMessageLoop = false;

    pop.Connect("pop.somehost.com");
    pop.Login("jdoe", "secret");

    // Initiate an asynchronous deletion attempt.
    pop.BeginDeleteMessages(pop.InboxMessageCount - 4, 5, null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        pop.Wait(0);
    }

    // End the message flagging operation. If it's in progress at the moment
    // this method starts, it will wait until it's done first.
    pop.EndDeleteMessages();

    // Disconnect from the server.
    pop.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' Put the code below inside your class.

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim pop As New Pop3

    ' Let MailBee process events.
    pop.RaiseEventsViaMessageLoop = False

    pop.Connect("pop.somehost.com")
    pop.Login("jdoe", "secret")

    ' Initiate an asynchronous deletion attempt.
    pop.BeginDeleteMessages(pop.InboxMessageCount - 4, 5, Nothing, Nothing)

    ' Simulate some lengthy work here...
    Dim i As Integer
    For i = 1 To 100
        ' Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above.
        pop.Wait(0)
    Next

    ' End the message flagging operation. If it's in progress at the moment
    ' this method starts, it will wait until it's done first.
    pop.EndDeleteMessages()

    ' Disconnect from the server.
    pop.Disconnect()
End Sub
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DeleteMessages(Int32, Int32)


Pop3.BeginDisconnect Method

Pop3BeginDisconnect Method

Note: This API is now obsolete.

Begins an asynchronous request for a disconnection from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DisconnectAsync instead.")]
public IAsyncResult BeginDisconnect(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DisconnectAsync instead.")>
Public Function BeginDisconnect (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous disconnection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Disconnect.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Disconnect


Pop3.BeginDownloadMessage Method

Pop3BeginDownloadMessage Method

Note: This API is now obsolete.

Begins an asynchronous request for downloading the specified message header or entire message from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEntireMessageAsync or DownloadMessageHeaderAsync instead.")]
public IAsyncResult BeginDownloadMessage(
    int index,
    int bodyLineCount,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEntireMessageAsync or DownloadMessageHeaderAsync instead.")>
Public Function BeginDownloadMessage (
    index As Integer,
    bodyLineCount As Integer,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire message.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous downloading the message.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks

This method is an asynchronous version of DownloadMessageHeader(Int32).

If multiple messages or message headers are downloaded, it's recommended to use BeginDownloadMessages(Int32, Int32, Int32, AsyncCallback, Object) method, since it can operate much faster if the server supports pipelining.

Examples
This WinForms sample demonstrates asynchronous downloading of the first message in the inbox. No callback function is used. Once the message is downloaded, all the attachments to the message are saved into C:\Temp folder.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// Put the code below inside your class.

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Pop3 pop = new Pop3();

    // Let MailBee process events.
    pop.RaiseEventsViaMessageLoop = false;

    pop.Connect("pop.somehost.com");
    pop.Login("jdoe", "secret");

    // Initiate an asynchronous download attempt.
    // bodyLineCount = -1 to indicate the entire message must be downloaded.
    pop.BeginDownloadMessage(1, -1, null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        pop.Wait(0);
    }

    // End the message download operation and return MailMessage object.
    // If the operation is still in progress at the moment when
    // this method starts, the method will wait until the operation completion.
    MailMessage msg = pop.EndDownloadMessage();

    // Save all attachments into C:\Temp folder.
    msg.Attachments.SaveAll(@"C:\Temp");

    // Disconnect from the server.
    pop.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' Put the code below inside your class.

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim pop As New Pop3

    ' Let MailBee process events.
    pop.RaiseEventsViaMessageLoop = False

    pop.Connect("pop.somehost.com")
    pop.Login("jdoe", "secret")

    ' Initiate an asynchronous download attempt.
    ' bodyLineCount = -1 to indicate the entire message must be downloaded.
    pop.BeginDownloadMessage(1, -1, Nothing, Nothing)

    ' Simulate some lengthy work here...
    Dim i As Integer
    For i = 1 To 100
        ' Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above.
        pop.Wait(0)
    Next

    ' End the message download operation and return MailMessage object.
    ' If the operation is still in progress at the moment when
    ' this method starts, the method will wait until the operation completion.
    Dim msg As MailMessage
    msg = pop.EndDownloadMessage()

    ' Save all attachments into C:\Temp folder.
    msg.Attachments.SaveAll("C:\Temp")

    ' Disconnect from the server.
    pop.Disconnect()
End Sub
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DownloadEntireMessage(Int32)
Pop3DownloadMessageHeader(Int32)
Pop3BeginDownloadMessages(Int32, Int32, Int32, AsyncCallback, Object)


Pop3.BeginDownloadMessages Method

Pop3BeginDownloadMessages Method

Note: This API is now obsolete.

Begins an asynchronous request for downloading the entire or partial messages in the specified range from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEntireMessagesAsync or DownloadMessageHeadersAsync instead.")]
public IAsyncResult BeginDownloadMessages(
    int startIndex,
    int count,
    int bodyLineCount,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DownloadEntireMessagesAsync or DownloadMessageHeadersAsync instead.")>
Public Function BeginDownloadMessages (
    startIndex As Integer,
    count As Integer,
    bodyLineCount As Integer,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire messages.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous downloading the message.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of DownloadMessageHeaders(Int32, Int32, Int32).
Examples
This sample asynchronously downloads headers of all the messages in the inbox. Then, it displays the following information about each message:
  • The length in bytes of the downloaded header data
  • The length in bytes of the actual message data on the server (it would be the length of the message if the entire message was downloaded)
MessageDataChunkReceived event is handled in order to track the download progress. No callback function is used. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // MessageDataChunkReceived event handler.
    private static void OnMessageDataChunkReceived(object sender,
        Pop3MessageDataChunkReceivedEventArgs e)
    {
        Console.WriteLine(e.BytesJustReceived + " bytes of the message #" +
            e.MessageNumber + " received");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();
        pop.Connect("pop.somehost.com");
        pop.Login("jdoe", "secret");

        // Subscribe to MessageDataChunkReceived event.
        pop.MessageDataChunkReceived +=
            new Pop3MessageDataChunkReceivedEventHandler(OnMessageDataChunkReceived);

        // Initiate an asynchronous download attempt.
        pop.BeginDownloadMessages(1, -1, 0, null, null);

        // Simulate some lengthy work here. At the same time,
        // the messages are downloaded on another thread.
        System.Threading.Thread.Sleep(3000);

        // End the messages download operation and return MailMessageCollection object.
        // If the operation is still in progress at the moment when
        // this method starts, the method will wait until the operation completion.
        MailMessageCollection msgs = pop.EndDownloadMessages();

        foreach (MailMessage msg in msgs)
        {
            Console.WriteLine("Message #" + msg.IndexOnServer +
                ": the length of the entire message is " + msg.SizeOnServer +
                " bytes, the length of the downloaded header is " + msg.Size + " bytes.");
        }

        // Disconnect from the server.
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' MessageDataChunkReceived event handler.
    Private Shared Sub OnMessageDataChunkReceived(ByVal sender As Object, _
        ByVal e As Pop3MessageDataChunkReceivedEventArgs)
        Console.WriteLine(e.BytesJustReceived & " bytes of the message #" & _
            e.MessageNumber & " received")
    End Sub

    ' The actual code
    Shared Sub Main(ByVal args As String())
        Dim pop As Pop3
        pop.Connect("pop.somehost.com")
        pop.Login("jdoe", "secret")

        ' Subscribe to MessageDataChunkReceived event.
        AddHandler pop.MessageDataChunkReceived, AddressOf OnMessageDataChunkReceived

        ' Initiate an asynchronous download attempt.
        pop.BeginDownloadMessages(1, -1, 0, Nothing, Nothing)

        ' Simulate some lengthy work here. At the same time,
        ' the messages are downloaded on another thread.
        System.Threading.Thread.Sleep(3000)

        ' End the messages download operation and return MailMessageCollection object.
        ' If the operation is still in progress at the moment when
        ' this method starts, the method will wait until the operation completion.
        Dim msgs As MailMessageCollection
        msgs = pop.EndDownloadMessages()

        For Each msg As MailMessage In msgs
            Console.WriteLine("Message #" + msg.IndexOnServer & _
                ": the length of the entire message is " & msg.SizeOnServer & _
                " bytes, the length of the downloaded header is " & msg.Size & " bytes.")
        Next

        ' Disconnect from the server.
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DownloadEntireMessages(Int32, Int32)
Pop3DownloadMessageHeaders(Int32, Int32, Int32)


Pop3.BeginExecuteCustomCommand Method

Pop3BeginExecuteCustomCommand Method

Note: This API is now obsolete.

Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ExecuteCustomCommandAsync instead.")]
public IAsyncResult BeginExecuteCustomCommand(
    string commandString,
    bool multiLineResponse,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ExecuteCustomCommandAsync instead.")>
Public Function BeginExecuteCustomCommand (
    commandString As String,
    multiLineResponse As Boolean,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

commandString
Type: SystemString
User-defined command text (including line terminator).
multiLineResponse
Type: SystemBoolean
true if the given command returns multi-line response on success; false if the given command always produces single-line response.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous user-defined command execution.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of ExecuteCustomCommand(String, Boolean).
Examples
Sending a mail message to the POP3 server in WinForms application (the POP3 server must support XTND XMIT extension). Sending itself is performed in a few stages:
  1. Send XTND XMIT command
  2. If the server returned positive response indicating XTND XMIT extension is supported, send message source data (encoded as multi-line POP3 request)
  3. If the server returned positive response, the message was accepted for delivery
Callback functions are actively used, and the application message loop never gets blocked (no waiting for an asynchronous method completion is used). Thus, we do need to care about dead-locks which would occur if an event was raised while the message loop was blocked by somewhat like WaitOne(Int32, Boolean) method call. This sample's code does not handle any events, but it's safe to use them if needed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// Put the code below inside your class.

// XTND XMIT callback function.
private void XtndXmitCallback(IAsyncResult result)
{
    Pop3 pop = (Pop3)result.AsyncState;

    // Process the results of XTND XMIT command.
    try
    {
        pop.EndExecuteCustomCommand();
    }
    catch (MailBeePop3NegativeResponseException)
    {
        MessageBox.Show("XTND XMIT command is not supported. The server responded: " +
            pop.GetServerResponse());
        pop.Disconnect();
        return;
    }

    // Create a mail message to be sent.
    MailMessage msg = new MailMessage();
    msg.From.Email = "jdoe@mydomain.com";
    msg.To.AsString = "kathy@herdomain.com";
    msg.Subject = "Meeting request";
    msg.BodyPlainText = "Hi, Kathy,\r\nCan we meet tomorrow?\r\n\r\nRegards,\r\nJohn";

    // Encode the mail message source as multi-line POP3 request.
    string messageSource = System.Text.Encoding.Default.GetString(msg.GetMessageRawData());
    messageSource = messageSource.Replace("\r\n.", "\r\n..");

    // Send the mail message asynchronously.
    pop.BeginExecuteCustomCommand(messageSource + "\r\n.\r\n",
        false, new AsyncCallback(SubmissionCallback), pop);
}

// Mail message submission callback function.
private void SubmissionCallback(IAsyncResult result)
{
    Pop3 pop = (Pop3)result.AsyncState;

    // Process the results of the mail message submission.
    try
    {
        pop.EndExecuteCustomCommand();
        MessageBox.Show("Message submitted for delivery");
    }
    catch (MailBeePop3NegativeResponseException)
    {
        MessageBox.Show("Message was not submitted. The server responded: " +
            pop.GetServerResponse());
    }

    pop.Disconnect();
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Pop3 pop = new Pop3();

    pop.Connect("pop.mydomain.com");
    pop.Login("jdoe", "secret");

    // Issue XTND XMIT command asynchronously.
    pop.BeginExecuteCustomCommand("XTND XMIT\r\n", false,
        new AsyncCallback(XtndXmitCallback), pop);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' Put the code below inside your class.

' XTND XMIT callback function.
Private Sub XtndXmitCallback(ByVal result As IAsyncResult)
    Dim pop As New Pop3
    pop = result.AsyncState

    ' Process the results of XTND XMIT command.
    Try
        pop.EndExecuteCustomCommand()
    Catch MailBeePop3NegativeResponseException As Exception
        MsgBox("XTND XMIT command is not supported. The server responded: " & _
            pop.GetServerResponse())
        pop.Disconnect()
        Return
    End Try

    ' Create a mail message to be sent.
    Dim msg As New MailMessage
    msg.From.Email = "jdoe@mydomain.com"
    msg.To.AsString = "kathy@herdomain.com"
    msg.Subject = "Meeting request"
    msg.BodyPlainText = "Hi, Kathy,\r\nCan we meet tomorrow?\r\n\r\nRegards,\r\nJohn"

    ' Encode the mail message source as multi-line POP3 request.
    Dim messageSource As String = System.Text.Encoding.Default.GetString(msg.GetMessageRawData())
    messageSource = messageSource.Replace("\r\n.", "\r\n..")

    ' Send the mail message asynchronously.
    pop.BeginExecuteCustomCommand(messageSource + "\r\n.\r\n", False, _
        New AsyncCallback(AddressOf SubmissionCallback), pop)
End Sub

' Mail message submission callback function.
Private Sub SubmissionCallback(ByVal result As IAsyncResult)
    Dim pop As New Pop3
    pop = result.AsyncState

    ' Process the results of the mail message submission.
    Try
        pop.EndExecuteCustomCommand()
        MsgBox("Message submitted for delivery")
    Catch MailBeePop3NegativeResponseException As Exception
        MsgBox("Message was not submitted. The server responded: " & _
            pop.GetServerResponse())
    End Try

    pop.Disconnect()
End Sub

' The actual code.
Private Sub Form11_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim pop As New Pop3
    pop.Connect("pop.mydomain.com")
    pop.Login("jdoe", "secret")

    ' Issue XTND XMIT command asynchronously.
    pop.BeginExecuteCustomCommand("XTND XMIT\r\n", False, _
        New AsyncCallback(AddressOf XtndXmitCallback), pop)
End Sub
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3ExecuteCustomCommand(String, Boolean)


Pop3.BeginLogin Method

Pop3BeginLogin Method

Note: This API is now obsolete.

Begins an asynchronous request for a logging in an account on a POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use LoginAsync instead.")]
public IAsyncResult BeginLogin(
    string targetName,
    string domain,
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use LoginAsync instead.")>
Public Function BeginLogin (
    targetName As String,
    domain As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

targetName
Type: SystemString
The Service Principal Name of the server. Used only with GSSAPI/Kerberos authentication. You can leave it a null reference (Nothing in Visual Basic) or an empty string.
domain
Type: SystemString
The user account domain on the server. Used only with NTLM and GSSAPI authentication. You can leave it a null reference to use the current domain.
accountName
Type: SystemString
The user account name on the server. You can leave it a null reference when using NTLM or GSSAPI and wish to authenticate as the current Windows user.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous login process.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Examples
This sample demonstrates asynchronous logging in a mailbox and use of a callback function in a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // A callback function.
    private static void LoginCallback(IAsyncResult result)
    {
        Pop3 pop = (Pop3)result.AsyncState;
        pop.EndLogin();
        Console.WriteLine("Overall size of all messages in the inbox is " +
            pop.InboxSize + " bytes");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        pop.Connect("pop.somehost.com");

        // Initiate an asynchronous login attempt.
        IAsyncResult ar = pop.BeginLogin(null, null, "jdoe", "secret",
            AuthenticationMethods.Auto, AuthenticationOptions.None,
            null, new AsyncCallback(LoginCallback), pop);

        // Simulate some lengthy work here. At the same time,
        // login is executed on another thread.
        System.Threading.Thread.Sleep(3000);

        // If the login attempt is still in progress, then wait until it's finished.
        while (pop.IsBusy) ar.AsyncWaitHandle.WaitOne();

        // Disconnect from the server.
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' A callback function.
    Private Shared Sub LoginCallback(ByVal result As IAsyncResult)
        Dim pop As New Pop3
        pop = result.AsyncState
        pop.EndLogin()
        Console.WriteLine("Overall size of all messages in the inbox is " & _
            pop.InboxSize & " bytes")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3
        pop.Connect("pop.somehost.com")

        ' Initiate an asynchronous login attempt.
        Dim ar = pop.BeginLogin(Nothing, Nothing, "jdoe", "secret", _
            AuthenticationMethods.Auto, AuthenticationOptions.None, _
            Nothing, New AsyncCallback(AddressOf LoginCallback), pop)

        ' Simulate some lengthy work here. At the same time
        ' login is executed on another thread.
        System.Threading.Thread.Sleep(3000)

        ' If the login attempt is still in progress, then wait until it's finished.
        While pop.IsBusy
            ar.AsyncWaitHandle.WaitOne()
        End While

        ' Disconnect from the server.
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
Pop3BeginConnect(String, Int32, Boolean, AsyncCallback, Object)
MailBeeSaslMethod


Pop3.BeginStartTls Method

Pop3BeginStartTls Method

Note: This API is now obsolete.

Begins an asynchronous request to start TLS/SSL negotiation with the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use StartTlsAsync instead.")]
public IAsyncResult BeginStartTls(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use StartTlsAsync instead.")>
Public Function BeginStartTls (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous TLS/SSL negotiation.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of StartTls.
Examples
Asynchronous TLS/SSL negotiation with the POP3 server in WinForms application. This sample also handles TlsStarted event. Wait method is used to wait for the asynchronous method completion, since .NET's standard WaitOne(Int32, Boolean) cannot process events.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// Put the code below inside your class

// TlsStarted event handler
private void OnTlsStarted(object sender, TlsStartedEventArgs e)
{
    MessageBox.Show("TLS/SSL negotiation complete. Secure connection is ready.");
}

// The actual code
private void Form1_Load(object sender, System.EventArgs e)
{
    Pop3 pop = new Pop3();

    // Let MailBee process events
    pop.RaiseEventsViaMessageLoop = false;

    pop.TlsStarted += new TlsStartedEventHandler(OnTlsStarted);

    pop.Connect("mail.domain.com");

    // Initiate an asynchronous TLS/SSL negotiation
    pop.BeginStartTls(null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above
        pop.Wait(0);
    }

    // If the connection was not established during execution of the lengthy
    // work, wait until it's established
    pop.Wait();

    // End the connection request
    pop.EndStartTls();

    // The connection is now under TLS/SSL layer!
    // Disconnect from the server
    pop.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail;

' Put the code below inside your class

' TlsStarted event handler
Private Shared Sub OnTlsStarted(ByVal sender As Object, ByVal e As TlsStartedEventArgs)
    MsgBox("TLS/SSL negotiation complete. Secure connection is ready.")
End Sub

' The actual code
Private Shared Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim pop As New Pop3

    ' Let MailBee process events
    pop.RaiseEventsViaMessageLoop = False

    AddHandler pop.TlsStarted, AddressOf OnTlsStarted

    pop.Connect("mail.domain.com")

    ' Initiate an asynchronous TLS/SSL negotiation
    pop.BeginStartTls(Nothing, Nothing)

    ' Simulate some lengthy work here...
    Dim i As Integer
    For i = 1 To 100
        ' Make a portion of the work
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above
        pop.Wait(0)
    Next

    ' If the connection was not established during execution of the lengthy
    ' work, wait until it's established.
    pop.Wait()

    ' End the connection request.
    pop.EndStartTls()

    ' The connection is now under TLS/SSL layer!
    ' Disconnect from the server
    pop.Disconnect()
End Sub
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3StartTls


Pop3.Connect Method

Pop3Connect Method
Connects to a POP3 server.
Overload List
Name | Description
Connect(String) | Connects to a POP3 server on the standard POP3 port (110).
Connect(String, Int32) | Connects to a POP3 server.
Connect(String, Int32, Boolean) | Connects to a POP3 server.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Connect Method (String)

Pop3Connect Method (String)
Connects to a POP3 server on the standard POP3 port (110).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect(
    string serverName
)
Public Function Connect (
    serverName As String
) As Boolean

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.

Return Value

Type: Boolean
true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If Pipelining is true and the server supports pipelining, MailBee will use it and join POP3 commands in batches whenever possible (see Connect(String, Int32, Boolean) overload for more information).
Note Note
By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.
Examples
This sample connects to the POP3 server, downloads the last message entirely, and displays its body text. If the message is HTML formatted, plain-text version is displayed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);
Console.WriteLine(msg.BodyPlainText);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Dim msg As MailMessage
msg = pop.DownloadEntireMessage(pop.InboxMessageCount)
Console.WriteLine(msg.BodyPlainText)
pop.Disconnect()
See Also

Reference

Pop3 Class
Connect Overload
MailBee.Pop3Mail Namespace


Pop3.Connect Method (String, Int32)

Pop3Connect Method (String, Int32)
Connects to a POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect(
    string serverName,
    int port
)
Public Function Connect (
    serverName As String,
    port As Integer
) As Boolean

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard POP3 port is 110. For TLS/SSL connections, dedicated port is 995 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).

Return Value

Type: Boolean
true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If Pipelining is true and the server supports pipelining, MailBee will use it and join POP3 commands in batches whenever possible (see Connect(String, Int32, Boolean) overload for more information).
Note Note
By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.
Examples
This sample connects to the POP3 server, downloads the last message entirely, and displays filenames of all attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com", 110);
pop.Login("jdoe", "secret");
MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);
foreach (Attachment attach in msg.Attachments)
{
    Console.WriteLine(attach.Filename);
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim pop As New Pop3
pop.Connect("mail.domain.com", 110)
pop.Login("jdoe", "secret")
Dim msg As MailMessage
msg = pop.DownloadEntireMessage(pop.InboxMessageCount)
For Each attach As Attachment In msg.Attachments
    Console.WriteLine(attach.Filename)
Next
pop.Disconnect()
See Also

Reference

Pop3 Class
Connect Overload
MailBee.Pop3Mail Namespace


Pop3.Connect Method (String, Int32, Boolean)

Pop3Connect Method (String, Int32, Boolean)
Connects to a POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect(
    string serverName,
    int port,
    bool pipelining
)
Public Function Connect (
    serverName As String,
    port As Integer,
    pipelining As Boolean
) As Boolean

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard POP3 port is 110. For TLS/SSL connections, dedicated port is 995 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).
pipelining
Type: SystemBoolean
Specifies whether to use commands pipelining if it's supported by the server.

Return Value

Type: Boolean
true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If pipelining is true and the server supports pipelining, MailBee will join POP3 commands in batches whenever possible, providing major performance boost in scenarios when multiple messages are downloaded or deleted at once. The methods which take advantage of pipelining are: DownloadMessageHeaders(Int32, Int32, Int32), DownloadEntireMessages(Int32, Int32), DeleteMessages(Int32, Int32), and their asynchronous versions (BeginDownloadMessages(Int32, Int32, Int32, AsyncCallback, Object), BeginDeleteMessages(Int32, Int32, AsyncCallback, Object)). The performance may increase 10+ times if many messages (20 and more) are processed.
Note Note
By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.
Examples
This sample connects to the POP3 server, downloads headers for the first 5 messages, and displays them. If the server supports pipelining, all 5 message headers will be downloaded in a single round-trip to the server.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com", 110, true);
pop.Login("jdoe", "secret");
MailMessageCollection msgHeaders = pop.DownloadMessageHeaders(1, 5);
foreach (MailMessage msgHeader in msgHeaders)
{
    Console.WriteLine("Message #" + msgHeader.IndexOnServer + ":\r\n" + msgHeader.RawHeader);
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class)
Dim pop As Pop3
pop.Connect("mail.domain.com", 110, True)
pop.Login("jdoe", "secret")
Dim msgHeaders As MailMessageCollection
msgHeaders = pop.DownloadMessageHeaders(1, 5)
For Each msgHeader As MailMessage In msgHeaders
    Console.WriteLine("Message #" & msgHeader.IndexOnServer & ":\r\n" & msgHeader.RawHeader)
Next
pop.Disconnect()
See Also

Reference

Pop3 Class
Connect Overload
MailBee.Pop3Mail Namespace


Pop3.ConnectAsync Method

Pop3ConnectAsync Method
Overload List
 | Name | Description
Public method | ConnectAsync(String) | async/await version of Connect(String).
Public method | ConnectAsync(String, Int32) | async/await version of Connect(String, Int32).
Public method | ConnectAsync(String, Int32, Boolean) | async/await version of Connect(String, Int32, Boolean).
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.ConnectAsync Method (String)

Pop3ConnectAsync Method (String)
async/await version of Connect(String).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync(
    string serverName
)
Public Function ConnectAsync (
    serverName As String
) As Task(Of Boolean)

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
ConnectAsync Overload
MailBee.Pop3Mail Namespace


Pop3.ConnectAsync Method (String, Int32)

Pop3ConnectAsync Method (String, Int32)
async/await version of Connect(String, Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync(
    string serverName,
    int port
)
Public Function ConnectAsync (
    serverName As String,
    port As Integer
) As Task(Of Boolean)

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard POP3 port is 110. For TLS/SSL connections, dedicated port is 995 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
ConnectAsync Overload
MailBee.Pop3Mail Namespace


Pop3.ConnectAsync Method (String, Int32, Boolean)

Pop3ConnectAsync Method (String, Int32, Boolean)
async/await version of Connect(String, Int32, Boolean).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync(
    string serverName,
    int port,
    bool pipelining
)
Public Function ConnectAsync (
    serverName As String,
    port As Integer,
    pipelining As Boolean
) As Task(Of Boolean)

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
port
Type: SystemInt32
The port on which to communicate with the server. The standard POP3 port is 110. For TLS/SSL connections, dedicated port is 995 (however, TLS/SSL connections via regular port are possible too, see SslMode and StartTls topics).
pipelining
Type: SystemBoolean
Specifies whether to use commands pipelining if it's supported by the server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a connection attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
ConnectAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DeleteMessage Method

Pop3DeleteMessage Method
Flags the specified message for deletion from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteMessage(
    int index
)
Public Function DeleteMessage (
    index As Integer
) As Boolean

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: Boolean
true if the message has been flagged for deletion; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If more than one message is deleted, it's recommended to use DeleteMessages(Int32, Int32) method when possible, since it can operate much faster if the server supports pipelining.
Note Note
Messages flagged for deletion are actually removed from the server on Disconnect method call. Until this moment, the developer can remove the deletion status for all messages flagged as deleted by calling ResetDeletes method.
Examples
This sample deletes the first message from a user account on a POP3 server.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
pop.DeleteMessage(1);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
pop.DeleteMessage(1)
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DeleteMessages(Int32, Int32)


Pop3.DeleteMessageAsync Method

Pop3DeleteMessageAsync Method
async/await version of DeleteMessage(Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteMessageAsync(
    int index
)
Public Function DeleteMessageAsync (
    index As Integer
) As Task(Of Boolean)

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the message has been flagged for deletion; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DeleteMessages Method

Pop3DeleteMessages Method
Flags messages for deletion from the server.
Overload List
Name | Description
DeleteMessages | Flags all the messages in the inbox for deletion from the server.
DeleteMessages(Int32, Int32) | Flags the specified range of messages for deletion from the server.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DeleteMessages Method

Pop3DeleteMessages Method
Flags all the messages in the inbox for deletion from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteMessages()
Public Function DeleteMessages As Boolean

Return Value

Type: Boolean
true if the messages have been flagged for deletion or the inbox is empty; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the POP3 server supports pipelining, this method will flag all the messages in a single network operation, which greatly increases performance and reduces network traffic.
Note Note
Messages flagged for deletion are actually removed from the server on Disconnect method call. Until this moment, the developer can remove the deletion status for all messages flagged as deleted by calling ResetDeletes method.
Examples
This sample deletes all the messages in the inbox.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
pop.DeleteMessages();
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
pop.DeleteMessages()
pop.Disconnect()
See Also

Reference

Pop3 Class
DeleteMessages Overload
MailBee.Pop3Mail Namespace


Pop3.DeleteMessages Method (Int32, Int32)

Pop3DeleteMessages Method (Int32, Int32)
Flags the specified range of messages for deletion from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteMessages(
    int startIndex,
    int count
)
Public Function DeleteMessages (
    startIndex As Integer,
    count As Integer
) As Boolean

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range being deleted.
count
Type: SystemInt32
Number of messages to be flagged for deletion, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be flagged for deletion.

Return Value

Type: Boolean
true if the messages have been flagged for deletion or count is 0; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the POP3 server supports pipelining, this method will flag all the messages in the specified range in a single network operation, which greatly increases performance and reduces network traffic.
Note Note
Messages flagged for deletion are actually removed from the server on Disconnect method call. Until this moment, the developer can remove the deletion status for all messages flagged as deleted by calling ResetDeletes method.
Examples
This sample deletes all the messages in the inbox starting at message #10. The messages in the range from 1 to 9 are not affected.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
pop.DeleteMessages(10, -1);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
pop.DeleteMessages(10, -1)
pop.Disconnect()
See Also

Reference

Pop3 Class
DeleteMessages Overload
MailBee.Pop3Mail Namespace


Pop3.DeleteMessagesAsync Method

Pop3DeleteMessagesAsync Method
Overload List
 | Name | Description
Public method | DeleteMessagesAsync | async/await version of DeleteMessages.
Public method | DeleteMessagesAsync(Int32, Int32) | async/await version of DeleteMessages(Int32, Int32).
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DeleteMessagesAsync Method

Pop3DeleteMessagesAsync Method
async/await version of DeleteMessages.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteMessagesAsync()
Public Function DeleteMessagesAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the messages have been flagged for deletion or the inbox is empty; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DeleteMessagesAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DeleteMessagesAsync Method (Int32, Int32)

Pop3DeleteMessagesAsync Method (Int32, Int32)
async/await version of DeleteMessages(Int32, Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DeleteMessagesAsync(
    int startIndex,
    int count
)
Public Function DeleteMessagesAsync (
    startIndex As Integer,
    count As Integer
) As Task(Of Boolean)

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range being deleted.
count
Type: SystemInt32
Number of messages to be flagged for deletion, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be flagged for deletion.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the messages have been flagged for deletion or count is 0; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DeleteMessagesAsync Overload
MailBee.Pop3Mail Namespace


Pop3.Disconnect Method

Pop3Disconnect Method
Disconnects from the POP3 server and releases any used resources.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Disconnect()
Public Function Disconnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
On successful completion of this method, all the messages marked as deleted during the POP3 session are physically deleted by the server. If this method fails, the connection is still closed and all network resources are freed, but it's undefined whether the messages marked for deletion were really deleted or not.
Examples
This sample deletes the first message in the inbox.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
pop.DeleteMessage(1);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class)
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
pop.DeleteMessage(1)
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DisconnectAsync Method

Pop3DisconnectAsync Method
async/await version of Disconnect.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DisconnectAsync()
Public Function DisconnectAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Dispose Method

Pop3Dispose Method
Overload List
 | Name | Description
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Dispose Method

Pop3Dispose Method
Closes opened network connections (if any) and releases any used system resources.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
Usually, the developer does not need to call this method. It's recommended to call Disconnect method to close the connections and free the resources.
See Also

Reference

Pop3 Class
Dispose Overload
MailBee.Pop3Mail Namespace


Pop3.Dispose Method (Boolean)

Pop3Dispose Method (Boolean)
When overridden in a derived class, must release unmananged and optionally managed resources used by the component.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Remarks
If the derived class does not use any additional resources, this method does not need to be overridden. If, however, it's overridden, the developer must also call Dispose method of the base class.
See Also

Reference

Pop3 Class
Dispose Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessage Method

Pop3DownloadEntireMessage Method
Completely downloads the specified message from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DownloadEntireMessage(
    int index
)
Public Function DownloadEntireMessage (
    index As Integer
) As MailMessage

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: MailMessage
On success, a MailMessage object containing the entire message, including the message header, all the body parts and attachments; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If more than one message is downloaded, it's recommended to use DownloadEntireMessages(Int32, Int32) method when possible, since it can operate faster if the server supports pipelining and many small messages are downloaded.

However, if you're dealing with large e-mails (more than 1MB), it's recommended to download and process them one-by-one to avoid out-of-memory issues. Also, set List flag in InboxPreloadOptions property value prior to calling Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method. This will eliminate memory buffer re-allocations during downloading. You can also use both DownloadEntireMessage(Int32) method to download large e-mails and DownloadEntireMessages(Int32, Int32) overload to download ranges of smaller e-mails between larger ones.

Examples
This sample downloads the last message from an inbox on a POP3 server, saves it as index.htm file, and also saves the embedded pictures and other linked objects, making it possible to open index.htm file in a browser and have the message being correctly displayed (including all the graphics, styles, etc).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml;
msg.SaveHtmlAndRelatedFiles(@"C:\Temp\index.htm");
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Dim msg As MailMessage
msg = pop.DownloadEntireMessage(pop.InboxMessageCount)
msg.Parser.PlainToHtmlMode = PlainToHtmlAutoConvert.IfNoHtml
msg.SaveHtmlAndRelatedFiles("C:\Temp\index.htm")
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DownloadEntireMessages(Int32, Int32)


Pop3.DownloadEntireMessageAsync Method

Pop3DownloadEntireMessageAsync Method
async/await version of DownloadEntireMessage(Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessage> DownloadEntireMessageAsync(
    int index
)
Public Function DownloadEntireMessageAsync (
    index As Integer
) As Task(Of MailMessage)

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: Task MailMessage
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessage object containing the entire message, including the message header, all the body parts and attachments; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessages Method

Pop3DownloadEntireMessages Method
Completely downloads all or the specified messages from the server.
Overload List
Name | Description
DownloadEntireMessages | Completely downloads all the messages from the inbox on the server.
DownloadEntireMessages(Int32, Int32) | Completely downloads the messages in the specified range from the server.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessages Method

Pop3DownloadEntireMessages Method
Completely downloads all the messages from the inbox on the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadEntireMessages()
Public Function DownloadEntireMessages As MailMessageCollection

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.

Note Note
As this method downloads all e-mails in the inbox, you must have plenty of memory to have such operation done. In case of out-of-memory issues, download large emails individually.

You can use GetMessageSizes method to learn the sizes of all e-mails in the inbox without downloading them. For instance, if you found that you have 10 small e-mails less than 10MB total, then a large 100MB e-mail, then many small e-mails 500MB total, you can first download 10 small emails with a single call of DownloadEntireMessages(Int32, Int32) overload, process them, then download a large e-mail with DownloadEntireMessage(Int32) method, process it, and then use DownloadEntireMessages(Int32, Int32) overload again several times to get e-mails downloaded in approx. 100MB groups. This way, you won't need to download each and every e-mail one-by-one (which would defeat the idea of using pipelining) and still won't use too much memory. Small e-mails will be downloaded in a batch while large ones will get downloaded on their own.

Examples
This sample completely downloads all the messages from the inbox, and displays the filename and data size for each of the attachments of each downloaded message. MessageDataChunkReceived event is used to track the download progress. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // MessageDataChunkReceived event handler.
    private static void OnMessageDataChunkReceived(object sender,
        Pop3MessageDataChunkReceivedEventArgs e)
    {
        Console.WriteLine(e.BytesJustReceived +
            " bytes of the message #" + e.MessageNumber + " received");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");

        // Subscribe to the MessageDataChunkReceived event.
        pop.MessageDataChunkReceived +=
            new Pop3MessageDataChunkReceivedEventHandler(OnMessageDataChunkReceived);

        // Download the messages.
        MailMessageCollection msgs = pop.DownloadEntireMessages();

        // Display some information about downloaded messages.
        foreach (MailMessage msg in msgs)
        {
            string attachFilenames = string.Empty;
            if (msg.Attachments.Count == 0)
            {
                attachFilenames = "no";
            }
            else
            {
                foreach (Attachment attach in msg.Attachments)
                {
                    if (attachFilenames != string.Empty)
                    {
                        attachFilenames += "; ";
                    }
                    attachFilenames += attach.Filename;
                }
            }
            Console.WriteLine("Message #" + msg.IndexOnServer +
                " contains " + attachFilenames + " attachment(s)");
        }

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' MessageDataChunkReceived event handler.
    Private Shared Sub OnMessageDataChunkReceived(ByVal sender As Object, _
        ByVal e As Pop3MessageDataChunkReceivedEventArgs)
        Console.WriteLine(e.BytesJustReceived & _
            " bytes of the message #" & e.MessageNumber & " received")
    End Sub

    ' The actual code
    Shared Sub Main(ByVal args As String())
        Dim pop As Pop3
        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")

        ' Subscribe to the MessageDataChunkReceived event.
        AddHandler pop.MessageDataChunkReceived, AddressOf OnMessageDataChunkReceived

        ' Download the messages
        Dim msgs As MailMessageCollection
        msgs = pop.DownloadEntireMessages()

        ' Display some information about downloaded messages.
        For Each msg As MailMessage In msgs
            Dim attachFilenames As String
            attachFilenames = String.Empty
            If msg.Attachments.Count = 0 Then
                attachFilenames = "no"
            Else
                For Each attach As Attachment In msg.Attachments
                    If attachFilenames <> String.Empty Then
                        attachFilenames &= "; "
                    End If
                    attachFilenames &= attach.Filename
                Next
            End If
            Console.WriteLine("Message #" & msg.IndexOnServer & _
                " contains " & msg.Attachments.Count & " attachment(s)")
        Next
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
DownloadEntireMessages Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessages Method (Int32, Int32)

Pop3DownloadEntireMessages Method (Int32, Int32)
Completely downloads the messages in the specified range from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadEntireMessages(
    int startIndex,
    int count
)
Public Function DownloadEntireMessages (
    startIndex As Integer,
    count As Integer
) As MailMessageCollection

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.

Note Note
As this method downloads multiple e-mails at once, you must have plenty of memory to have such operation done. In case of out-of-memory issues, reduce count or download large emails individually.

You can use GetMessageSizes method to learn the sizes of all e-mails in the inbox without downloading them. For instance, if you found that you have 10 small e-mails less than 10MB total, then a large 100MB e-mail, then many small e-mails 500MB total, you can first download 10 small emails with a single call of DownloadEntireMessages(Int32, Int32) overload, process them, then download a large e-mail with DownloadEntireMessage(Int32) method, process it, and then use DownloadEntireMessages(Int32, Int32) overload again several times to get e-mails downloaded in approx. 100MB groups. This way, you won't need to download each and every e-mail one-by-one (which would defeat the idea of using pipelining) and still won't use too much memory. Small e-mails will be downloaded in a batch while large ones will get downloaded on their own.

Examples
This sample completely downloads the last 10 messages from the inbox, and displays the number of attachments for each downloaded message. MessageDownloaded event is used to track the download progress. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // MessageDownloaded event handler.
    private static void OnMessageDownloaded(object sender, Pop3MessageDownloadedEventArgs e)
    {
        Console.WriteLine("Message #" + e.MessageNumber + " downloaded");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");

        // Subscribe to the MessageDownloaded event.
        pop.MessageDownloaded += new Pop3MessageDownloadedEventHandler(OnMessageDownloaded);

        // Download the messages.
        MailMessageCollection msgs = pop.DownloadEntireMessages(pop.InboxMessageCount - 9, 10);

        // Display some information about downloaded messages.
        foreach (MailMessage msg in msgs)
        {
            Console.WriteLine("Message #" + msg.IndexOnServer +
                " contains " + msg.Attachments.Count + " attachment(s)");
        }

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' MessageDownloaded event handler.
    Private Shared Sub OnMessageDownloaded(ByVal sender As Object, ByVal e As Pop3MessageDownloadedEventArgs)
        Console.WriteLine("Message #" & e.MessageNumber & " downloaded")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As Pop3
        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")

        ' Subscribe to the MessageDownloaded event.
        AddHandler pop.MessageDownloaded, AddressOf OnMessageDownloaded

        ' Download the messages.
        Dim msgs As MailMessageCollection
        msgs = pop.DownloadEntireMessages(pop.InboxMessageCount - 9, 10)

        ' Display some information about downloaded messages.
        For Each msg As MailMessage In msgs
            Console.WriteLine("Message #" & msg.IndexOnServer & _
                " contains " & msg.Attachments.Count & " attachment(s)")
        Next

        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
DownloadEntireMessages Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessagesAsync Method

Pop3DownloadEntireMessagesAsync Method
Overload List
 | Name | Description
Public method | DownloadEntireMessagesAsync | async/await version of DownloadEntireMessages.
Public method | DownloadEntireMessagesAsync(Int32, Int32) | async/await version of DownloadEntireMessages(Int32, Int32).
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessagesAsync Method

Pop3DownloadEntireMessagesAsync Method
async/await version of DownloadEntireMessages.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadEntireMessagesAsync()
Public Function DownloadEntireMessagesAsync As Task(Of MailMessageCollection)

Return Value

Type: Task MailMessageCollection
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadEntireMessagesAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadEntireMessagesAsync Method (Int32, Int32)

Pop3DownloadEntireMessagesAsync Method (Int32, Int32)
async/await version of DownloadEntireMessages(Int32, Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadEntireMessagesAsync(
    int startIndex,
    int count
)
Public Function DownloadEntireMessagesAsync (
    startIndex As Integer,
    count As Integer
) As Task(Of MailMessageCollection)

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.

Return Value

Type: Task MailMessageCollection
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessageCollection containing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadEntireMessagesAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeader Method

Pop3DownloadMessageHeader Method
Overload List
Name | Description
DownloadMessageHeader(Int32) | Downloads the header of the specified message from the server.
DownloadMessageHeader(Int32, Int32) | Downloads the header and the specified number of body lines of the message on the server.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeader Method (Int32)

Pop3DownloadMessageHeader Method (Int32)
Downloads the header of the specified message from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DownloadMessageHeader(
    int index
)
Public Function DownloadMessageHeader (
    index As Integer
) As MailMessage

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: MailMessage
On success, a MailMessage object containing the downloaded message header; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If more than one message header is downloaded, it's recommended to use DownloadMessageHeaders(Int32, Int32, Int32) method when possible, since it can operate much faster if the server supports pipelining.
Examples
This sample downloads header of the last message from an inbox on a POP3 server, and prints e-mail addresses of all the recipients of this message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
MailMessage msg = pop.DownloadMessageHeader(pop.InboxMessageCount);
EmailAddressCollection recipients = msg.GetAllRecipients();
foreach (EmailAddress address in recipients)
{
    Console.WriteLine(address.Email);
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Dim msg As MailMessage
msg = pop.DownloadMessageHeader(pop.InboxMessageCount)
Dim recipients As EmailAddressCollection
recipients = msg.GetAllRecipients()
For Each address As EmailAddress In recipients
    Console.WriteLine(address.Email)
Next
pop.Disconnect()
See Also

Reference

Pop3 Class
DownloadMessageHeader Overload
MailBee.Pop3Mail Namespace
Pop3DownloadMessageHeaders(Int32, Int32, Int32)


Pop3.DownloadMessageHeader Method (Int32, Int32)

Pop3DownloadMessageHeader Method (Int32, Int32)
Downloads the header and the specified number of body lines of the message on the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DownloadMessageHeader(
    int index,
    int bodyLineCount
)
Public Function DownloadMessageHeader (
    index As Integer,
    bodyLineCount As Integer
) As MailMessage

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire message.

Return Value

Type: MailMessage
On success, a MailMessage object containing the downloaded partial message; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

When bodyLineCount is 0, only the message header is downloaded. When bodyLineCount is -1, this method is equivalent to DownloadEntireMessage(Int32) method.

Setting bodyLineCount to a positive value allows the developer to implement message body preview feature. In this case, it's recommended to set bodyLineCount >= 20 since the first 5-15 lines of the message source body are often filled with the special information and do not contain the actual body text.

If bodyLineCount is set to a certain value (such as 100), small messages having less than 100 lines in the message source body will be downloaded completely. Larger messages will be parsed partially. For instance, if 100 body lines of the message have been received, and the message contains an attachment which starts at 80-th line and ends at 150-th line of the message source body (so it has not fitted in the 100 lines received), MailBee will still add this attachment into Attachments collection, but the attachment binary data will obviously be incomplete.

Note Note
If more than one message header is downloaded, it's recommended to use DownloadMessageHeaders(Int32, Int32, Int32) method when possible, since it can operate much faster if the server supports pipelining.
Examples
This sample downloads the header and 20 lines of the message source body for the last message in an inbox on a POP3 server, and prints the message body text (if any) MailBee managed to extract from the downloaded 20 lines of the message source body.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
MailMessage msg = pop.DownloadMessageHeader(pop.InboxMessageCount, 20);
Console.WriteLine(msg.BodyPlainText);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Dim msg As MailMessage
msg = pop.DownloadMessageHeader(pop.InboxMessageCount, 20)
Console.WriteLine(msg.BodyPlainText)
pop.Disconnect()
See Also

Reference

Pop3 Class
DownloadMessageHeader Overload
MailBee.Pop3Mail Namespace
Pop3DownloadMessageHeaders(Int32, Int32, Int32)


Pop3.DownloadMessageHeaderAsync Method

Pop3DownloadMessageHeaderAsync Method
Overload List
 | Name | Description
Public method | DownloadMessageHeaderAsync(Int32) | async/await version of DownloadMessageHeader(Int32).
Public method | DownloadMessageHeaderAsync(Int32, Int32) | async/await version of DownloadMessageHeader(Int32, Int32).
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeaderAsync Method (Int32)

Pop3DownloadMessageHeaderAsync Method (Int32)
async/await version of DownloadMessageHeader(Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessage> DownloadMessageHeaderAsync(
    int index
)
Public Function DownloadMessageHeaderAsync (
    index As Integer
) As Task(Of MailMessage)

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: Task MailMessage
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessage object containing the downloaded message header; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadMessageHeaderAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeaderAsync Method (Int32, Int32)

Pop3DownloadMessageHeaderAsync Method (Int32, Int32)
async/await version of DownloadMessageHeader(Int32, Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessage> DownloadMessageHeaderAsync(
    int index,
    int bodyLineCount
)
Public Function DownloadMessageHeaderAsync (
    index As Integer,
    bodyLineCount As Integer
) As Task(Of MailMessage)

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire message.

Return Value

Type: Task MailMessage
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessage object containing the downloaded partial message; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadMessageHeaderAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeaders Method

Pop3DownloadMessageHeaders Method
Downloads headers of all or the specified messages from the server.
Overload List
Name | Description
DownloadMessageHeaders | Downloads headers of all messages in the inbox on the server.
DownloadMessageHeaders(Int32, Int32) | Downloads the header of each message in the specified range from the server.
DownloadMessageHeaders(Int32, Int32, Int32) | Downloads the header and the specified number of body lines of each message in the specified range from the server.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeaders Method

Pop3DownloadMessageHeaders Method
Downloads headers of all messages in the inbox on the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadMessageHeaders()
Public Function DownloadMessageHeaders As MailMessageCollection

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection object containing the downloaded message headers; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.
Examples
This sample downloads headers of all the messages in the mailbox, and displays the following information for each message:
  • The display name of the sender (or the e-mail address if the display name is not available)
  • The display names of the recipients (or the e-mail address when the particular display name is not available)
The message information is displayed in descending order (from newer messages to older ones).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");

// Download headers of all the messages in the inbox.
MailMessageCollection msgs = pop.DownloadMessageHeaders();

// Reverse the order of the elements to make newer messages appear first in the collection.
msgs.Reverse();

foreach (MailMessage msg in msgs)
{
    // Get the sender.
    string sender = msg.From.DisplayName;
    if (sender == string.Empty)
    {
        sender = msg.From.Email;
    }

    // Get the list of recipients.
    string recipients = string.Empty;
    foreach (EmailAddress address in msg.GetAllRecipients())
    {
        string recipient = address.DisplayName;
        if (recipient == string.Empty)
        {
            recipient = address.Email;
        }

        if (recipients == string.Empty)
        {
            recipients += recipient;
        }
        else
        {
            recipients += ", " + recipient;
        }
    }

    Console.WriteLine("Message #" + msg.IndexOnServer + " was originally sent by " + sender + " to " + recipients);
}

pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")

' Download headers of all the messages in the inbox.
Dim msgs As MailMessageCollection
msgs = pop.DownloadMessageHeaders()

' Reverse the order of the elements to make newer messages appear first in the collection.
msgs.Reverse()

For Each msg As MailMessage In msgs
    ' Get the sender.
    Dim sender As String
    sender = msg.From.DisplayName
    If sender = String.Empty Then
        sender = msg.From.Email
    End If

    ' Get the list of recipients.
    Dim recipients As String
    recipients = String.Empty
    For Each address As EmailAddress In msg.GetAllRecipients()
        Dim recipient As String = address.DisplayName
        If recipient = String.Empty Then
            recipient = address.Email
        End If

        If recipients = String.Empty Then
            recipients = recipients & recipient
        Else
            recipients = recipients & ", " & recipient
        End If
    Next

    Console.WriteLine("Message #" & msg.IndexOnServer & " was originally sent by " & sender & " to " & recipients)
Next

pop.Disconnect()
See Also

Reference

Pop3 Class
DownloadMessageHeaders Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeaders Method (Int32, Int32)

Pop3DownloadMessageHeaders Method (Int32, Int32)
Downloads the header of each message in the specified range from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadMessageHeaders(
    int startIndex,
    int count
)
Public Function DownloadMessageHeaders (
    startIndex As Integer,
    count As Integer
) As MailMessageCollection

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection object containing the downloaded message headers; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.
Examples
This sample downloads headers of the last 10 messages in the mailbox, and displays the following information for each message:
  • Subject: field
  • Date and time when the message was created
  • Date and time when the message was delivered to the mailbox
The message information is displayed in descending order (from newer messages to older ones).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");

// Download headers of the last 10 messages.
MailMessageCollection msgs = pop.DownloadMessageHeaders(pop.InboxMessageCount - 9, 10);

// Reverse the order of the elements to make newer messages appear first in the collection.
msgs.Reverse();

// Display Date, DateReceived, and Subject.
foreach (MailMessage msg in msgs)
{
    Console.WriteLine("Message #" + msg.IndexOnServer + ", created at " + msg.Date + " and received at " + msg.DateReceived + ", has Subject: " + msg.Subject);
}

pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")

' Download headers of the last 10 messages.
Dim msgs As MailMessageCollection = pop.DownloadMessageHeaders(pop.InboxMessageCount - 9, 10)

' Reverse the order of the elements to make newer messages appear first in the collection.
msgs.Reverse()

' Display Date, DateReceived, and Subject.
For Each msg As MailMessage In msgs
    Console.WriteLine("Message #" & msg.IndexOnServer & ", created at " & msg.Date & " and received at " & msg.DateReceived & ", has Subject: " & msg.Subject)
Next

pop.Disconnect()
See Also

Reference

Pop3 Class
DownloadMessageHeaders Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeaders Method (Int32, Int32, Int32)

Pop3DownloadMessageHeaders Method (Int32, Int32, Int32)
Downloads the header and the specified number of body lines of each message in the specified range from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection DownloadMessageHeaders(
    int startIndex,
    int count,
    int bodyLineCount
)
Public Function DownloadMessageHeaders (
    startIndex As Integer,
    count As Integer,
    bodyLineCount As Integer
) As MailMessageCollection

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire messages.

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection object containing the downloaded partial messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

When bodyLineCount is 0, only the message header is downloaded. When bodyLineCount is -1, this method is equivalent to DownloadEntireMessage(Int32) method.

Setting bodyLineCount to a positive value allows the developer to implement message body preview feature. In this case, it's recommended to set bodyLineCount >= 20 since the first 5-15 lines of the message source body are often filled with the special information and do not contain the actual body text.

If bodyLineCount is set to a certain value (such as 100), small messages having less than 100 lines in the message source body will be downloaded completely. Larger messages will be parsed partially. For instance, if 100 body lines of the message have been received, and the message contains an attachment which starts at 80-th line and ends at 150-th line of the message source body (so it has not fitted in the 100 lines received), MailBee will still add this attachment into Attachments collection, but the attachment binary data will obviously be incomplete.

Note Note
If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.
Examples
This sample downloads the header and 300 lines (approx. 20-30 KBytes) of the message source body for every message in an inbox on a POP3 server, and displays whether the messages probably contain attachments or not.
Note Note
If no attachment is found in a partial message, there is still no guarantee the message would not contain attachments if was downloaded completely; the message may just have a large body text section which spans more than 300 lines in the entire message. If more body lines (such as 1000) are downloaded with the header, attachment detection quality will be higher, but at the cost of increased network traffic with the server. Another approach is to use HasAttachments property, however, it's still not 100% accurate, because it may indicate the message does have attachments if it actually doesn't but the message header reports the message has at least one attachment.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
MailMessageCollection msgs = pop.DownloadMessageHeaders(1, -1, 300);
foreach (MailMessage msg in msgs)
{
    string attachmentStatus = msg.Attachments.Count == 0 ? "no" : "some";
    Console.WriteLine("Message #" + msg.IndexOnServer + " probably contains " + attachmentStatus + " attachment(s)");
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Dim msgs As MailMessageCollection
msgs = pop.DownloadMessageHeaders(1, -1, 300)
For Each msg As MailMessage In msgs
    Dim attachmentStatus As String
    If msg.Attachments.Count = 0 Then
        attachmentStatus = "no"
    Else
        attachmentStatus = "some"
    End If
    Console.WriteLine("Message #" & msg.IndexOnServer & " probably contains " & _
        attachmentStatus & " attachment(s)")
Next
pop.Disconnect()
See Also

Reference

Pop3 Class
DownloadMessageHeaders Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeadersAsync Method

Pop3DownloadMessageHeadersAsync Method
Overload List
 | Name | Description
Public method | DownloadMessageHeadersAsync | async/await version of DownloadMessageHeaders.
Public method | DownloadMessageHeadersAsync(Int32, Int32) | async/await version of DownloadMessageHeaders(Int32, Int32).
Public method | DownloadMessageHeadersAsync(Int32, Int32, Int32) | async/await version of DownloadMessageHeaders(Int32, Int32, Int32).
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeadersAsync Method

Pop3DownloadMessageHeadersAsync Method
async/await version of DownloadMessageHeaders.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadMessageHeadersAsync()
Public Function DownloadMessageHeadersAsync As Task(Of MailMessageCollection)

Return Value

Type: Task MailMessageCollection
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessageCollection object containing the downloaded message headers; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadMessageHeadersAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeadersAsync Method (Int32, Int32)

Pop3DownloadMessageHeadersAsync Method (Int32, Int32)
async/await version of DownloadMessageHeaders(Int32, Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadMessageHeadersAsync(
    int startIndex,
    int count
)
Public Function DownloadMessageHeadersAsync (
    startIndex As Integer,
    count As Integer
) As Task(Of MailMessageCollection)

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.

Return Value

Type: Task MailMessageCollection
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessageCollection object containing the downloaded message headers; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadMessageHeadersAsync Overload
MailBee.Pop3Mail Namespace


Pop3.DownloadMessageHeadersAsync Method (Int32, Int32, Int32)

Pop3DownloadMessageHeadersAsync Method (Int32, Int32, Int32)
async/await version of DownloadMessageHeaders(Int32, Int32, Int32).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<MailMessageCollection> DownloadMessageHeadersAsync(
    int startIndex,
    int count,
    int bodyLineCount
)
Public Function DownloadMessageHeadersAsync (
    startIndex As Integer,
    count As Integer,
    bodyLineCount As Integer
) As Task(Of MailMessageCollection)

Parameters

startIndex
Type: SystemInt32
The ordinal position (in the inbox) of the first message in the range to be downloaded.
count
Type: SystemInt32
Number of messages to be downloaded, or -1 to indicate that all messages in the range startIndex to InboxMessageCount must be downloaded.
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire messages.

Return Value

Type: Task MailMessageCollection
A task that represents the asynchronous operation. On success, the value of TResult parameter is a MailMessageCollection object containing the downloaded message headers; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
DownloadMessageHeadersAsync Overload
MailBee.Pop3Mail Namespace


Pop3.EndConnect Method

Pop3EndConnect Method
Ends the pending asynchronous connection request.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndConnect()
Public Function EndConnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginConnect(String, Int32, Boolean, AsyncCallback, Object)


Pop3.EndDeleteMessage Method

Pop3EndDeleteMessage Method
Ends the pending asynchronous request for flagging the message for deletion.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndDeleteMessage()
Public Function EndDeleteMessage As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginDeleteMessage(Int32, AsyncCallback, Object)


Pop3.EndDeleteMessages Method

Pop3EndDeleteMessages Method
Ends the pending asynchronous request for flagging the range of messages for deletion.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndDeleteMessages()
Public Function EndDeleteMessages As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginDeleteMessages(Int32, Int32, AsyncCallback, Object)


Pop3.EndDisconnect Method

Pop3EndDisconnect Method
Ends a pending asynchronous disconnection request.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndDisconnect()
Public Function EndDisconnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginDisconnect(AsyncCallback, Object)


Pop3.EndDownloadMessage Method

Pop3EndDownloadMessage Method
Ends the pending asynchronous request for downloading the message and returns the downloaded message.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage EndDownloadMessage()
Public Function EndDownloadMessage As MailMessage

Return Value

Type: MailMessage
On success, a MailMessage object representing the downloaded message; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginDownloadMessage(Int32, Int32, AsyncCallback, Object)


Pop3.EndDownloadMessages Method

Pop3EndDownloadMessages Method
Ends the pending asynchronous request for downloading the messages and returns the downloaded messages.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection EndDownloadMessages()
Public Function EndDownloadMessages As MailMessageCollection

Return Value

Type: MailMessageCollection
On success, a MailMessageCollection object representing the downloaded messages; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginDownloadMessages(Int32, Int32, Int32, AsyncCallback, Object)


Pop3.EndExecuteCustomCommand Method

Pop3EndExecuteCustomCommand Method
Ends the pending asynchronous request for sending user-defined command to the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndExecuteCustomCommand()
Public Function EndExecuteCustomCommand As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginExecuteCustomCommand(String, Boolean, AsyncCallback, Object)


Pop3.EndLogin Method

Pop3EndLogin Method
Ends the pending asynchronous login request.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndLogin()
Public Function EndLogin As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginLogin(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod, AsyncCallback, Object)


Pop3.EndStartTls Method

Pop3EndStartTls Method
Ends a pending asynchronous TLS/SSL negotiation request.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndStartTls()
Public Function EndStartTls As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3BeginStartTls(AsyncCallback, Object)


Pop3.ExecuteCustomCommand Method

Pop3ExecuteCustomCommand Method
Sends user-defined command to the server and receives the server response to this command.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ExecuteCustomCommand(
    string commandString,
    bool multiLineResponse
)
Public Function ExecuteCustomCommand (
    commandString As String,
    multiLineResponse As Boolean
) As Boolean

Parameters

commandString
Type: SystemString
User-defined command text (including line terminator).
multiLineResponse
Type: SystemBoolean
true if the given command returns multi-line response on success; false if the given command always produces single-line response.

Return Value

Type: Boolean
true if the command was executed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The developer can use GetServerResponse method to obtain the response data returned by the server.
Examples
This sample connects to the POP3 server, issues HELP command, and displays the server response to this command. If HELP command is not supported by the server, MailBee will throw MailBeePop3NegativeResponseException. It's caught in the sample code, and the proper error message is displayed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
try
{
    // Send HELP command (it produces a single-line response).
    pop.ExecuteCustomCommand("HELP\r\n", false);
    Console.WriteLine(pop.GetServerResponse());
}
catch (MailBeePop3NegativeResponseException e)
{
    // The given POP3 server does not support HELP command.
    Console.WriteLine(e.Message);
    Console.WriteLine("Server response is: " + pop.GetServerResponse());
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
Try
    ' Send HELP command (it produces a single-line response).
    pop.ExecuteCustomCommand("HELP" & vbCrLf, False)
Catch e As MailBeePop3NegativeResponseException
    ' The given POP3 server does not support HELP command.
    Console.WriteLine(e.Message)
    Console.WriteLine("Server response is: " & pop.GetServerResponse())
End Try
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.ExecuteCustomCommandAsync Method

Pop3ExecuteCustomCommandAsync Method
async/await version of ExecuteCustomCommand(String, Boolean).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ExecuteCustomCommandAsync(
    string commandString,
    bool multiLineResponse
)
Public Function ExecuteCustomCommandAsync (
    commandString As String,
    multiLineResponse As Boolean
) As Task(Of Boolean)

Parameters

commandString
Type: SystemString
User-defined command text (including line terminator).
multiLineResponse
Type: SystemBoolean
true if the given command returns multi-line response on success; false if the given command always produces single-line response.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the command was executed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetErrorDescription Method

Pop3GetErrorDescription Method
Returns a textual description of the last error.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetErrorDescription()
Public Function GetErrorDescription As String

Return Value

Type: String
A string value containing a textual description of the last error.
Remarks
Error descriptions can be localized or edited by deriving from Resources class.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetExtension Method

Pop3GetExtension Method
Returns the name or parameters of the specified POP3 capability.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetExtension(
    string name
)
Public Function GetExtension (
    name As String
) As String

Parameters

name
Type: SystemString
The name of the capability. This name is case-insensitive, e.g. pipelining and PIPELINING mean the same.

Return Value

Type: String
If the specified capability is parameterless, the return value is the name of the capability itself. If the capability has parameters, the return value is a string which contains the parameters list as returned by the server. If the server does not support CAPA command (see GetExtensions for more information) or the given capability is not supported, the return value is a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The POP3 server (if supports CAPA command) always returns the list of all capabilities at once. Thus, all subsequent calls to GetExtension(String), GetExtensions, or GetExtensionValue(String) methods will use the cached version of the capability data, and no round-trips to the server will be made.
Note Note
This method may issue a network operation if the list of supported extensions has not yet been downloaded from the POP3 server. To make sure you have the local copy of the list, call GetExtensions first (or its async version).
Examples
This sample displays whether the server supports POP3 pipelining.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
string ext = pop.GetExtension("pipelining");
if (ext == null)
{
    Console.WriteLine("The given POP3 server does not support pipelining");
}
else
{
    Console.WriteLine("Pipelining is supported");
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class)
Dim pop As New Pop3
pop.Connect("mail.domain.com")
Dim ext As String
ext = pop.GetExtension("pipelining")
If ext Is Nothing Then
    Console.WriteLine("The given POP3 server does not support pipelining")
Else
    Console.WriteLine("Pipelining is supported")
End If
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetExtensions Method

Pop3GetExtensions Method
Returns a reference to the key-value list of the server capabilities.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary GetExtensions()
Public Function GetExtensions As StringDictionary

Return Value

Type: StringDictionary
The key-value list of the server capabilities, or a null reference (Nothing in Visual Basic) if the capabilities list is not available.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
You should already be connected to the POP3 server in order to use this method. If the server does not support CAPA command, the capabilities list will not be available. In this case, you can still try to call GetSupportedAuthMethods to get at least the list of supported authentication methods (AUTH command responsible for this is more widely supported than CAPA).
Note Note
If CAPA command has already been issued (for instance, this method has already been called or MailBee downloaded this list for its own purpose (such as to determine whether pipelining is supported by the server), this method will immediately return the cached results.

In the returned StringDictionary, each key is a capability name (always lowercase). Its value is either empty string (if the capability has no parameters) or space-delimited list of the parameters.

Examples
This sample displays the list of all capabilities supported by the server.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class)
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
System.Collections.Specialized.StringDictionary caps = pop.GetExtensions();
if (caps == null)
{
    Console.WriteLine("The given POP3 server does not support CAPA command");
}
else
{
    foreach (string cap in caps.Keys)
    {
        string val = caps[cap];
        if (val != string.Empty)
        {
            // Print capability name and parameters
            Console.WriteLine(cap + " " + val);
        }
        else
        {
            // For parameterless capabilities, print capability name only
            Console.WriteLine(cap);
        }
    }
}
pop.Disconnect();

// The output (the actual content will be different for a particular mail server).
user
top
stls
last
sasl LOGIN PLAIN CRAM-MD5 DIGEST-MD5 MSN NTLM
uidl
pipelining

In the output above, only "sasl" capability has parameters.
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
Dim caps As System.Collections.Specialized.StringDictionary = pop.GetExtensions()
If caps Is Nothing Then
    Console.WriteLine("The given POP3 server does not support CAPA command")
Else
    Dim cap As String
    Dim val As String
    For Each cap In caps.Keys
        val = caps(cap)
        If val <> String.Empty Then
            ' Print capability name and parameters.
            Console.WriteLine(cap & " " & val)
        Else
            ' For parameterless capabilities, print capability name only.
            Console.WriteLine(cap)
        End If
    Next
End If
pop.Disconnect()

' The output (the actual content will be different for a particular mail server).
user
top
stls
last
sasl LOGIN PLAIN CRAM-MD5 DIGEST-MD5 MSN NTLM
uidl
pipelining

In the output above, only "sasl" capability has parameters.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetExtensionsAsync Method

Pop3GetExtensionsAsync Method
async/await version of GetExtensions.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<StringDictionary> GetExtensionsAsync()
Public Function GetExtensionsAsync As Task(Of StringDictionary)

Return Value

Type: Task StringDictionary
A task that represents the asynchronous operation. The value of TResult parameter is the key-value list of the server capabilities, or a null reference (Nothing in Visual Basic) if the capabilities list is not available.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetExtensionValue Method

Pop3GetExtensionValue Method
Returns the parameters of the specified POP3 capability, or an empty string if the capability has no parameters.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetExtensionValue(
    string name
)
Public Function GetExtensionValue (
    name As String
) As String

Parameters

name
Type: SystemString
The name of the capability. This name is case-insensitive, e.g. pipelining and PIPELINING mean the same.

Return Value

Type: String
If the specified capability is parameterless, the return value is Empty. If the capability has parameters, the return value is a string which contains the parameters list as returned by the server. If the server does not support CAPA command (see GetExtensions for more information) or the given capability is not supported, the return value is a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method can be used to retrieve additional information about the given capability. However, if you wish to get the list of SASL authentication methods supported by the server, you may also use GetSupportedAuthMethods method for this. GetSupportedAuthMethods method can succeed even if the server does not support CAPA command but supports AUTH command (which is often the case).
Note Note
This method may issue a network operation if the list of supported extensions has not yet been downloaded from the POP3 server. To make sure you have the local copy of the list, call GetExtensions first (or its async version).
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetMessageIndexFromUid Method

Pop3GetMessageIndexFromUid Method
Gets the message number of the message to which the specified Unique-ID is assigned.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetMessageIndexFromUid(
    string uid
)
Public Function GetMessageIndexFromUid (
    uid As String
) As Integer

Parameters

uid
Type: SystemString
Unique-ID string assigned to the message in the inbox.

Return Value

Type: Int32
The message number (in the range from 1 to InboxMessageCount) of the message to which the server has assigned the specified Unique-ID, or 0 if the inbox does not contain the message with the given Unique-ID.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | The uid is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Unique-ID values are case-sensitive. SomeValue and SOMEVALUE are NOT equivalent.
Note Note
This method may issue a network operation if the UID list has not yet been downloaded from the POP3 server during login (see InboxPreloadOptions). To make sure you have the local copy of the list, call GetMessageUids first (or its async version).
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3GetMessageUidFromIndex(Int32)
Pop3InboxPreloadOptions


Pop3.GetMessageSize Method

Pop3GetMessageSize Method
Gets the length (in bytes) of the specified message in the inbox.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetMessageSize(
    int index
)
Public Function GetMessageSize (
    index As Integer
) As Integer

Parameters

index
Type: SystemInt32
The ordinal position of the message in the inbox. It must be in the range from 1 to InboxMessageCount. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: Int32
The length (in bytes) of the specified message in the inbox.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | The message index is not in the range from 1 to InboxMessageCount (by absolute value).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Note Note
This method may issue a network operation if the message list has not yet been downloaded from the POP3 server during login (see InboxPreloadOptions). To make sure you have the local copy of the list, call GetMessageSizes first (or its async version).
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3GetMessageSizes
Pop3InboxPreloadOptions


Pop3.GetMessageSizes Method

Pop3GetMessageSizes Method
Gets the array of lengths (in bytes) of all messages in the inbox. The array is zero-based.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int[] GetMessageSizes()
Public Function GetMessageSizes As Integer()

Return Value

Type: Int32
A zero-based array of lengths (in bytes) of all messages in the inbox, or a null reference (Nothing in Visual Basic) in case of an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Since the lower index in a .NET array is 0 while the lower message number in the inbox is 1, indices in the lengths array are -1 to the message numbers.
Examples
This sample displays the size in bytes of the first and the last message in the inbox.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");

int[] lengths = pop.GetMessageSizes();
Console.WriteLine("Message #1 is the size of " + lengths[0] + " bytes");
Console.WriteLine("Message #" + pop.InboxMessageCount +
    " is the size of " + lengths[pop.InboxMessageCount - 1] + " bytes");

pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")

Dim lengths As Integer() = pop.GetMessageSizes()
Console.WriteLine("Message #1 is the size of " & lengths(0) & " bytes")
Console.WriteLine("Message #" & pop.InboxMessageCount & _
    " is the size of " & lengths(pop.InboxMessageCount - 1) & " bytes")

pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3GetMessageSize(Int32)
Pop3InboxPreloadOptions


Pop3.GetMessageSizesAsync Method

Pop3GetMessageSizesAsync Method
async/await version of GetMessageSizes.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<int[]> GetMessageSizesAsync()
Public Function GetMessageSizesAsync As Task(Of Integer())

Return Value

Type: Task Int32
A task that represents the asynchronous operation. The value of TResult parameter is a zero-based array of lengths (in bytes) of all messages in the inbox or a null reference (Nothing in Visual Basic) in case of an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetMessageUidFromIndex Method

Pop3GetMessageUidFromIndex Method
Gets the Unique-ID string assigned to the specified message in the inbox on the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetMessageUidFromIndex(
    int index
)
Public Function GetMessageUidFromIndex (
    index As Integer
) As String

Parameters

index
Type: SystemInt32
The message number (in the range from 1 to InboxMessageCount) of the message. Can be negative in the range from -1 to -InboxMessageCount, i.e. -1 denotes the last e-mail in the inbox.

Return Value

Type: String
The Unique-ID string assigned to the specified message in the inbox on the server.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | The message index is not in the range from 1 to InboxMessageCount (by absolute value).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Unique-ID is not the same value as MessageID. Unique-ID is assigned to each message in the inbox by the POP3 server, while MessageID value is assigned to the message by the mail composing program. For instance, if the same message was placed into the inbox twice, both copies will have the same MessageID value, but Unique-ID values will be different.

Unique-ID's is the preferred way of implementation of downloading new mails mechanism.

Note Note
This method may issue a network operation if the UID list has not yet been downloaded from the POP3 server during login (see InboxPreloadOptions). To make sure you have the local copy of the list, call GetMessageUids first (or its async version).
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3GetMessageIndexFromUid(String)
Pop3InboxPreloadOptions


Pop3.GetMessageUids Method

Pop3GetMessageUids Method
Gets the array of Unique-ID's of all messages in the inbox. The array is zero-based.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GetMessageUids()
Public Function GetMessageUids As String()

Return Value

Type: String
A zero-based array of Unique-ID strings of all messages in the inbox or a null reference (Nothing in Visual Basic) in case of an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Since the lower index in a .NET array is 0 while the lower message number in the inbox is 1, indices in the Unique-ID's array are -1 to the message numbers.
Examples
This sample displays Unique-ID values of the first and the last message in the inbox.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");

string[] uids = pop.GetMessageUids();
Console.WriteLine("Unique-ID of message #1 is " + uids[0]);
Console.WriteLine("Unique-ID of message #" + pop.InboxMessageCount +
    " is " + uids[pop.InboxMessageCount - 1]);

pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")

Dim uids As String() = pop.GetMessageUids()
Console.WriteLine("Unique-ID of message #1 is " & uids(0))
Console.WriteLine("Unique-ID of message #" & pop.InboxMessageCount & _
    " is " & uids(pop.InboxMessageCount - 1))

pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3GetMessageUidFromIndex(Int32)
Pop3InboxPreloadOptions


Pop3.GetMessageUidsAsync Method

Pop3GetMessageUidsAsync Method
async/await version of GetMessageUids.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string[]> GetMessageUidsAsync()
Public Function GetMessageUidsAsync As Task(Of String())

Return Value

Type: Task String
A task that represents the asynchronous operation. The value of TResult parameter is a zero-based array of Unique-ID strings of all messages in the inbox or a null reference (Nothing in Visual Basic) in case of an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetServerResponse Method

Pop3GetServerResponse Method
Returns the last response from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetServerResponse()
Public Function GetServerResponse As String

Return Value

Type: String
A string value which contains the last response from the server, or a null reference (Nothing in Visual Basic) if not connected to the server or if the previous response was considered large (a downloaded e-mail) and it was removed from memory during to avoid wasting resources.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetSocket Method

Pop3GetSocket Method
Returns the underlying Socket MailBee uses for the current network connection.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Socket GetSocket()
Public Function GetSocket As Socket

Return Value

Type: Socket
A reference to the underlying Socket MailBee uses for the current network connection, or a null reference if there is no active connection.
Remarks
In case of UWP edition, this method returns StreamSocket instead.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetSocketError Method

Pop3GetSocketError Method
Returns a Win32 error code of the last socket-related error.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetSocketError()
Public Function GetSocketError As Integer

Return Value

Type: Int32
An integer value containing the last socket-related error code, or 0 if there is no error.
Remarks
This error code is obtained from NativeErrorCode.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetStream Method

Pop3GetStream Method
Returns the underlying Stream MailBee uses for the current network connection.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Stream GetStream()
Public Function GetStream As Stream

Return Value

Type: Stream
A reference to the underlying Stream MailBee uses for the current network connection, or a null reference (Nothing in Visual Basic) if there is no active connection.
Remarks
Typically this will be an instance of a class inherited from NetworkStream or SslStream.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.GetSupportedAuthMethods Method

Pop3GetSupportedAuthMethods Method
Returns a set of flags indicating which authentication methods are supported by the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods GetSupportedAuthMethods()
Public Function GetSupportedAuthMethods As AuthenticationMethods

Return Value

Type: AuthenticationMethods
A set of flags indicating which authentication methods are supported by the server.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method performs round-trip to the server only if the list of authentication methods has not already been downloaded. Since this list is a part of the server capabilities, it will already be available in the local cache if the server capabilities have already been downloaded during this connection (for instance, due to GetExtensions method call). If the list of supported authentication methods is already available in the local cache, this method will immediately return the cached results.
Note Note
If the POP3 server does not support CAPA command and the client already logged in the mailbox, it's not possible to get the list of supported authentication methods (unless it has already been downloaded prior to logging in). This is because AUTH command (which returns the list of authentication methods available) cannot be issued once the client has logged in.
Examples
This sample indicates whether APOP authentication is supported by the server.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
AuthenticationMethods authMethods = pop.GetSupportedAuthMethods();

if ((authMethods & AuthenticationMethods.Apop) > 0)
{
    Console.WriteLine("APOP secure authentication is supported");
}
else
{
    Console.WriteLine("The POP3 server does not support APOP");
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
Dim authMethods As AuthenticationMethods = pop.GetSupportedAuthMethods()

If ((authMethods And AuthenticationMethods.Apop) > 0) Then
    Console.WriteLine("APOP secure authentication is supported")
Else
    Console.WriteLine("The POP3 server does not support APOP")
End If
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3GetExtensions


Pop3.GetSupportedAuthMethodsAsync Method

Pop3GetSupportedAuthMethodsAsync Method
async/await version of GetSupportedAuthMethods.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<AuthenticationMethods> GetSupportedAuthMethodsAsync()
Public Function GetSupportedAuthMethodsAsync As Task(Of AuthenticationMethods)

Return Value

Type: Task AuthenticationMethods
A task that represents the asynchronous operation. The value of TResult parameter is a set of flags indicating which authentication methods are supported by the server.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Last Method

Pop3Last Method
Gets the message number of the last message ever accessed in this mailbox during actual or all prior POP3 sessions.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Last()
Public Function Last As Integer

Return Value

Type: Int32
On success, the message number of the last message ever accessed, or 0 if no messages have ever been accessed in the mailbox; on failure, -1.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Although LAST command was originally intended for locating new messages, it was deprecated in subsequent revisions of the POP3 protocol due. Use of this command is not recommended.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.LastAsync Method

Pop3LastAsync Method
async/await version of Last.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<int> LastAsync()
Public Function LastAsync As Task(Of Integer)

Return Value

Type: Task Int32
A task that represents the asynchronous operation. The value of TResult parameter is the message number of the last message ever accessed, or 0 if no messages have ever been accessed in the mailbox; on failure, -1�
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Login Method

Pop3Login Method
Overload List
Name | Description
Login(String, String) | Logs in a mailbox on the POP3 server.
Login(String, String, AuthenticationMethods) | Logs in a mailbox on the POP3 server.
Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mailbox on the POP3 server.
Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | Logs in a mailbox on the POP3 server.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Login Method (String, String)

Pop3Login Method (String, String)
Logs in a mailbox on the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string accountName,
    string password
)
Public Function Login (
    accountName As String,
    password As String
) As Boolean

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method will try to authenticate using the best (the most secure) authentication method supported by the server, but will downgrade to less secure methods (to the simplest USER/PASS authentication in the worst case) if better methods are not available.

You can also force using a particular authentication method with Login(String, String, AuthenticationMethods) overload passing a method like Regular.

Note Note
If SafeMode is true, MailBee will use the simplest USER/PASS authentication by default (Regular option). This can often help to troubleshoot login problems (many mail servers implement secure authentication methods incorrectly).
Examples
This sample connects to a POP3 server, logs in a user account, and displays the total number of messages in an inbox.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
Console.WriteLine(pop.InboxMessageCount + " message(s) in inbox");
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
Console.WriteLine(pop.InboxMessageCount & " message(s) in inbox")
pop.Disconnect()
See Also

Reference

Pop3 Class
Login Overload
MailBee.Pop3Mail Namespace


Pop3.Login Method (String, String, AuthenticationMethods)

Pop3Login Method (String, String, AuthenticationMethods)
Logs in a mailbox on the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string accountName,
    string password,
    AuthenticationMethods authMethods
)
Public Function Login (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods
) As Boolean

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
Authentication methods are tried from more secure to less secure. If authMethods is set to Auto, MailBee will try to use the most secure method supported by the server but will downgrade to less secure methods (to the simplest USER/PASS authentication in the worst case) if better methods are not available.
Examples
This sample connects to a POP3 server and logs in a user account using secure authentication methods only. Use of insecure methods is not allowed.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret",
    AuthenticationMethods.Apop | AuthenticationMethods.SaslCramMD5 | AuthenticationMethods.SaslNtlm);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret", _
    AuthenticationMethods.Apop Or AuthenticationMethods.SaslCramMD5 Or AuthenticationMethods.SaslNtlm)
pop.Disconnect()
See Also

Reference

Pop3 Class
Login Overload
MailBee.Pop3Mail Namespace


Pop3.Login Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

Pop3Login Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
Logs in a mailbox on the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function Login (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Boolean

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

By default, MailBee won't even try to use authentication methods which are not listed by the server in its capabilities. This behavior can be changed by setting TryUnsupportedMethods bit in authOptions. If, during the authentication attempt, the server reports that the method is unsupported, MailBee will try the next method in authMethods until the compatible method is found or no more methods left. This behavior can be changed by setting UseSingleMethodOnly bit in authOptions.

Authentication methods are tried from more secure to less secure. If authMethods is set to Auto and authOptions is None, MailBee will try to use the most secure method supported by the server but will downgrade to less secure methods (to the simplest USER/PASS authentication in the worst case) if better methods are not available.

Examples
This sample connects to a POP3 server and attempts to log in a user account using SASL NTLM method in Integrated Windows Authentication mode (passing credentials of the currently logged Windows user) even if NTLM is not listed in the server capabilities (the server may still support NTLM while not advertizing this). Use of other authentication methods is not allowed by this sample (they do not support obtaining the current Windows user's credentials and thus will raise exception is empty credentials are supplied by the caller).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login(null, null, AuthenticationMethods.SaslNtlm,
    AuthenticationOptions.TryUnsupportedMethods, null);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login(Nothing, Nothing, AuthenticationMethods.SaslNtlm, _
    AuthenticationOptions.TryUnsupportedMethods, Nothing)
pop.Disconnect()
See Also

Reference

Pop3 Class
Login Overload
MailBee.Pop3Mail Namespace
MailBeeSaslMethod


Pop3.Login Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

Pop3Login Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
Logs in a mailbox on the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login(
    string targetName,
    string domain,
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function Login (
    targetName As String,
    domain As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Boolean

Parameters

targetName
Type: SystemString
The Service Principal Name (SPN) of the POP3 server. Only used with GSSAPI authentication method. If an empty string, NTLM method will be used for GSSAPI. If a null reference (Nothing in Visual Basic), MailBee will autodetect SPN as "POP3/serverName" and use Kerberos for GSSAPI. If set to a non-empty string, MailBee will also select Kerberos for GSSAPI and use this value as SPN.
domain
Type: SystemString
The user account domain on the server. Only used with NTLM and GSSAPI authentication methods. You can leave it a null reference to use the current domain.
accountName
Type: SystemString
The user account name on the server (can be empty for NTLM and GSSAPI).
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Boolean
true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

By default, MailBee won't even try to use authentication methods which are not listed by the server in its capabilities. This behavior can be changed by setting TryUnsupportedMethods bit in authOptions. If, during the authentication attempt, the server reports that the method is unsupported, MailBee will try the next method in authMethods until the compatible method is found or no more methods left. This behavior can be changed by setting UseSingleMethodOnly bit in authOptions.

Authentication methods are tried from more secure to less secure. If authMethods is set to Auto and authOptions is None, MailBee will try to use the most secure method supported by the server but will downgrade to less secure methods (to the simplest USER/PASS authentication in the worst case) if better methods are not available.

Examples
This sample connects to a POP3 server and attempts to log in a user account using SASL GSSAPI method in Integrated Windows Authentication mode and NTLM is selected as the underlying implementation because targetName is an empty string.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
pop.Login("", null, null, null, AuthenticationMethods.SaslGssApi,
    AuthenticationOptions.TryUnsupportedMethods, null);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
pop.Login("", Nothing, Nothing, Nothing, AuthenticationMethods.SaslGssApi, _
    AuthenticationOptions.TryUnsupportedMethods, Nothing)
pop.Disconnect()
See Also

Reference

Pop3 Class
Login Overload
MailBee.Pop3Mail Namespace
MailBeeSaslMethod


Pop3.LoginAsync Method

Pop3LoginAsync Method
Overload List
 | Name | Description
Public method | LoginAsync(String, String) | async/await version of Login(String, String).
Public method | LoginAsync(String, String, AuthenticationMethods) | async/await version of Login(String, String, AuthenticationMethods).
Public method | LoginAsync(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Public method | LoginAsync(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) | async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.LoginAsync Method (String, String)

Pop3LoginAsync Method (String, String)
async/await version of Login(String, String).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string accountName,
    string password
)
Public Function LoginAsync (
    accountName As String,
    password As String
) As Task(Of Boolean)

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
LoginAsync Overload
MailBee.Pop3Mail Namespace


Pop3.LoginAsync Method (String, String, AuthenticationMethods)

Pop3LoginAsync Method (String, String, AuthenticationMethods)
async/await version of Login(String, String, AuthenticationMethods).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string accountName,
    string password,
    AuthenticationMethods authMethods
)
Public Function LoginAsync (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods
) As Task(Of Boolean)

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox. or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
LoginAsync Overload
MailBee.Pop3Mail Namespace


Pop3.LoginAsync Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

Pop3LoginAsync Method (String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
async/await version of Login(String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function LoginAsync (
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Task(Of Boolean)

Parameters

accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
LoginAsync Overload
MailBee.Pop3Mail Namespace


Pop3.LoginAsync Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)

Pop3LoginAsync Method (String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)
async/await version of Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync(
    string targetName,
    string domain,
    string accountName,
    string password,
    AuthenticationMethods authMethods,
    AuthenticationOptions authOptions,
    SaslMethod authUserDefined
)
Public Function LoginAsync (
    targetName As String,
    domain As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods,
    authOptions As AuthenticationOptions,
    authUserDefined As SaslMethod
) As Task(Of Boolean)

Parameters

targetName
Type: SystemString
The Service Principal Name (SPN) of the POP3 server. Only used with GSSAPI authentication method. If an empty string, NTLM method will be used for GSSAPI. If a null reference (Nothing in Visual Basic), MailBee will autodetect SPN as "POP3/serverName" and use Kerberos for GSSAPI. If set to a non-empty string, MailBee will also select Kerberos for GSSAPI and use this value as SPN.
domain
Type: SystemString
The user account domain on the server. Only used with NTLM and GSSAPI authentication methods. You can leave it a null reference to use the current domain.
accountName
Type: SystemString
The user account name on the server (can be empty for NTLM and GSSAPI).
password
Type: SystemString
The password of the user account on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when logging in a mailbox.
authOptions
Type: MailBeeAuthenticationOptions
Specifies the options which affect login process.
authUserDefined
Type: MailBeeSaslMethod
A reference to the instance of user defined authentication method, or a null reference (Nothing in Visual Basic) if user defined authentication is not used.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if a login attempt succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
LoginAsync Overload
MailBee.Pop3Mail Namespace


Pop3.Noop Method

Pop3Noop Method
Sends a NOOP command to the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Noop()
Public Function Noop As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method is useful for keeping the connection alive when there is no real activity. However, some POP3 servers may ignore this command and still close the connection. If this is the case, you may use Noop2 method instead.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Noop2 Method

Pop3Noop2 Method
Sends a command to the POP3 server to keep the connection alive.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Noop2()
Public Function Noop2 As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The developer can use this method to keep the POP3 server from timing out the connection when there is no real activity. This method actually sends STAT command to the server. This seems to be more reliable solution than the standard NOOP command which is ignored by some POP3 servers.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Noop


Pop3.Noop2Async Method

Pop3Noop2Async Method
async/await version of Noop2.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> Noop2Async()
Public Function Noop2Async As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.NoopAsync Method

Pop3NoopAsync Method
async/await version of Noop.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> NoopAsync()
Public Function NoopAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.OnConnected Method

Pop3OnConnected Method
Used by MailBee to raise Connected event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnConnected(
    ConnectedEventArgs args
)
Protected Sub OnConnected (
    args As ConnectedEventArgs
)

Parameters

args
Type: MailBeeConnectedEventArgs
The object containing event data.
Remarks

When RaiseEventsViaMessageLoop is true (i.e. default value), MailBee uses this method to raise Connected event. In WinForms application, the event will be raised on the message loop thread. In other applications (such as web or console applications), threading is not a concern, and the current thread MailBee is running on will be used.

You can override this method in a derived class to force MailBee execute your own code instead of raising Connected event. This may help to avoid threading issues in WinForms applications (because events may not be raised if the message loop thread is blocked for some reason, while calling overridden methods does not depend on the message loop thread state).

Another solution of this problem is setting RaiseEventsViaMessageLoop to false and using Wait method to block the message loop thread if needed. This way, you do not need to derive any descendant class from Pop3 class.

See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Connected
Pop3RaiseEventsViaMessageLoop


Pop3.OnDataReceived Method

Pop3OnDataReceived Method
Used by MailBee to raise DataReceived event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DataReceived
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnDataSent Method

Pop3OnDataSent Method
Used by MailBee to raise DataSent event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataSent(
    DataTransferEventArgs args
)
Protected Sub OnDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DataSent
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnDisconnected Method

Pop3OnDisconnected Method
Used by MailBee to raise Disconnected event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDisconnected(
    DisconnectedEventArgs args
)
Protected Sub OnDisconnected (
    args As DisconnectedEventArgs
)

Parameters

args
Type: MailBeeDisconnectedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Disconnected
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnErrorOccurred Method

Pop3OnErrorOccurred Method
Used by MailBee to raise ErrorOccurred event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnErrorOccurred(
    ErrorEventArgs args
)
Protected Sub OnErrorOccurred (
    args As ErrorEventArgs
)

Parameters

args
Type: MailBeeErrorEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3ErrorOccurred
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnHostResolved Method

Pop3OnHostResolved Method
Used by MailBee to raise HostResolved event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnHostResolved(
    HostResolvedEventArgs args
)
Protected Sub OnHostResolved (
    args As HostResolvedEventArgs
)

Parameters

args
Type: MailBeeHostResolvedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3HostResolved
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnLoggedIn Method

Pop3OnLoggedIn Method
Used by MailBee to raise LoggedIn event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLoggedIn(
    LoggedInEventArgs args
)
Protected Sub OnLoggedIn (
    args As LoggedInEventArgs
)

Parameters

args
Type: MailBeeLoggedInEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3LoggedIn
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnLogNewEntry Method

Pop3OnLogNewEntry Method
Used by MailBee to raise LogNewEntry event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLogNewEntry(
    LogNewEntryEventArgs args
)
Protected Sub OnLogNewEntry (
    args As LogNewEntryEventArgs
)

Parameters

args
Type: MailBeeLogNewEntryEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3LogNewEntry
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnLowLevelDataReceived Method

Pop3OnLowLevelDataReceived Method
Used by MailBee to raise LowLevelDataReceived event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLowLevelDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnLowLevelDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3LowLevelDataReceived
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnLowLevelDataSent Method

Pop3OnLowLevelDataSent Method
Used by MailBee to raise LowLevelDataSent event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLowLevelDataSent(
    DataTransferEventArgs args
)
Protected Sub OnLowLevelDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3LowLevelDataSent
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnMessageDataChunkReceived Method

Pop3OnMessageDataChunkReceived Method
Used by MailBee to raise MessageDataChunkReceived event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageDataChunkReceived(
    Pop3MessageDataChunkReceivedEventArgs args
)
Protected Sub OnMessageDataChunkReceived (
    args As Pop3MessageDataChunkReceivedEventArgs
)

Parameters

args
Type: MailBee.Pop3MailPop3MessageDataChunkReceivedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3MessageDataChunkReceived
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnMessageDownloaded Method

Pop3OnMessageDownloaded Method
Used by MailBee to raise MessageDownloaded event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageDownloaded(
    Pop3MessageDownloadedEventArgs args
)
Protected Sub OnMessageDownloaded (
    args As Pop3MessageDownloadedEventArgs
)

Parameters

args
Type: MailBee.Pop3MailPop3MessageDownloadedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3MessageDownloaded
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnSocketConnected Method

Pop3OnSocketConnected Method
Used by MailBee to raise SocketConnected event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSocketConnected(
    SocketConnectedEventArgs args
)
Protected Sub OnSocketConnected (
    args As SocketConnectedEventArgs
)

Parameters

args
Type: MailBeeSocketConnectedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SocketConnected
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnSocketCreating Method

Pop3OnSocketCreating Method
Used by MailBee to raise SocketCreating event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSocketCreating(
    SocketCreatingEventArgs args
)
Protected Sub OnSocketCreating (
    args As SocketCreatingEventArgs
)

Parameters

args
Type: MailBeeSocketCreatingEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SocketCreating
Pop3OnConnected(ConnectedEventArgs)


Pop3.OnTlsStarted Method

Pop3OnTlsStarted Method
Used by MailBee to raise TlsStarted event.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnTlsStarted(
    TlsStartedEventArgs args
)
Protected Sub OnTlsStarted (
    args As TlsStartedEventArgs
)

Parameters

args
Type: MailBeeTlsStartedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3TlsStarted
Pop3OnConnected(ConnectedEventArgs)


Pop3.QuickDownloadMessage Method

Pop3QuickDownloadMessage Method
Overload List
Name | Description
QuickDownloadMessage(String, String, String, Int32) | Completely downloads the specified message from the server, in a single line of code.
QuickDownloadMessage(String, String, String, Int32, Int32) | Downloads the specified message (entire message or message header only) from the server, in a single line of code.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.QuickDownloadMessage Method (String, String, String, Int32)

Pop3QuickDownloadMessage Method (String, String, String, Int32)
Completely downloads the specified message from the server, in a single line of code.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessage QuickDownloadMessage(
    string serverName,
    string accountName,
    string password,
    int index
)
Public Shared Function QuickDownloadMessage (
    serverName As String,
    accountName As String,
    password As String,
    index As Integer
) As MailMessage

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
index
Type: SystemInt32
The ordinal position of the message in the inbox, starting at 1 (can be negative, i.e. -1 denotes the last e-mail in the inbox).

Return Value

Type: MailMessage
A MailMessage object containing the downloaded message (including the header and all the body parts and attachments).
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the inbox.

The common use of this method is to quickly receive the message when its index in the inbox is already known. For instance, QuickDownloadMessages(String, String, String, Int32) method was used to download headers for all messages in the inbox and build the message list where the user can click a particular message to view it completely. Once the user selected the message to be viewed, the application passes its index in the message list as a value of index parameter of QuickDownloadMessage(String, String, String, Int32, Int32) method to download the selected message (if the message list index is zero-based, the developer should also add 1 to the index value).

Note Note
Static methods still require the valid license key be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEntireMessageAsync(Int32).

Examples
This sample downloads the first message in the inbox and saves it as .EML file to disk.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = Pop3.QuickDownloadMessage("pop.server.com",
    "login", "password", 1);
msg.SaveMessage(@"C:\Temp\message.eml");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop.server.com", _
    "login", "password", 1)
msg.SaveMessage("C:\Temp\message.eml")
See Also

Reference

Pop3 Class
QuickDownloadMessage Overload
MailBee.Pop3Mail Namespace
Pop3QuickDownloadMessages(String, String, String, Int32)


Pop3.QuickDownloadMessage Method (String, String, String, Int32, Int32)

Pop3QuickDownloadMessage Method (String, String, String, Int32, Int32)
Downloads the specified message (entire message or message header only) from the server, in a single line of code.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessage QuickDownloadMessage(
    string serverName,
    string accountName,
    string password,
    int index,
    int bodyLineCount
)
Public Shared Function QuickDownloadMessage (
    serverName As String,
    accountName As String,
    password As String,
    index As Integer,
    bodyLineCount As Integer
) As MailMessage

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
index
Type: SystemInt32
The ordinal position of the message in the inbox, starting at 1 (can be negative, i.e. -1 denotes the last e-mail in the inbox).
bodyLineCount
Type: SystemInt32
Number of lines of the message source body to download in addition to the message source header, or -1 to download the entire message, or 0 to download the message header only.

Return Value

Type: MailMessage
A MailMessage object containing the downloaded message.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the inbox.

The common use of this method is to quickly receive the message or its part when its index in the inbox is already known. For instance, QuickDownloadMessages(String, String, String, Int32) method was used to download headers for all messages in the inbox and build the message list where the user can click a particular message to view it in more detail. Once the user selected the message to be viewed, the application passes its index in the message list as a value of index parameter of QuickDownloadMessage(String, String, String, Int32, Int32) method to download the selected message or its part (if the message list index is zero-based, the developer should also add 1 to the index value).

Note Note
Static methods still require the valid license key to be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEntireMessagesAsync(Int32, Int32).

Examples

This sample partially downloads the first message in the inbox (the header and the first 100 lines of the message source body are downloaded), and displays preview of the plain-text body of the message. This may be useful if the entire message is very large, and the user wants to take a look at the beginning of the body text in order to decide whether to download the entire message.

If the message has HTML part but does not have plain-text part, the plain-text version will be generated automatically.

C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessage msg = Pop3.QuickDownloadMessage("pop.server.com",
    "login", "password", 1, 100);
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;
Console.WriteLine(msg.BodyPlainText);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msg As MailMessage = Pop3.QuickDownloadMessage("pop.server.com", _
    "login", "password", 1, 100)
msg.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain
Console.WriteLine(msg.BodyPlainText)
See Also

Reference

Pop3 Class
QuickDownloadMessage Overload
MailBee.Pop3Mail Namespace
Pop3QuickDownloadMessages(String, String, String, Int32)


Pop3.QuickDownloadMessages Method

Pop3QuickDownloadMessages Method
Overload List
Name | Description
QuickDownloadMessages(String, String, String) | Completely downloads all the messages in the inbox on the server, in a single line of code.
QuickDownloadMessages(String, String, String, Int32) | Downloads all the messages (entire messages or message headers only) in the inbox on the server, in a single line of code.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.QuickDownloadMessages Method (String, String, String)

Pop3QuickDownloadMessages Method (String, String, String)
Completely downloads all the messages in the inbox on the server, in a single line of code.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessageCollection QuickDownloadMessages(
    string serverName,
    string accountName,
    string password
)
Public Shared Function QuickDownloadMessages (
    serverName As String,
    accountName As String,
    password As String
) As MailMessageCollection

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.

Return Value

Type: MailMessageCollection
A MailMessageCollection object containing the downloaded messages.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the inbox.

If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.

Note Note
Static methods still require the valid license key be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadEntireMessagesAsync.

Examples
This sample downloads all the messages in the inbox, and displays the index (an ordinal position in the inbox) and the attachments count of each message which has any attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessageCollection msgs = Pop3.QuickDownloadMessages("pop.server.com",
    "login", "password");
foreach (MailMessage msg in msgs)
{
    if (msg.HasAttachments)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer +
            " has " + msg.Attachments.Count + " attachment(s)");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msgs As MailMessageCollection = Pop3.QuickDownloadMessages("pop.server.com", _
    "login", "password")
For Each msg As MailMessage In msgs
    If msg.HasAttachments Then
        Console.WriteLine("Message #" & msg.IndexOnServer & _
            " has " & msg.Attachments.Count & " attachment(s)")
    End If
Next
See Also

Reference

Pop3 Class
QuickDownloadMessages Overload
MailBee.Pop3Mail Namespace
Pop3QuickDownloadMessage(String, String, String, Int32, Int32)


Pop3.QuickDownloadMessages Method (String, String, String, Int32)

Pop3QuickDownloadMessages Method (String, String, String, Int32)
Downloads all the messages (entire messages or message headers only) in the inbox on the server, in a single line of code.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static MailMessageCollection QuickDownloadMessages(
    string serverName,
    string accountName,
    string password,
    int bodyLineCount
)
Public Shared Function QuickDownloadMessages (
    serverName As String,
    accountName As String,
    password As String,
    bodyLineCount As Integer
) As MailMessageCollection

Parameters

serverName
Type: SystemString
The name or IP address of the POP3 server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The password of the user account on the server.
bodyLineCount
Type: SystemInt32
Number of lines of a message source body to download in addition to a message source header, or -1 to download entire messages, or 0 to download message headers only.

Return Value

Type: MailMessageCollection
A MailMessageCollection object containing the downloaded messages.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method does not delete any messages in the inbox.

If the POP3 server supports pipelining, this method will download all the messages in a single network operation, which greatly increases performance and reduces network traffic.

Note Note
Static methods still require the valid license key be assigned to MailBee.Global.LicenseKey property (by either setting in in the code or in the config file such as app.config). All samples in MailBee documentation assume the license key is already set in the config file.

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like DownloadMessageHeadersAsync(Int32, Int32, Int32).

Examples
This sample downloads headers of all the messages in the inbox, and displays indices (ordinal positions in the inbox) of all messages which likely have any attachments.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
MailMessageCollection msgs = Pop3.QuickDownloadMessages("pop.server.com",
    "login", "password", 0);
foreach (MailMessage msg in msgs)
{
    if (msg.HasAttachments)
    {
        Console.WriteLine("Message #" + msg.IndexOnServer +
            " seems to have any attachments");
    }
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim msgs As MailMessageCollection = Pop3.QuickDownloadMessages("pop.server.com", _
    "login", "password", 0)
For Each msg As MailMessage In msgs
    If msg.HasAttachments Then
        Console.WriteLine("Message #" & msg.IndexOnServer & _
            " seems to have any attachments")
    End If
Next
See Also

Reference

Pop3 Class
QuickDownloadMessages Overload
MailBee.Pop3Mail Namespace
Pop3QuickDownloadMessage(String, String, String, Int32, Int32)


Pop3.ResetDeletes Method

Pop3ResetDeletes Method
Resets the POP3 session, and cancels the deleted status for all messages flagged for deletion in the inbox.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ResetDeletes()
Public Function ResetDeletes As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The developer can use this method to cancel purging messages which were flagged for deletion during the current POP3 session. Normally, messages flagged for deletion are purged (permanently deleted) when Disconnect method is called and the POP3 session is closed.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DeleteMessage(Int32)
Pop3Disconnect


Pop3.ResetDeletesAsync Method

Pop3ResetDeletesAsync Method
async/await version of ResetDeletes.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ResetDeletesAsync()
Public Function ResetDeletesAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.ResetState Method

Pop3ResetState Method
Resets the internal state of the component.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ResetState()
Public Sub ResetState
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method will close the connection if it's open, and will remove IsAborted status if Abort method was previously called. Typically, the developer may use this method to reuse the component after it went into aborted state due to Abort method call.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.StartTls Method

Pop3StartTls Method
Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool StartTls()
Public Function StartTls As Boolean

Return Value

Type: Boolean
true if TLS/SSL negotiation succeeded and the connection is now secured with TLS/SSL layer; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method lets the developer to switch the existing, already opened connection (usually, on port 110), to SSL/TLS mode. If the connection has been opened on a dedicated SSL port from the start (usually, port 995), the developer doesn't need to call this method.

As alternative to calling StartTls method, the developer can ask MailBee to start TLS/SSL negotiation automatically by setting SslMode property value to OnConnect or UseStartTls.

AutodetectPortAndSslMode property may cause MailBee to automatically enable TLS/SSL for some well-known hosts or ports even if SslMode property of the current connection has its default value. Be sure to always check IsSslConnection value prior to calling StartTls.

Note Note
Not all mail servers support STARTTLS functionality.
Examples
This sample attempts to establish TLS/SSL connection with the POP3 server and displays the number of messages in the inbox on success.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Connect("mail.domain.com");
if (!pop.IsSslConnection)
{
    pop.StartTls();
}
pop.Login("jdoe", "secret");
Console.WriteLine(pop.InboxMessageCount);
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Connect("mail.domain.com")
If Not pop.IsSslConnection Then
    pop.StartTls()
End If
pop.Login("jdoe", "secret")
Console.WriteLine(pop.InboxMessageCount)
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SslMode
Pop3SslProtocol
Pop3BeginStartTls(AsyncCallback, Object)


Pop3.StartTlsAsync Method

Pop3StartTlsAsync Method
async/await version of StartTls.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> StartTlsAsync()
Public Function StartTlsAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if TLS/SSL negotiation succeeded and the connection is now secured with TLS/SSL layer; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Wait Method

Pop3Wait Method
Overload List
 | Name | Description
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Wait Method

Pop3Wait Method

Note: This API is now obsolete.

Waits until the currently running (if any) asynchronous method is finished.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+.")]
public void Wait()
<ObsoleteAttribute("This method is obsolete in .NET 4.5+.")>
Public Sub Wait
Exceptions
Exception | Condition
MailBeeInvalidStateException | RaiseEventsViaMessageLoop is true
Remarks
Note Note
.NET 4.5+ apps should use XXXAsync methods which can be awaited. The current method is suitable for BeginXXX/EndXXX methods only which are now deprecated.
This method should only be used in WinForms applications in the scenarios when the application message loop is blocked and events raised by asynchronous methods get no chance to be processed.
Caution note Caution
RaiseEventsViaMessageLoop property must be set to false prior to using this method. This is required in order to switch event marshalling mechanism from sending events to the application message loop to the internal thread-independent event processor.

Usually, when the developer uses asynchronous methods which might raise events, it's not possible to use methods like WaitOne(Int32, Boolean), since they would block the message loop and thus prevent events (which are raised on the message loop thread) from getting processed. Wait method provides an alternative approach which addresses the problem.

Another alternative (in WinForms application) to using Wait method is to never block the application message loop. See BeginExecuteCustomCommand(String, Boolean, AsyncCallback, Object) method for the code example.

Note Note
In many cases, it's easier not to use events at all but derive a new class from Pop3 class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Pop3 Class
Wait Overload
MailBee.Pop3Mail Namespace


Pop3.Wait Method (Int32)

Pop3Wait Method (Int32)

Note: This API is now obsolete.

Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+.")]
public bool Wait(
    int timeoutInterval
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+.")>
Public Function Wait (
    timeoutInterval As Integer
) As Boolean

Parameters

timeoutInterval
Type: SystemInt32
The amount of time (in milliseconds) the method will wait completion of the currently running asynchronous method before returning false.

Return Value

Type: Boolean
true if the asynchronous method has finished execution during the specified amount of time, false if it's still running.
Exceptions
Exception | Condition
MailBeeInvalidStateException | RaiseEventsViaMessageLoop is true
Remarks
Note Note
.NET 4.5+ apps should use XXXAsync methods which can be awaited. The current method is suitable for BeginXXX/EndXXX methods only which are now deprecated.
This method should only be used in WinForms applications in the scenarios when the application message loop is blocked and events raised by asynchronous methods get no chance to be processed.
Caution note Caution
RaiseEventsViaMessageLoop property must be set to false prior to using this method. This is required in order to switch event marshalling mechanism from sending events to the application message loop to the internal thread-independent event processor.
Usually, when the developer wants to use asynchronous methods which might raise events in a WinForm application, it's not possible to use methods like WaitOne(Int32, Boolean), since they would block the message loop and thus prevent events (which are raised on the message loop thread) from getting processed. Wait method provides an alternative approach which addresses the problem.
Note Note
The developer can also use this method with timeoutInterval set to 0 in order to process currently pending MailBee events. This is useful if some lengthy work is performed on the message loop thread, and the developer wants to periodically let MailBee events get processed and then continue the lengthy work without waiting for the completion of the asynchronous method. See BeginConnect(String, Int32, Boolean, AsyncCallback, Object) method for examples.
Another alternative (in WinForms application) to using Wait method is to never block the application message loop. See BeginExecuteCustomCommand(String, Boolean, AsyncCallback, Object) method for the code example.
Note Note
In many cases, it's easier not to use events at all but derive a new class from Pop3 class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Pop3 Class
Wait Overload
MailBee.Pop3Mail Namespace


Pop3 Properties

Pop3 Properties

The Pop3 type exposes the following members.

Properties
 | Name | Description
Public property | EnableLastDownloaded | Gets or sets whether MailBee should save currently downloaded messages in LastDownloadedMessages property.
Public property | InboxMessageCount | Gets the number of messages in the inbox.
Public property | InboxPreloadOptions | Gets or sets the status of whether MailBee will download the list of message sizes and/or the list of message lengths during logging in the inbox.
Public property | InboxSize | Gets the total size (in bytes) occupied by all the messages in the inbox.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | IsConnected | Indicates whether the component is connected to the server.
Public property | IsLoggedIn | Indicates whether the component has already successfully authenticated on the server and logged in the user account.
Public property | IsSslConnection | Indicates whether the current connection (if any) iss secured with TLS/SSL layer.
 | LastDownloadedMessages | Gets the collection of the messages downloaded to the current moment.
Public property | LastResult | Gets a numeric code of the last error.
 | LicenseKey | Obsolete. Assigns the license key.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
 | Proxy | Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RaiseEventsViaMessageLoop | Gets or sets whether the events will be raised on the message loop of the application or not.
Public property | RequestEncoding | Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the server.
Public property | ResponseEncoding | Gets or sets the encoding used to convert a byte data received from the server into a string.
Public property | Site | Gets or sets the object to be used as a site for the component.
 | SslCertificates | Provides access to the client and server SSL certificate settings.
 | SslMode | Gets or sets how the component should establish TLS/SSL connection with the mail server.
Public property | SslProtocol | Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.EnableLastDownloaded Property

Pop3EnableLastDownloaded Property
Gets or sets whether MailBee should save currently downloaded messages in LastDownloadedMessages property.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EnableLastDownloaded { get; set; }
Public Property EnableLastDownloaded As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, any method of Pop3 component which receives mail messages or message headers (RETR or TOP responses) from the server (like DownloadEntireMessages(Int32, Int32), DownloadMessageHeaders(Int32, Int32, Int32), DownloadEntireMessage(Int32), and DownloadMessageHeader(Int32)) will populate LastDownloadedMessages collection with MailMessage objects received and parsed during the method execution; if false, LastDownloadedMessages property will always return a null reference (Nothing in Visual Basic). The default value is false.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3LastDownloadedMessages


Pop3.InboxMessageCount Property

Pop3InboxMessageCount Property
Gets the number of messages in the inbox.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int InboxMessageCount { get; }
Public ReadOnly Property InboxMessageCount As Integer
    Get

Property Value

Type: Int32
The number of messages in the inbox, or 0 if not yet logged in the user account on the server.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3InboxSize


Pop3.InboxPreloadOptions Property

Pop3InboxPreloadOptions Property
Gets or sets the status of whether MailBee will download the list of message sizes and/or the list of message lengths during logging in the inbox.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Pop3InboxPreloadOptions InboxPreloadOptions { get; set; }
Public Property InboxPreloadOptions As Pop3InboxPreloadOptions
    Get
    Set

Property Value

Type: Pop3InboxPreloadOptions
A set of flags indicating which elements of the inbox statistics must be downloaded immediately after the successful login operation. The default value is None.
Remarks

By default, MailBee automatically downloads the required elements the inbox statistics when appropriate. However, in some cases, the developer may prefer to have this data preloaded. For instance, if you're downloading large e-mails (more than 1MB), pre-downloading their sizes will help MailBee to pre-allocate a buffer of the required length and avoid any re-allocations during the download process.

Note Note
This property has effect only if set BEFORE Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method call.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.InboxSize Property

Pop3InboxSize Property
Gets the total size (in bytes) occupied by all the messages in the inbox.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public long InboxSize { get; }
Public ReadOnly Property InboxSize As Long
    Get

Property Value

Type: Int64
The total size (in bytes) occupied by all the messages in the inbox, or 0 if not yet logged in the user account on the server.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3InboxMessageCount


Pop3.IsAborted Property

Pop3IsAborted Property
Indicates whether Abort method has been called for the component.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsAborted { get; }
Public ReadOnly Property IsAborted As Boolean
    Get

Property Value

Type: Boolean
true if Abort method has already been called; otherwise, false. The default value is false.
Remarks

In aborted state, the component does not raise any events, and most methods, if called, will immediately return an error or throw an exception.

ResetState method can be used to restore the component back to operational state.

See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.IsBusy Property

Pop3IsBusy Property
Indicates whether the component is performing a lengthy operation.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBusy { get; }
Public ReadOnly Property IsBusy As Boolean
    Get

Property Value

Type: Boolean
A bool value indicating whether the component is busy because it's doing some work.
Remarks
When the component is busy, it's not possible to start another lengthy operation. For instance, if the component connects to the server or transfers data over the network, no other network operation can be started at this time. Any attempt to do so will result in MailBeeInvalidStateException.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.IsConnected Property

Pop3IsConnected Property
Indicates whether the component is connected to the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsConnected { get; }
Public ReadOnly Property IsConnected As Boolean
    Get

Property Value

Type: Boolean
true if the component is connected to the server; otherwise, false.
Remarks

This property only reflects the state of client side of the connection. If the server forcibly closed the connection on its side, the application won't know about this until it makes an attempt to send or receive data.

In other words, it reflectes the state of the connection at the time when the last data to the moment was received.

To check if you're still connected to the server from its point of view, issue a command to the server, such as Noop. If the method throws an exception, this means the server has closed the connection. If no exception occurred, the connection is still up.

See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.IsLoggedIn Property

Pop3IsLoggedIn Property
Indicates whether the component has already successfully authenticated on the server and logged in the user account.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsLoggedIn { get; }
Public ReadOnly Property IsLoggedIn As Boolean
    Get

Property Value

Type: Boolean
true if already logged in the user account on the server; otherwise, false.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.IsSslConnection Property

Pop3IsSslConnection Property
Indicates whether the current connection (if any) iss secured with TLS/SSL layer.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSslConnection { get; }
Public ReadOnly Property IsSslConnection As Boolean
    Get

Property Value

Type: Boolean
true if the current connection is TLS/SSL; false if the connection is not secure.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.LastDownloadedMessages Property

Pop3LastDownloadedMessages Property
Gets the collection of the messages downloaded to the current moment.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessageCollection LastDownloadedMessages { get; }
Public ReadOnly Property LastDownloadedMessages As MailMessageCollection
    Get

Property Value

Type: MailMessageCollection
A reference to the collection of the mail messages downloaded to the current moment by the corresponding method of Pop3 component, or a null reference (Nothing in Visual Basic) if EnableLastDownloaded is false or no method receiving mail messages has already been called (or if such method failed prior to starting receiving messages).
Remarks
Note Note
This is an advanced property which serves special purposes. It's activated via setting EnableLastDownloaded prior to calling a method which requests mail messages from the server.

This property can be used to get downloaded mail messages in the case if the corresponding method failed. Pop3 methods throw an exception or return a null reference on failure. Sometimes, however, the developer still wishes to get messages which had already been received to the moment of failure (for instance, if 100 messages had been received and error occurred for message #101). In this case, the developer can use this property to get messages which had already been received and parsed to the moment of the failure.

When this collection is not needed any longer, the developer should set EnableLastDownloaded to false to free the resources. Also, LastDownloadedMessages will be reset to a null reference with a new call of any method requesting mail messages from the server.

Examples

This sample demonstrates reliable approach to downloading messages from a POP3 account. The code tolerates disconnections and other errors which may occur during downloading messages. If any problem occurs, the code reconnects to the server if needed and attempts to download the remaining messages (already downloaded messages are not downloaded again, however). Also, the code execution won't end up in an endless loop in the case of permanent errors (if no messages had been downloaded at all, the code won't try again).

To simulate connection drops during the POP3 session, the code suddenly closes the connection during getting message data from the server.

C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Pop3Mail;

class Sample
{
    static int  traffic;
    static bool downloadingMsgs;

    // We use Pop3.DataReceived event to simulate connection drop during
    // getting message data from the server. We do this through closing
    // the connection after 50000 bytes of message data has been received from the
    // server. This may occur multiple times (for instance, if there is 1MB of mail
    // in the inbox, the connection will be dropped about 20 times).
    // If, however, there is a message larger than 50KB in the inbox, the download process
    // will stop because it would otherwise end up in an endless loop (because this code
    // always disconnects on getting 50-th KB of the data and it would never have received
    // such message completely).
    static void pop_DataReceived(object sender, DataTransferEventArgs e)
    {
        if (downloadingMsgs)
        {
            traffic += e.Data.Length;

            // Increase 50000 to a larger value if you wish to test this code with
            // a mailbox containing large messages (larger than 50KB).
            if (traffic > 50000)
            {
                ((Pop3)sender).Log.WriteLine("SIMULATE CONNECTION DROP");
                ((Pop3)sender).GetSocket().Close();
            }
        }
    }

    static void Main(string[] args)
    {
        // Initialize Pop3 object and make it automatically load UIDs of all messages on the server.
        Pop3 pop = new Pop3();
        pop.InboxPreloadOptions = Pop3InboxPreloadOptions.Uidl;

        // Enable logging POP3 session into a file. Useful for troubleshooting.
        // Also, this log can be used to track the history of disconnections and
        // reconnections during downloading messages.
        pop.Log.Filename = @"C:\Temp\log.txt";
        pop.Log.Enabled = true;
        pop.Log.Clear();

        // Attach to a DataReceived event which will be used for simulating
        // connection failures.
        pop.DataReceived += new DataTransferEventHandler(pop_DataReceived);

        // Will set it to true once either everything has been downloaded
        // or a permanent error has occurred.
        bool finished = false;

        // Remember UID of the last message which had already been downloaded.
        // After reconnecting, we'll download messages with UIDs corresponding to
        // subsequent messages. For the first time, set it to null to indicate no
        // messages had already been downloaded.
        string lastUid = null;

        // We'll collect downloaded messages in this collection.
        MailMessageCollection msgs = new MailMessageCollection();

        // Because we catch exceptions in this code but still want to know
        // which error has occurred in the case of permanent failure, we remember
        // the reason of it.
        MailBeeException permanentException = null;

        // Enable cache of messages downloaded during execution of the last method.
        pop.EnableLastDownloaded = true;

        do
        {
            // Prevent connection drop simulation when not downloading messages.
            downloadingMsgs = false;

            // Connect or reconnect to the server if required (and login/select inbox).
            if (!pop.IsConnected)
            {
                pop.Connect("pop.company.com");
            }
            if (!pop.IsLoggedIn)
            {
                pop.Login("jdoe", "secret");
            }

            traffic = 0;

            try
            {
                // Enable connection drop simulation.
                downloadingMsgs = true;

                int lastMsgNumber = 0;
                if (lastUid != null)
                {
                    lastMsgNumber = pop.GetMessageIndexFromUid(lastUid);
                }

                if (lastMsgNumber < pop.InboxMessageCount)
                {
                    // Download the remaining messages.
                    pop.DownloadEntireMessages(lastMsgNumber + 1, -1);
                    msgs.Add(pop.LastDownloadedMessages);
                }

                // Disable connection drop simulation.
                downloadingMsgs = false;

                // All's done.
                finished = true;
            }
            catch (MailBeeException e)
            {
                downloadingMsgs = false;

                if (pop.LastDownloadedMessages == null ||
                    pop.LastDownloadedMessages.Count == 0)
                {
                    // Haven't got any messages. Assume this is permanent error
                    // (otherwise, we could get endless loop).
                    finished = true;
                    permanentException = e;
                }
                else
                {
                    // Error has occurred but some messages have still been
                    // downloaded. We'll proceed with getting the rest of messages.
                    msgs.Add(pop.LastDownloadedMessages);

                    // Get last UID from the value of UID of the last downloaded message.
                    lastUid = (string)pop.LastDownloadedMessages[pop.LastDownloadedMessages.Count - 1].UidOnServer;
                }
            }
        } while (!finished);

        // Clear and disable the cache of the last downloaded messages.
        pop.EnableLastDownloaded = false;

        if (pop.IsConnected)
        {
            // Attempt to disconnect (we need to catch MailBeeSocketObjectDisposedException
            // here because we simulated connection drop bypassing MailBee (using Socket.Close()
            // method) and Pop3.IsConnected could remain true). In real world apps, this
            // is not required and Pop3.IsConnected always reflects the actual state of
            // the connection.
            try
            {
                pop.Disconnect();
            }
            catch (MailBeeSocketObjectDisposedException) {}
        }

        // Display UIDs of the downloaded messages.
        foreach (MailMessage msg in msgs)
        {
            Console.Write((string)msg.UidOnServer + " ");
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Pop3Mail

Class Sample
    Shared traffic As Integer
    Shared downloadingMsgs As Boolean

    ' We use Pop3.DataReceived event to simulate connection drop during
    ' getting message data from the server. We do this through closing
    ' the connection after 50000 bytes of message data has been received from the
    ' server. This may occur multiple times (for instance, if there is 1MB of mail
    ' in the inbox, the connection will be dropped about 20 times).
    ' If, however, there is a message larger than 50KB in the inbox, the download process
    ' will stop because it would otherwise end up in an endless loop (because this code
    ' always disconnects on getting 50-th KB of the data and it would never have received
    ' such message completely).
    Shared Sub pop_DataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        If downloadingMsgs Then
            traffic += e.Data.Length

            ' Increase 50000 to a larger value if you wish to test this code with
            ' a mailbox containing large messages (larger than 50KB).
            If traffic > 50000 Then
                CType(sender, Pop3).Log.WriteLine("SIMULATE CONNECTION DROP")
                CType(sender, Pop3).GetSocket().Close()
            End If
        End If
    End Sub

    Shared Sub Main(ByVal args() As String)
        ' Initialize Pop3 object and make it automatically load UIDs of all messages on the server.
        Dim pop As Pop3 = New Pop3
        pop.InboxPreloadOptions = Pop3InboxPreloadOptions.Uidl

        ' Enable logging POP3 session into a file. Useful for troubleshooting.
        ' Also, this log can be used to track the history of disconnections and
        ' reconnections during downloading messages.
        pop.Log.Filename = "C:\Temp\log.txt"
        pop.Log.Enabled = True
        pop.Log.Clear()

        ' Attach to a DataReceived event which will be used for simulating
        ' connection failures.
        AddHandler pop.DataReceived, AddressOf pop_DataReceived

        ' Will set it to true once either everything has been downloaded
        ' or a permanent error has occurred.
        Dim finished As Boolean = False

        ' Remember UID of the last message which had already been downloaded.
        ' After reconnecting, we'll download messages with UIDs corresponding to
        ' subsequent messages. For the first time, set it to null to indicate no
        ' messages had already been downloaded.
        Dim lastUid As String = Nothing

        ' We'll collect downloaded messages in this collection.
        Dim msgs As MailMessageCollection = New MailMessageCollection

        ' Because we catch exceptions in this code but still want to know
        ' which error has occurred in the case of permanent failure, we remember
        ' the reason of it.
        Dim permanentException As MailBeeException = Nothing

        ' Enable cache of messages downloaded during execution of the last method.
        pop.EnableLastDownloaded = True

        Do
            ' Prevent connection drop simulation when not downloading messages.
            downloadingMsgs = False

            ' Connect or reconnect to the server if required (and login/select inbox).
            If Not pop.IsConnected Then
                pop.Connect("pop.company.com")
            End If
            If Not pop.IsLoggedIn Then
                pop.Login("jdoe", "secret")
            End If

            traffic = 0

            Try
                ' Enable connection drop simulation.
                downloadingMsgs = True

                Dim lastMsgNumber As Integer = 0
                If Not lastUid Is Nothing Then
                    lastMsgNumber = pop.GetMessageIndexFromUid(lastUid)
                End If

                If lastMsgNumber < pop.InboxMessageCount Then
                    ' Download the remaining messages.
                    pop.DownloadEntireMessages(lastMsgNumber + 1, -1)
                    msgs.Add(pop.LastDownloadedMessages)
                End If

                ' Disable connection drop simulation.
                downloadingMsgs = False

                ' All's done.
                finished = True
            Catch e As MailBeeException
                downloadingMsgs = False

                If pop.LastDownloadedMessages Is Nothing Or pop.LastDownloadedMessages.Count = 0 Then
                    ' Haven't got any messages. Assume this is permanent error
                    ' (otherwise, we could get endless loop).
                    finished = True
                    permanentException = e
                Else
                    ' Error has occurred but some messages have still been
                    ' downloaded. We'll proceed with getting the rest of messages.
                    msgs.Add(pop.LastDownloadedMessages)

                    ' Get last UID from the value of UID of the last downloaded message.
                    lastUid = CType(pop.LastDownloadedMessages(pop.LastDownloadedMessages.Count - 1).UidOnServer, String)
                End If
            End Try
        Loop While Not finished

        ' Clear and disable the cache of the last downloaded messages.
        pop.EnableLastDownloaded = False

        If pop.IsConnected Then
            ' Attempt to disconnect (we need to catch MailBeeSocketObjectDisposedException
            ' here because we simulated connection drop bypassing MailBee (using Socket.Close()
            ' method) and Pop3.IsConnected could remain true). In real world apps, this
            ' is not required and Pop3.IsConnected always reflects the actual state of
            ' the connection.
            Try
                pop.Disconnect()
            Catch e As MailBeeSocketObjectDisposedException
            End Try
        End If

        ' Display UIDs of the downloaded messages.
        Dim msg As MailMessage
        For Each msg In msgs
            Console.Write(CType(msg.UidOnServer, String) & " ")
        Next
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3EnableLastDownloaded


Pop3.LastResult Property

Pop3LastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.LicenseKey Property

Pop3LicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Log Property

Pop3Log Property
Gets the object used for logging MailBee activities into a file or memory buffer.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Logger Log { get; }
Public ReadOnly Property Log As Logger
    Get

Property Value

Type: Logger
A reference to the object used for logging MailBee activities into a file or memory buffer.
Remarks
This property is never a null reference (Nothing in Visual Basic) even if logging is not used.
Examples
This sample sets file logging on and sets the filename of the log file.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.Log.Enabled = true;
pop.Log.Filename = @"C:\Temp\log.txt";
pop.Connect("mail.domain.com");
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.Log.Enabled = True
pop.Log.Filename = "C:\Temp\log.txt"
pop.Connect("mail.domain.com")
pop.Disconnect()
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Proxy Property

Pop3Proxy Property
Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ProxyServer Proxy { get; }
Public ReadOnly Property Proxy As ProxyServer
    Get

Property Value

Type: ProxyServer
A reference to the proxy server settings.
Remarks
By default, proxy server is not used. The developer can change this to make MailBee use SOCKS4, SOCKS5, or HTTP proxy server. This is useful when a firewall prohibits direct connections with a mail server but permits connections via a proxy.
Examples
This console sample establishes connection with the mail server via an HTTP proxy server which requires clients to authenticate themselves.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Proxy;

class Sample
{
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();
        pop.Proxy.Name = "proxy.server.com";
        pop.Proxy.Protocol = ProxyProtocol.Http;
        pop.Proxy.Port = 808;
        pop.Proxy.AccountName = "jdoe";
        pop.Proxy.Password = "secret";
        pop.Connect("mail.company.com");
        Console.WriteLine("Connected via a proxy server");
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Proxy

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim pop As New Pop3
        pop.Proxy.Name = "proxy.server.com"
        pop.Proxy.Protocol = ProxyProtocol.Http
        pop.Proxy.Port = 808
        pop.Proxy.AccountName = "jdoe"
        pop.Proxy.Password = "secret"
        pop.Connect("mail.company.com")
        Console.WriteLine("Connected via a proxy server")
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
MailBee.ProxyProxyServer


Pop3.RaiseEvents Property

Pop3RaiseEvents Property
Gets or sets whether the component will raise any events.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEvents { get; set; }
Public Property RaiseEvents As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will raise any events. The default value is true.
Remarks
If this propery is false, OnEventName methods will also not be called.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.RaiseEventsViaMessageLoop Property

Pop3RaiseEventsViaMessageLoop Property
Gets or sets whether the events will be raised on the message loop of the application or not.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEventsViaMessageLoop { get; set; }
Public Property RaiseEventsViaMessageLoop As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the events will be raised on the message loop of the application or not. The default value is true.
Remarks
This property is only meaningful in WinForms applications where events and asynchronous methods are used, and the developer needs to block the message loop for some reason (usually, to wait for completion of an asynchronous method). In this case, you should set this property to false and use Wait method to wait until asynchronous MailBee method is finished. See Wait method for more information.

The above also applies to synchronous methods if they are called on worker (non-UI) threads. If, however, the application does not use asynchronous methods of MailBee (and never calls its synchronous methods on non-UI threads), it should NOT attempt to set RaiseEventsViaMessageLoop to false or use Wait method.

Note Note
If you develop non-WinForms application (such as web or console application), you do not need to set this property or use Wait method regardless if the application uses worker threads or not.
Another alternative (in WinForms application) to using Wait method is to never block the application message loop. See BeginExecuteCustomCommand(String, Boolean, AsyncCallback, Object) method for the code example.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.RequestEncoding Property

Pop3RequestEncoding Property
Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding RequestEncoding { get; set; }
Public Property RequestEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert a string into a bytes stream which is then sent to the server. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.ResponseEncoding Property

Pop3ResponseEncoding Property
Gets or sets the encoding used to convert a byte data received from the server into a string.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ResponseEncoding { get; set; }
Public Property ResponseEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert a byte data received from the server into a string. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Site Property

Pop3Site Property
Gets or sets the object to be used as a site for the component.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual ISite Site { get; set; }
Public Overridable Property Site As ISite
    Get
    Set

Property Value

Type: ISite
A reference to the object to be used as a site for the component. The default value is a null reference (Nothing in Visual Basic).

Implements

IComponentSite
Remarks
The developer does not need to set this property. It's used by RAD tools such as form designers.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.SslCertificates Property

Pop3SslCertificates Property
Provides access to the client and server SSL certificate settings.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ClientServerCertificates SslCertificates { get; }
Public ReadOnly Property SslCertificates As ClientServerCertificates
    Get

Property Value

Type: ClientServerCertificates
A reference to the client and server SSL certificate settings.
Remarks

The following code should be used to access the server certificate (assuming pop is a Pop3 component instance): pop.SslCertificates.Server. To set the client certificate, the developer should assign pop.SslCertificates.Client property.

Examples
This console sample establishes secure connection with the mail server using the private certificate of the client and then displays various information about the server certificate. The client certificate is taken from a file (MailBee can also read certificates from the registry, see CertificateStore class description for details).
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Security;

class Sample
{
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();
        pop.SslMode = SslStartupMode.OnConnect;
        pop.SslCertificates.Client = new Certificate(@"C:\my.pfx", CertFileType.Pfx, "secret");
        pop.Connect("mail.domain.com", 995);
        Console.WriteLine("The server certificate info");
        Console.WriteLine("===========================");
        Console.WriteLine("Issued by:    " + pop.SslCertificates.Server.IssuedBy);
        Console.WriteLine("Issued to:    " + pop.SslCertificates.Server.IssuedTo);
        Console.WriteLine("Valid from:    " + pop.SslCertificates.Server.ValidFromDate);
        Console.WriteLine("Valid to:    " + pop.SslCertificates.Server.ValidToDate);
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Security

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim pop As New Pop3
        pop.SslMode = SslStartupMode.OnConnect
        pop.SslCertificates.Client = New Certificate("C:\my.pfx", CertFileType.Pfx, "secret")
        pop.Connect("mail.domain.com", 995)
        Console.WriteLine("The server certificate info")
        Console.WriteLine("===========================")
        Console.WriteLine("Issued by:    " & pop.SslCertificates.Server.IssuedBy)
        Console.WriteLine("Issued to:    " & pop.SslCertificates.Server.IssuedTo)
        Console.WriteLine("Valid from:    " & pop.SslCertificates.Server.ValidFromDate)
        Console.WriteLine("Valid to:    " & pop.SslCertificates.Server.ValidToDate)
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
MailBee.SecurityCertificate
MailBee.SecurityCertificateStore


Pop3.SslMode Property

Pop3SslMode Property
Gets or sets how the component should establish TLS/SSL connection with the mail server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SslStartupMode SslMode { get; set; }
Public Property SslMode As SslStartupMode
    Get
    Set

Property Value

Type: SslStartupMode
One of SslStartupMode values specifying if and how the component should establish TLS/SSL connection with the mail server. The default value is Manual which means the connection won't be established in TLS/SSL mode unless the developer manually calls StartTls method.
Remarks

AutodetectPortAndSslMode property may cause MailBee to automatically enable TLS/SSL for some well-known hosts or ports even if SslMode property has its default value.

Note Note
Not all mail servers support TLS/SSL functionality. Also, some servers support only newest TLS versions (see SslProtocol topic for details).
Examples
This sample connects to the mail server on regular port 110, then switches the connection into TLS/SSL mode using STLS command, logs in the mail account and downloads the first mail message in this account.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Security;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Pop3 pop = new Pop3();
pop.SslMode = SslStartupMode.UseStartTls;
pop.Connect("mail.domain.com");
pop.Login("jdoe", "secret");
if (pop.InboxMessageCount > 0)
{
    MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);
    Console.WriteLine(msg.Attachments.Count + " attachment(s) in the message.");
}
pop.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Security
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim pop As New Pop3
pop.SslMode = SslStartupMode.UseStartTls
pop.Connect("mail.domain.com")
pop.Login("jdoe", "secret")
If pop.InboxMessageCount > 0 Then
    MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);
    Console.WriteLine(msg.Attachments.Count & " attachment(s) in the message.");
End If
pop.Disconnect();
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SslProtocol
Pop3StartTls


Pop3.SslProtocol Property

Pop3SslProtocol Property
Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SecurityProtocol SslProtocol { get; set; }
Public Property SslProtocol As SecurityProtocol
    Get
    Set

Property Value

Type: SecurityProtocol
One of SecurityProtocol values specifying the security protocol to be used for performing TLS/SSL negotiation and data encryption. The default value is Auto.
Remarks
The default value allows MailBee to select the best (the most secure) protocol supported by the mail server. However, if the mail server does not support automatic protocol negotiation, it will likely close the connection (MailBeeSocketResetException will be thrown). In this case, the application should set this property to non-Auto value (such as Tls1).
Note Note
In case of UWP platform, MailBee always uses TlsAuto setting.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.SynchronizingObject Property

Pop3SynchronizingObject Property
Gets or sets the object used to marshal the calls of the event handlers.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ISynchronizeInvoke SynchronizingObject { get; set; }
Public Property SynchronizingObject As ISynchronizeInvoke
    Get
    Set

Property Value

Type: ISynchronizeInvoke
A reference to the object on whose thread the events should be raised. The default value is a null reference (Nothing in Visual Basic) which tells MailBee to determine the appropriate marshalling object automatically.
Remarks
Usually, you do not need to set this property because MailBee can automatically marshal events to proper threads.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.ThrowExceptions Property

Pop3ThrowExceptions Property
Gets or sets whether the component will throw exceptions on errors.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the component methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult, GetErrorDescription, GetServerResponse, GetSocketError members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee usage will still be thrown. Typical examples of such errors are: passing invalid arguments to methods, calling methods or settings properties in illegal state (for instance, an attempt to start an asynchronous method while another asynchronous method is not yet finished), etc. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

ThrowExceptions property does not control whether to throw exceptions which occur due to logging errors (such as "log file cannot be written to", etc). To control whether logging exceptions should be thrown, the developer can use Log.DisableOnException property.

See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Timeout Property

Pop3Timeout Property
Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Timeout { get; set; }
Public Property Timeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error, or zero to wait indefinitely. The default value is DefaultTimeout.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | Timeout is negative.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.TrialDaysLeft Property

Pop3TrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value which contains the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Version Property

Pop3Version Property
Gets the version of the MailBee assembly.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3 Events

Pop3 Events

The Pop3 type exposes the following members.

Events
 | Name | Description
 | Connected | Occurs when the connection with the server is successfully established.
 | DataReceived | Occurs when data is received from the POP3 server.
 | DataSent | Occurs when data is sent to the POP3 server.
 | Disconnected | Occurs when the connection with the server gets closed.
Public event | Disposed | Occurs after the component was disposed.
 | ErrorOccurred | Occurs when the MailBeeException is thrown.
 | HostResolved | Occurs when the POP3 server name is successully resolved into IP address(es).
 | LoggedIn | Occurs when the component successfully authenticates the user on the server and logs in the user account.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Pop3.Log.MemoryLog is true).
 | LowLevelDataReceived | Occurs when data is received from the connected socket.
 | LowLevelDataSent | Occurs when data is sent to the connected socket.
 | MessageDataChunkReceived | Occurs on progress of downloading message source data from the server.
 | MessageDownloaded | Occurs when a message was downloaded from the server.
 | SocketConnected | Occurs when the POP3 server accepts the connection attempt and opens the transmission channel between the remote host (POP3 server) and the client (MailBee).
 | SocketCreating | Occurs when MailBee needs a new socket object for establishing a connection with the POP3 server.
 | TlsStarted | Occurs when the connection with the server becomes secure.
Top
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.Connected Event

Pop3Connected Event
Occurs when the connection with the server is successfully established.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ConnectedEventHandler Connected
Public Event Connected As ConnectedEventHandler

Value

Type: MailBeeConnectedEventHandler
Remarks
This event indicates successful completion of the connection procedure, while SocketConnected event (occurs before Connected) indicates the connection request from MailBee was accepted by the server, and the POP3 connection procedure will now begin.
Examples
This sample uses Connected event to report the successful connection status into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // Connected event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Successfully connected to the server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to Connected event.
        pop.Connected += new ConnectedEventHandler(OnConnected);

        pop.Connect("mail.domain.com");
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' Connected event handler.
    Private Shared Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Successfully connected to the server.")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to Connected event.
        AddHandler pop.Connected, AddressOf OnConnected

        pop.Connect("mail.domain.com")
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SocketConnected


Pop3.DataReceived Event

Pop3DataReceived Event
Occurs when data is received from the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataReceived
Public Event DataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

Unlike LowLevelDataReceived event, occurrence of this event indicates receiving POP3-related data only. For instance, if the transmission channel is SSL-encrypted, LowLevelDataReceived event indicates receiving of encrypted data, while DataReceived will be raised later (after decrypting the data). If the transmission channel is not encrypted or otherwise scrambled, DataReceived and LowLevelDataReceived are equivalent.

Unlike MessageDataChunkReceived event, DataReceived will be raised when any POP3-related data is received, while MessageDataChunkReceived event is raised only when message header or entire message data is downloaded.

Note Note
This event is also raised when zero-length data is received from the server. When the server sends zero-length data portion, it means the server closed the connection. This normally happens after Disconnect method was called.
Examples
This sample prints all the data received from the server during POP3 session into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("[" + System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the DataReceived event.
        pop.DataReceived += new DataTransferEventHandler(OnDataReceived);

        // Do something which would produce some network traffic.
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' DataReceived event handler.
    Private Shared Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("[" & System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the DataReceived event.
        AddHandler pop.DataReceived, AddressOf OnDataReceived

        ' Do something which would produce some network traffic.
        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3MessageDataChunkReceived
Pop3LowLevelDataReceived


Pop3.DataSent Event

Pop3DataSent Event
Occurs when data is sent to the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataSent
Public Event DataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks
Unlike LowLevelDataSent event, occurrence of this event indicates sending POP3-related data only. For instance, if the transmission channel is SSL-encrypted, LowLevelDataSent event indicates sending of any portion of encrypted data, while DataSent will be raised later to indicate the entire request (which was previously sent as one or several encrypted data chunks) has been sent. If the transmission channel is not encrypted or otherwise scrambled, DataSent and LowLevelDataSent are equivalent.
Examples
This sample prints all the data sent to the server during POP3 session into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // DataSent event handler.
    private static void OnDataSent(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("[" + System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the DataSent event.
        pop.DataSent += new DataTransferEventHandler(OnDataSent);

        // Do something which would produce some network traffic.
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' DataSent event handler.
    Private Shared Sub OnDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("[" & System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the DataReceived event.
        AddHandler pop.DataReceived, AddressOf OnDataSent

        ' Do something which would produce some network traffic.
        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3LowLevelDataSent


Pop3.Disconnected Event

Pop3Disconnected Event
Occurs when the connection with the server gets closed.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DisconnectedEventHandler Disconnected
Public Event Disconnected As DisconnectedEventHandler

Value

Type: MailBeeDisconnectedEventHandler
Remarks
This event is raised in all the cases when the connection gets closed, including normal shutdown and failures.
Note Note
If Abort method is called, the connection is immediately closed, but no events (including Disconnected) are raised any longer.
Examples
This sample demonstrates that Disconnected event raises even on failures (when MailBeeException is thrown). The sample connects to the POP3 server and then sends invalid data to the server. The server does not respond and the network operation times out.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // Disconnected event handler.
    private static void OnDisconnected(object sender, DisconnectedEventArgs e)
    {
        if (e.IsNormalShutdown)
        {
            // QUIT command was sent to POP3 server.
            Console.WriteLine("Normally disconnected from the server.");
        }
        else
        {
            // Rough disconnect (due to failure). If any messages have been
            // flagged for deletion, they will possibly not be deleted.
            Console.WriteLine("The connection was terminated.");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to Disconnected event.
        pop.Disconnected += new DisconnectedEventHandler(OnDisconnected);

        pop.Connect("mail.domain.com");

        // We do not want to wait too long. Set one second as timeout value.
        pop.Timeout = 1000;

        // Simulate connection error by sending a request to which the POP3
        // server will never respond (due to a lack of "\r\n" in the request data).
        // This will cause MailBee to terminate the connection and raise
        // Disconnected event, and then throw MailBeeException (exceptions are
        // enabled by default).
        pop.ExecuteCustomCommand("NONSENSE", false);

        // This line will probably never execute (unless the server
        // suddenly responds to NONSENSE sequence of bytes).
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' Disconnected event handler.
    Private Shared Sub OnDisconnected(ByVal sender As Object, ByVal e As DisconnectedEventArgs)
        If e.IsNormalShutdown Then
            ' QUIT command was sent to POP3 server.
            Console.WriteLine("Normally disconnected from the server.")
        Else
            ' Rough disconnect (due to failure). If any messages have been
            ' flagged for deletion, they will possibly not be deleted.
            Console.WriteLine("The connection was terminated.")
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LoggedIn event.
        AddHandler pop.Disconnected, AddressOf OnDisconnected

        pop.Connect("mail.domain.com")

        ' We do not want to wait too long. Set one second as timeout value.
        pop.Timeout = 1000

        ' Simulate connection error by sending a request to which the POP3
        ' server will never respond (due to a lack of "\r\n" in the request data).
        ' This will cause MailBee to terminate the connection and raise
        ' Disconnected event, and then throw MailBeeException (exceptions are
        ' enabled by default).
        pop.ExecuteCustomCommand("NONSENSE", False)

        ' This line will probably never execute (unless the server
        ' suddenly responds to NONSENSE sequence of bytes).
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Disconnect


Pop3.Disposed Event

Pop3Disposed Event
Occurs after the component was disposed.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event EventHandler Disposed
Public Event Disposed As EventHandler

Value

Type: SystemEventHandler

Implements

IComponentDisposed
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.ErrorOccurred Event

Pop3ErrorOccurred Event
Occurs when the MailBeeException is thrown.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ErrorEventHandler ErrorOccurred
Public Event ErrorOccurred As ErrorEventHandler

Value

Type: MailBeeErrorEventHandler
Remarks

When MailBee encounters any error, it throws the MailBeeException. However, MailBee can trap this exception if the error was not critical. For instance, if the POP3 server responds with a negative reply to an optional POP3 command (such as CAPA), the MailBeeException will be thrown and then trapped by MailBee itself, but no exception will be thrown to the application code. Such errors are called warnings.

ErrorOccurred event allows the developer to track both warnings and critical errors because it's raised for a particular exception even if MailBee will trap this exception and do not pass it to the application code.

Examples
This sample logs all the warnings and critical errors issued during the POP3 session into the console. If the connection succeeds and the POP3 server does support CAPA command, no output will be produced. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        // Check whether the error is critical or not.
        if (e.IsFinalError)
        {
            // Display corresponding MailBeeException.Message.
            // After OnErrorOccurred handler finishes, MailBee will
            // throw the same exception to the application code.
            Console.WriteLine("CRITICAL ERROR: " + e.Reason.Message);
        }
        else
        {
            // Display corresponding MailBeeException.Message.
            // After OnErrorOccurred handler finishes, MailBee will
            // try another methods to accomplish the current task.
            Console.WriteLine("WARNING: " + e.Reason.Message);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the ErrorOccurred event.
        pop.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Connect to the server.
        pop.Connect("mail.domain.com");

        // Request any data which needs CAPA command to be issued
        // in order to obtain the required information. The list of supported
        // authentication methods can serve this purpose. If CAPA command
        // fails (but the server responds, i.e. the connection itself is still valid),
        // MailBee will not throw any exception to the application code
        // (but ErrorOccurred event will still be raised) and will try to issue
        // AUTH command to get the list of supported authentication methods.
        // If AUTH command fails too, it's still not a critical error. SASL
        // authentication methods will just not be available.
        AuthenticationMethods authMethods = pop.GetSupportedAuthMethods();

        // Close the connection
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports Pop3Mail

Public Class Sample
    ' ErrorOccurred event handler.
    Private Shared Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        ' Check whether the error is critical or not
        If e.IsFinalError Then
            ' Display corresponding MailBeeException.Message.
            ' After OnErrorOccurred handler finishes, MailBee will
            ' throw the same exception to the application code.
            Console.WriteLine("CRITICAL ERROR: " & e.Reason.Message)
        Else
            ' Display corresponding MailBeeException.Message.
            ' After OnErrorOccurred handler finishes, MailBee will
            ' try another methods to accomplish the current task.
            Console.WriteLine("WARNING: " & e.Reason.Message)
        End If
    End Sub

    ' The actual code
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the ErrorOccurred event.
        AddHandler pop.ErrorOccurred, AddressOf OnErrorOccurred

        ' Connect to the server.
        pop.Connect("mail.domain.com")

        ' Request any data which needs CAPA command to be issued
        ' in order to obtain the required information. The list of supported
        ' authentication methods can serve this purpose. If CAPA command
        ' fails (but the server responds, i.e. the connection itself is still valid),
        ' MailBee will not throw any exception to the application code
        ' (but ErrorOccurred event will still be raised) and will try to issue
        ' AUTH command to get the list of supported authentication methods.
        ' If AUTH command fails too, it's still not a critical error. SASL
        ' authentication methods will just not be available.
        Dim authMethodrs As AuthenticationMethods = pop.GetSupportedAuthMethods()

        ' Close the connection.
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.HostResolved Event

Pop3HostResolved Event
Occurs when the POP3 server name is successully resolved into IP address(es).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event HostResolvedEventHandler HostResolved
Public Event HostResolved As HostResolvedEventHandler

Value

Type: MailBeeHostResolvedEventHandler
Remarks
If the POP3 server name (serverName parameter of Connect(String, Int32, Boolean) method) was already specified as an IP address, this event is still raised.
Note Note
No checking if performed on whether the resolved IP address points to the live host.
Examples
This sample connects to the POP3 server host and prints all the IP addresses of this host into console. Most hosts, however, have only one IP address assigned.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // HostResolved event handler.
    private static void OnHostResolved(object sender, HostResolvedEventArgs e)
    {
        foreach (System.Net.IPAddress ip in e.RemoteHost.AddressList)
        {
            Console.WriteLine(ip.ToString());
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the HostResolved event.
        pop.HostResolved += new HostResolvedEventHandler(OnHostResolved);

        pop.Connect("mail.domain.com");
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' HostResolved event handler.
    Private Shared Sub OnHostResolved(ByVal sender As Object, ByVal e As HostResolvedEventArgs)
        For Each ip As System.Net.IPAddress In e.RemoteHost.AddressList
            Console.WriteLine(ip.ToString())
        Next
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LowLevelDataSent event.
        AddHandler pop.HostResolved, AddressOf OnHostResolved

        pop.Connect("mail.domain.com")
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SocketConnected
Pop3Connected


Pop3.LoggedIn Event

Pop3LoggedIn Event
Occurs when the component successfully authenticates the user on the server and logs in the user account.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LoggedInEventHandler LoggedIn
Public Event LoggedIn As LoggedInEventHandler

Value

Type: MailBeeLoggedInEventHandler
Remarks
After raising this event, the component will download the mailbox statistics from the mail server (number of messages in the mailbox, and other information as specified by InboxPreloadOptions property setting.
Examples
This sample connects to the POP3 server, logs in the user account, and downloads the complete mailbox statistics. The sample demonstrates there is a delay between LoggedIn event occurence and Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method completion, which is the amount of time spent on downloading the mailbox statistics after completion of the authentication process.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // LoggedIn event handler.
    private static void OnLoggedIn(object sender, LoggedInEventArgs e)
    {
        Console.WriteLine("Successfully logged in the user account at " +
            (DateTime.Now - DateTime.Today));
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the LoggedIn event.
        pop.LoggedIn += new LoggedInEventHandler(OnLoggedIn);

        pop.Connect("mail.domain.com");

        // Set "download the complete mailbox statistics" mode to increase the delay
        // between LoggedIn event and Login method completion
        pop.InboxPreloadOptions = Pop3InboxPreloadOptions.List | Pop3InboxPreloadOptions.Uidl;

        // Authenticate the user, log in the mailbox, and download the mailbox statistics.
        pop.Login("jdoe", "secret");

        Console.WriteLine("The user account statistics received at " +
            (DateTime.Now - DateTime.Today));

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' LoggedIn event handler.
    Private Shared Sub OnLoggedIn(ByVal sender As Object, ByVal e As LoggedInEventArgs)
        Dim DNow As DateTime = DateTime.Now
        Dim DToday As DateTime = DateTime.Today
        Console.WriteLine("Successfully logged in the user account at " & _
            DateDiff(DateInterval.Hour, DateTime.Now, DateTime.Today))
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LoggedIn event.
        AddHandler pop.LoggedIn, AddressOf OnLoggedIn

        pop.Connect("mail.domain.com")

        ' Set "download the complete mailbox statistics" mode to increase the delay
        ' between LoggedIn event and Login method completion.
        pop.InboxPreloadOptions = Pop3InboxPreloadOptions.List Or Pop3InboxPreloadOptions.Uidl

        ' Authenticate the user, log in the mailbox, and download the mailbox statistics.
        pop.Login("jdoe", "secret")

        Console.WriteLine("The user account statistics received at " & _
            DateDiff(DateInterval.Hour, DateTime.Now, DateTime.Today))

        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod)


Pop3.LogNewEntry Event

Pop3LogNewEntry Event
Occurs when an entry is written into the log file (or into the memory buffer if Pop3.Log.MemoryLog is true).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LogNewEntryEventHandler LogNewEntry
Public Event LogNewEntry As LogNewEntryEventHandler

Value

Type: MailBeeLogNewEntryEventHandler
Remarks

This event is raised only if logging is turned on (Enabled is true).

MailBee raises this event BEFORE adding the entry into the the log. Since many properties of NewEntry object are editable, the developer can change the data MailBee will put into the log or even cancel logging the current entry at all. This may be useful the developer wishes to log only those entires which meet certain criteria.

Note Note
Entries added by the developer (through WriteLine(String) method call) do not cause this event to be raised. Thus, it's safe to add user-defined log entries even in the LogNewEntry event handler itself. This does not cause endless recursion which would otherwise occur if WriteLine(String) method called in LogNewEntry event handler raised this event again.
Examples
This sample enables logging the POP3 session into a file, and logs only those entries which indicate any data traffic between the client (MailBee) and the server. Other entries are discarded, and user-defined log entry is added instead. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // LogNewEntry event handler.
    private static void OnLogNewEntry(object sender, LogNewEntryEventArgs e)
    {
        if ( !(e.NewEntry.MessageType == LogMessageType.Recv ||
            e.NewEntry.MessageType == LogMessageType.Send) )
        {
            // Do not add this entry if it does not indicate any data transfer,
            // and put our own message instead.
            e.NewEntry.AddThisEntry = false;
            ((Pop3)sender).Log.WriteLine("UNWANTED MESSAGE REMOVED");

            // Note: we could produce similar results just by writing new values
            // into MessageText and MessageComment properties of the original entry.
            // The code above uses Log.WriteLine method just to show how to add new
            // entries in the event handler itself. You may comment 2 code lines above
            // and uncomment 2 code lines below to use the alternate approach.
            //
            // e.NewEntry.MessageText = "UNWANTED MESSAGE REMOVED";
            // e.NewEntry.MessageComment = string.Empty;
        }
    }

    // The actual code
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Enable logging the POP3 session into a file.
        pop.Log.Enabled = true;
        pop.Log.Filename = @"C:\Temp\log.txt";
        pop.Log.Clear();

        // Subscribe to the LogNewEntry event.
        pop.LogNewEntry += new LogNewEntryEventHandler(OnLogNewEntry);

        // Do something which would produce some network traffic.
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");
        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Public Class Sample
    ' LogNewEntry event handler.
    Private Shared Sub OnLogNewEntry(ByVal sender As Object, ByVal e As LogNewEntryEventArgs)
        If Not (e.NewEntry.MessageType = LogMessageType.Recv Or _
            e.NewEntry.MessageType = LogMessageType.Send) Then
            ' Do not add this entry if it does not indicate any data transfer,
            ' and put our own message instead.
            e.NewEntry.AddThisEntry = False
            sender.Log.WriteLine("UNWANTED MESSAGE REMOVED");

            ' Note: we could produce similar results just by writing new values
            ' into MessageText and MessageComment properties of the original entry.
            ' The code above uses Log.WriteLine method just to show how to add new
            ' entries in the event handler itself. You may comment 2 code lines above
            ' and uncomment 2 code lines below to use the alternate approach.
            '
            ' e.NewEntry.MessageText = "UNWANTED MESSAGE REMOVED"
            ' e.NewEntry.MessageComment = String.Empty
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Enable logging the POP3 session into a file.
        pop.Log.Enabled = True
        pop.Log.Filename = "C:\Temp\log.txt"
        pop.Log.Clear()

        ' Subscribe to the LogNewEntry event.
        AddHandler pop.LogNewEntry, AddressOf OnLogNewEntry

        ' Do something which would produce some network traffic.
        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")
        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace


Pop3.LowLevelDataReceived Event

Pop3LowLevelDataReceived Event
Occurs when data is received from the connected socket.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler LowLevelDataReceived
Public Event LowLevelDataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

If the transmission channel is encrypted, this event will be raised when any encrypted chunk of data is received. Thus, this event can be used to record the data which is actually received from the network.

The typical use of this property is to calculate the network traffic produced during the POP3 session. SSL encryption increases the length of the transmitted data blocks, thus it's more accurate to calculate traffic by counting the length of data actually transmitted over the network.

If the transmission channel is not encrypted or otherwise scrambled, this property is equivalent to DataReceived.

Examples
This sample calculates all incoming traffic from the server during the POP3 session, and prints the result into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // Total bytes received counter.
    private static int _totalBytes = 0;

    // LowLevelDataReceived event handler.
    private static void OnLowLevelDataReceived(object sender,
        DataTransferEventArgs e)
    {
        // Increment the counter.
        _totalBytes += e.Data.Length;
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the LowLevelDataReceived event.
        pop.LowLevelDataReceived += new DataTransferEventHandler(OnLowLevelDataReceived);

        // Do something which would produce some network traffic.
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");
        MailMessageCollection msgs = pop.DownloadMessageHeaders();
        pop.Disconnect();

        // Print the total number of bytes previously received from the server.
        Console.WriteLine(_totalBytes + " bytes received in all");
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' Total bytes received counter.
    Private Shared _totalBytes = 0

    ' LowLevelDataReceived event handler.
    Private Shared Sub OnLowLevelDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Increment the counter.
        _totalBytes += e.Data.Length
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LowLevelDataReceived event.
        AddHandler pop.LowLevelDataReceived, AddressOf OnLowLevelDataReceived

        ' Do something which would produce some network traffic.
        pop.Connect("pop.somehost.com")
        pop.Login("jdoe", "secret")

        Dim msgs As MailMessageCollection
        msgs = pop.DownloadMessageHeaders()
        pop.Disconnect()

        ' Print the total number of bytes previously received from the server.
        Console.WriteLine(_totalBytes & " bytes received in all")
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DataReceived


Pop3.LowLevelDataSent Event

Pop3LowLevelDataSent Event
Occurs when data is sent to the connected socket.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler LowLevelDataSent
Public Event LowLevelDataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

If the transmission channel is encrypted, this event will be raised each time an encrypted chunk of data is successfully sent. Thus, this event can be used to record the data which is actually sent to the network.

The typical use of this property is to calculate the network traffic produced during the POP3 session. SSL encryption increases the length of the transmitted data blocks, thus it's more accurate to calculate traffic by counting the length of data actually transmitted over the network.

If the transmission channel is not encrypted or otherwise scrambled, this property is equivalent to DataSent.

Examples
This sample calculates all outgoing traffic to the server during the POP3 session, and prints the result into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // Total bytes sent counter.
    private static int _totalBytes = 0;

    // LowLevelDataSent event handler.
    private static void OnLowLevelDataSent(object sender,
        DataTransferEventArgs e)
    {
        _totalBytes += e.Data.Length;
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the LowLevelDataSent event.
        pop.LowLevelDataSent += new DataTransferEventHandler(OnLowLevelDataSent);

        // Do something which would produce some network traffic.
        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");
        MailMessageCollection msgs = pop.DownloadMessageHeaders();
        pop.Disconnect();

        // Print the total number of bytes previously sent to the server.
        Console.WriteLine(_totalBytes + " bytes sent in all");
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' Total bytes sent counter.
    Private Shared _totalBytes = 0

    ' LowLevelDataSent event handler.
    Private Shared Sub OnLowLevelDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        _totalBytes += e.Data.Length
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LowLevelDataSent event.
        AddHandler pop.LowLevelDataSent, AddressOf OnLowLevelDataSent

        ' Do something which would produce some network traffic.
        pop.Connect("pop.somehost.com")
        pop.Login("jdoe", "secret")
        Dim msgs As MailMessageCollection
        msgs = pop.DownloadMessageHeaders()
        pop.Disconnect()

        ' Print the total number of bytes previously received from the server.
        Console.WriteLine(_totalBytes & " bytes received in all")
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DataSent


Pop3.MessageDataChunkReceived Event

Pop3MessageDataChunkReceived Event
Occurs on progress of downloading message source data from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event Pop3MessageDataChunkReceivedEventHandler MessageDataChunkReceived
Public Event MessageDataChunkReceived As Pop3MessageDataChunkReceivedEventHandler

Value

Type: MailBee.Pop3MailPop3MessageDataChunkReceivedEventHandler
Remarks

This event is a special case of DataReceived event. While DataReceived event occurs when any data is received, MessageDataChunkReceived event indicates message data is being received. In other words, MessageDataChunkReceived event is a filtered version of more general DataReceived event.

When both DataReceived and MessageDataChunkReceived events are used, DataReceived is raised first.

Examples
This sample completely downloads the last message in the inbox, and deletes it from the server. Both DataReceived and MessageDataChunkReceived events are handled, and the corresponding messages are printed into console when each of these events is raised. This sample demonstrates that DataReceived is raised more often than MessageDataChunkReceived.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine(e.Data.Length + " bytes received");
    }

    // MessageDataChunkReceived event handler.
    private static void OnMessageDataChunkReceived(object sender,
        Pop3MessageDataChunkReceivedEventArgs e)
    {
        Console.WriteLine(e.BytesJustReceived + " bytes of the message #" +
            e.MessageNumber + " received");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to events.
        pop.DataReceived += new DataTransferEventHandler(OnDataReceived);
        pop.MessageDataChunkReceived +=
            new Pop3MessageDataChunkReceivedEventHandler(OnMessageDataChunkReceived);

        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");

        // Completely download the last message in the inbox.
        MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' Connected event handler.
    Private Shared Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine(e.Data.Length & " bytes received")
    End Sub

    Private Shared Sub OnMessageDataChunkReceived(ByVal sender As Object, _
        ByVal e As Pop3MessageDataChunkReceivedEventArgs)
        Console.WriteLine(e.BytesJustReceived & " bytes of the message #" & _
            e.MessageNumber & " received")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to events.
        AddHandler pop.DataReceived, AddressOf OnDataReceived
        AddHandler pop.MessageDataChunkReceived, _
            AddressOf OnMessageDataChunkReceived

        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")

        ' Completely download the last message in the inbox.
        Dim msg As MailMessage
        msg = pop.DownloadEntireMessage(pop.InboxMessageCount)

        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DataReceived


Pop3.MessageDownloaded Event

Pop3MessageDownloaded Event
Occurs when a message was downloaded from the server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event Pop3MessageDownloadedEventHandler MessageDownloaded
Public Event MessageDownloaded As Pop3MessageDownloadedEventHandler

Value

Type: MailBee.Pop3MailPop3MessageDownloadedEventHandler
Remarks

If only message headers were requested for download (e.g. DownloadMessageHeaders(Int32, Int32, Int32) method was called), this event is raised when a message header is downloaded.

When multiple messages are downloaded, this event is raised for every message (or message header) which was downloaded.

Examples
This sample downloads headers of the last 10 messages in the inbox. For each downloaded header, the corresponding status message is displayed.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;

class Sample
{
    // MessageDownloaded event handler.
    private static void OnMessageDownloaded(object sender,
        Pop3MessageDownloadedEventArgs e)
    {
        Console.WriteLine("The header of the message #" + e.MessageNumber +
            " has been downloaded");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the MessageDownloaded event.
        pop.MessageDownloaded +=
            new Pop3MessageDownloadedEventHandler(OnMessageDownloaded);

        pop.Connect("mail.domain.com");
        pop.Login("jdoe", "secret");

        // Download headers of the last 10 messages in the inbox.
        MailMessageCollection msgs = pop.DownloadMessageHeaders(pop.InboxMessageCount - 9, 10);

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime

Class Sample
    ' MessageDownloaded event handler.
    Private Shared Sub OnMessageDownloaded(ByVal sender As Object, _
        ByVal e As Pop3MessageDownloadedEventArgs)
        Console.WriteLine("The header of the message #" & e.MessageNumber & _
            " has been downloaded")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the MessageDownloaded event.
        AddHandler pop.MessageDownloaded, AddressOf OnMessageDownloaded

        pop.Connect("mail.domain.com")
        pop.Login("jdoe", "secret")

        ' Download headers of the last 10 messages in the inbox.
        Dim msgs As MailMessageCollection = pop.DownloadMessageHeaders(pop.InboxMessageCount - 9, 10)

        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3DownloadEntireMessage(Int32)
Pop3DownloadEntireMessages(Int32, Int32)
Pop3DownloadMessageHeader(Int32)
Pop3DownloadMessageHeaders(Int32, Int32, Int32)


Pop3.SocketConnected Event

Pop3SocketConnected Event
Occurs when the POP3 server accepts the connection attempt and opens the transmission channel between the remote host (POP3 server) and the client (MailBee).

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SocketConnectedEventHandler SocketConnected
Public Event SocketConnected As SocketConnectedEventHandler

Value

Type: MailBeeSocketConnectedEventHandler
Remarks
This event is raised immediately after Socket successfully connected to the POP3 server host. After the socket itself has been connected and this event raised, the client needs to receive some data from the server in order to complete the procedure of establishing connection with the POP3 server. If the connection must be SSL-encrypted, a few additional round-trips to the server required in order to completely establish the connection. Then, once the connection is fully initialized and ready for sending POP3 commands to the server, Connected event is raised.
Examples
This sample demonstrates the order in which events are raised during Connect(String, Int32, Boolean) method call. The events used in this sample occur in the following order:
  1. HostResolved
  2. SocketCreating
  3. SocketConnected
  4. LowLevelDataReceived
  5. DataReceived
  6. Connected

Once Connect(String, Int32, Boolean) method finishes, all event handlers are removed in the code, thus Disconnect method does not generate any events (but it would do if we didn't remove LowLevelDataReceived and DataReceived handlers).

DataSent and LowLevelDataSent events are not used in this sample because Connect(String, Int32, Boolean) method does not send any data to the server. However, it would be different if SSL-encrypted connection was used.

C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;

class Sample
{
    // HostResolved event handler.
    private static void OnHostResolved(object sender, HostResolvedEventArgs e)
    {
        Console.WriteLine("The host name of the server was resolved into IP address.");
    }

    // SocketConnected event handler.
    private static void OnSocketConnected(object sender, SocketConnectedEventArgs e)
    {
        Console.WriteLine("The server accepted the connection.");
    }

    // LowLevelDataReceived event handler.
    private static void OnLowLevelDataReceived(object sender, DataTransferEventArgs e)
    {
        // Since SSL connection is not used, OnDataReceived and OnLowLevelDataReceived
        // routines will produce the same output. This sample handles both events just
        // to demonstrate that LowLevelDataReceived event is raised before the
        // corresponding DataReceived event.
        // But in SSL case, DataReceived and LowLevelDataReceived event data would be
        // completely different, and some LowLevelDataReceived events (such as ones
        // occurred during the SSL handshake) would not be followed by DataReceived
        // events at all, because the data sent or received during the SSL handshake
        // does not relate to POP3 protocol and cannot be decoded into textual form.
        Console.WriteLine("Low level data received: [" +
            System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("Data received: [" +
            System.Text.Encoding.Default.GetString(e.Data) + "]");
    }

    // Connected event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Successfully connected to the server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to the events.
        pop.HostResolved += new HostResolvedEventHandler(OnHostResolved);
        pop.SocketConnected += new SocketConnectedEventHandler(OnSocketConnected);
        pop.LowLevelDataReceived += new DataTransferEventHandler(OnLowLevelDataReceived);
        pop.DataReceived += new DataTransferEventHandler(OnDataReceived);
        pop.Connected += new ConnectedEventHandler(OnConnected);

        // Connect to the server and make the events get raised.
        pop.Connect("mail.domain.com");

        // Unsubscribe from the events.
        pop.HostResolved -= new HostResolvedEventHandler(OnHostResolved);
        pop.SocketConnected -= new SocketConnectedEventHandler(OnSocketConnected);
        pop.LowLevelDataReceived -= new DataTransferEventHandler(OnLowLevelDataReceived);
        pop.DataReceived -= new DataTransferEventHandler(OnDataReceived);
        pop.Connected -= new ConnectedEventHandler(OnConnected);

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail

Class Sample
    ' HostResolved event handler.
    Private Shared Sub OnHostResolved(ByVal sender As Object, ByVal e As HostResolvedEventArgs)
        Console.WriteLine("The host name of the server was resolved into IP address.")
    End Sub

    Private Shared Sub OnSocketConnected(ByVal sender As Object, ByVal e As SocketConnectedEventArgs)
        ' SocketConnected event handler.
        Console.WriteLine("The server accepted the connection.")
    End Sub

    ' LowLevelDataReceived event handler.
    Private Shared Sub OnLowLevelDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Since SSL connection is not used, OnDataReceived and OnLowLevelDataReceived
        ' routines will produce the same output. This sample handles both events just
        ' to demonstrate that LowLevelDataReceived event is raised before the
        ' corresponding DataReceived event.
        ' But in SSL case, DataReceived and LowLevelDataReceived event data would be
        ' completely different, and some LowLevelDataReceived events (such as ones
        ' occurred during the SSL handshake) would not be followed by DataReceived
        ' events at all, because the data sent or received during the SSL handshake
        ' does not relate to POP3 protocol and cannot be decoded into textual form.
        Console.WriteLine("Low level data received: [" & _
            System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    ' DataReceived event handler.
    Private Shared Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("Data received: [" & _
            System.Text.Encoding.Default.GetString(e.Data) & "]")
    End Sub

    Private Shared Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Successfully connected to the server.")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to the LowLevelDataSent event.
        AddHandler pop.HostResolved, AddressOf OnHostResolved
        AddHandler pop.SocketConnected, AddressOf OnSocketConnected
        AddHandler pop.LowLevelDataReceived, AddressOf OnLowLevelDataReceived
        AddHandler pop.DataReceived, AddressOf OnDataReceived
        AddHandler pop.Connected, AddressOf OnConnected

        ' Connect to the server and make the events get raised.
        pop.Connect("mail.domain.com")

        ' Unsubscribe from the events.
        RemoveHandler pop.HostResolved, AddressOf OnHostResolved
        RemoveHandler pop.SocketConnected, AddressOf OnSocketConnected
        RemoveHandler pop.LowLevelDataReceived, AddressOf OnLowLevelDataReceived
        RemoveHandler pop.DataReceived, AddressOf OnDataReceived
        RemoveHandler pop.Connected, AddressOf OnConnected

        pop.Disconnect()
    End Sub
 End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Connected


Pop3.SocketCreating Event

Pop3SocketCreating Event
Occurs when MailBee needs a new socket object for establishing a connection with the POP3 server.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SocketCreatingEventHandler SocketCreating
Public Event SocketCreating As SocketCreatingEventHandler

Value

Type: MailBeeSocketCreatingEventHandler
Remarks
This event is raised just before MailBee will start making the connection (i.e. before SocketConnected event). This lets you specify your own socket object in case if you need some special socket settings. If you need this, set NewSocket property to the socket object needed in your event handler.
Note Note
It's possible that this event will fire multiple times in case if the host has multple endpoints assigned. For instance, if the first endpoint was IPv6, the connection could not be made but second endpoint (IPv4) would succeed. On each call of this event handler, your code must supply a new, fresh socket object (otherwise MailBee will create its own). By default, however, MailBee tries IPv4 addresses first (see PreferIPv4Hosts) so this situation is unlikely to happen.
Examples
Imap.SocketCreating topic contains similar code snippet which shows the idea how to use this event.
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3Connected


Pop3.TlsStarted Event

Pop3TlsStarted Event
Occurs when the connection with the server becomes secure.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event TlsStartedEventHandler TlsStarted
Public Event TlsStarted As TlsStartedEventHandler

Value

Type: MailBeeTlsStartedEventHandler
Remarks
This event is raised when TLS/SSL negotiation completes and TLS session successfully starts. Usually, this happens as a result of successful completion of StartTls method or if automatic TLS/SSL negotiation was requested via setting SslMode property to non-Manual value.
Examples
This console sample demonstrates that TlsStarted event is raised during executing Login(String, String, String, String, AuthenticationMethods, AuthenticationOptions, SaslMethod) method when SslMode property is set to UseStartTls value.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Security;

class Sample
{
    // TlsStarted event handler.
    private static void OnTlsStarted(object sender, TlsStartedEventArgs e)
    {
        // This will happen during Login method execution.
        Console.WriteLine("TLS/SSL session started.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Subscribe to TlsStarted event.
        pop.TlsStarted += new TlsStartedEventHandler(OnTlsStarted);

        // Notify MailBee it should start TLS/SSL session when appropriate.
        // The connection is made to the regular port so that STLS command
        // will be used to start TLS/SSL session.
        pop.SslMode = SslStartupMode.UseStartTls;

        pop.Connect("mail.domain.com");

        Console.WriteLine("Connected to the server. Will login now...");

        // TLS/SSL negotiation will take place here. Thus, user credentials
        // will be sent to the mail server already under secure TLS/SSL layer.
        pop.Login("jdoe@domain.com", "secret");

        Console.WriteLine("Logged in successfully.");

        pop.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Security

Public Class Sample
    ' TlsStarted event handler.
    Private Shared Sub OnTlsStarted(ByVal sender As Object, ByVal e As TlsStartedEventArgs)
        ' This will happen during Login method execution.
        Console.WriteLine("TLS/SSL session started.")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim pop As New Pop3

        ' Subscribe to TlsStarted event.
        AddHandler pop.TlsStarted, AddressOf OnTlsStarted

        ' Notify MailBee it should start TLS/SSL session when appropriate.
        ' The connection is made to the regular port so that STLS command
        ' will be used to start TLS/SSL session.
        pop.SslMode = SslStartupMode.UseStartTls

        pop.Connect("mail.domain.com")

        Console.WriteLine("Connected to the server. Will login now...")

        ' TLS/SSL negotiation will take place here. Thus, user credentials
        ' will be sent to the mail server already under secure TLS/SSL layer.
        pop.Login("jdoe@domain.com", "secret")

        Console.WriteLine("Logged in successfully.")

        pop.Disconnect()
    End Sub
End Class
See Also

Reference

Pop3 Class
MailBee.Pop3Mail Namespace
Pop3SslMode
Pop3StartTls


Pop3InboxPreloadOptions Enumeration

Pop3InboxPreloadOptions Enumeration
Specifies which elements of the mailbox statistics to download immediately after successful logging in the mailbox.

Namespace: MailBee.Pop3Mail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum Pop3InboxPreloadOptions
<FlagsAttribute>
Public Enumeration Pop3InboxPreloadOptions
Members
Member name | Value | Description
None | 0 | Do not preload any elements of mailbox statistics (lengths and Unique-ID's of messages).
List | 1 | After successful login, send LIST POP3 command and download the list of lengths of all messages in the mailbox.
Uidl | 2 | After successful login, send UIDL POP3 command and download the list of Unique-ID's of all messages in the mailbox.
Remarks

Normally (when None is used), MailBee automatically downloads mailbox statistics when required. For instance, if the application never calls any methods which operate with Unique-ID values (the methods like GetMessageUidFromIndex(Int32), UIDL POP3 command will never be issued. If, however, GetMessageUidFromIndex(Int32) gets called, MailBee will detect UIDL has not been issued yet, and then send this command to the server. If the developer does not want to rely on automatic download of mailbox statistics, the options provided by this enumeration can be used.

However, if you deal with large multi-megabyte e-mails, it's strongly recommended to set List flag in InboxPreloadOptions value prior to logging into a mailbox. This way MailBee will know the size of each e-mail before downloading and allocate the buffer of the required size at once. This will eliminate step-by-step memory reallocations during downloading a large e-mail.

See Also

Reference

MailBee.Pop3Mail Namespace
Pop3InboxPreloadOptions


MailBee.Proxy Namespace

MailBee.Proxy Namespace
MailBee.Proxy namespace contains types which enable Smtp, Pop3, and Imap components to make connections via a proxy server. SOCKS4, SOCKS5, and HTTP proxies are supported.
Classes
 | Class | Description
Public class | MailBeeProxyAuthenticationException | The exception that is thrown when the proxy server rejects authentication data sent the client or does not support any of the authentication methods supported by the client.
Public class | MailBeeProxyAuthorizationException | The exception that is thrown when the proxy server rejects the proxy connection request from the client.
Public class | MailBeeProxyException | An abstract parent for all exceptions that are thrown when the proxy server returns negative reply during negotiating with the client.
Public class | ProxyServer | Contains properties which define the proxy server settings.
Enumerations
 | Enumeration | Description
Public enumeration | ProxyProtocol | Defines the available modes of establishing connection with a mail server via a proxy server.


MailBeeProxyAuthenticationException Class

MailBeeProxyAuthenticationException Class
The exception that is thrown when the proxy server rejects authentication data sent the client or does not support any of the authentication methods supported by the client.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBee.ProxyMailBeeProxyException
MailBee.ProxyMailBeeProxyAuthenticationException

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeProxyAuthenticationException : MailBeeProxyException
<SerializableAttribute>
Public Class MailBeeProxyAuthenticationException
    Inherits MailBeeProxyException

The MailBeeProxyAuthenticationException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeProxyAuthenticationException | Initializes a new instance of the MailBeeProxyAuthenticationException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Proxy Namespace


MailBeeProxyAuthenticationException Constructor

MailBeeProxyAuthenticationException Constructor
Initializes a new instance of the MailBeeProxyAuthenticationException class

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeProxyAuthenticationException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeProxyAuthenticationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthenticationException Methods

MailBeeProxyAuthenticationException Methods

The MailBeeProxyAuthenticationException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProxyAuthenticationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthenticationException Properties

MailBeeProxyAuthenticationException Properties

The MailBeeProxyAuthenticationException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeProxyAuthenticationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthenticationException Events

MailBeeProxyAuthenticationException Events

The MailBeeProxyAuthenticationException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProxyAuthenticationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthorizationException Class

MailBeeProxyAuthorizationException Class
The exception that is thrown when the proxy server rejects the proxy connection request from the client.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBee.ProxyMailBeeProxyException
MailBee.ProxyMailBeeProxyAuthorizationException

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeProxyAuthorizationException : MailBeeProxyException
<SerializableAttribute>
Public Class MailBeeProxyAuthorizationException
    Inherits MailBeeProxyException

The MailBeeProxyAuthorizationException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeProxyAuthorizationException | Initializes a new instance of the MailBeeProxyAuthorizationException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Proxy Namespace


MailBeeProxyAuthorizationException Constructor

MailBeeProxyAuthorizationException Constructor
Initializes a new instance of the MailBeeProxyAuthorizationException class

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeProxyAuthorizationException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeProxyAuthorizationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthorizationException Methods

MailBeeProxyAuthorizationException Methods

The MailBeeProxyAuthorizationException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProxyAuthorizationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthorizationException Properties

MailBeeProxyAuthorizationException Properties

The MailBeeProxyAuthorizationException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeProxyAuthorizationException Class
MailBee.Proxy Namespace


MailBeeProxyAuthorizationException Events

MailBeeProxyAuthorizationException Events

The MailBeeProxyAuthorizationException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProxyAuthorizationException Class
MailBee.Proxy Namespace


MailBeeProxyException Class

MailBeeProxyException Class
An abstract parent for all exceptions that are thrown when the proxy server returns negative reply during negotiating with the client.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeConnectionException
MailBee.ProxyMailBeeProxyException
MailBee.ProxyMailBeeProxyAuthenticationException
MailBee.ProxyMailBeeProxyAuthorizationException

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeProxyException : MailBeeConnectionException
Public MustInherit Class MailBeeProxyException
    Inherits MailBeeConnectionException

The MailBeeProxyException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeProxyException | Initializes a new instance of the MailBeeProxyException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Proxy Namespace


MailBeeProxyException Constructor

MailBeeProxyException Constructor
Initializes a new instance of the MailBeeProxyException class

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeProxyException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeProxyException Class
MailBee.Proxy Namespace


MailBeeProxyException Methods

MailBeeProxyException Methods

The MailBeeProxyException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProxyException Class
MailBee.Proxy Namespace


MailBeeProxyException Properties

MailBeeProxyException Properties

The MailBeeProxyException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeProxyException Class
MailBee.Proxy Namespace


MailBeeProxyException Events

MailBeeProxyException Events

The MailBeeProxyException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeProxyException Class
MailBee.Proxy Namespace


ProxyProtocol Enumeration

ProxyProtocol Enumeration
Defines the available modes of establishing connection with a mail server via a proxy server.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum ProxyProtocol
Public Enumeration ProxyProtocol
Members
Member name | Value | Description
NoProxy | 0 | Do not use a proxy server and connect directly to a mail server.
Socks4 | 1 | Connect through a SOCK4 proxy server.
Socks5 | 2 | Connect through a SOCK5 proxy server.
Http | 3 | Connect through an HTTP proxy server.
See Also

Reference

MailBee.Proxy Namespace


ProxyServer Class

ProxyServer Class
Contains properties which define the proxy server settings.
Inheritance Hierarchy
SystemObject
MailBee.ProxyProxyServer

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ProxyServer
Public Class ProxyServer

The ProxyServer type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AccountName | Gets or sets the user account name on the proxy server.
Public property | Name | Gets or sets the IP address or the domain name of the proxy server.
Public property | Password | Gets or sets the user account password on the proxy server.
Public property | Port | Gets or sets the port number on which to communicate with the proxy server.
Public property | Protocol | Gets or sets which proxy protocol (if any) should be used when connecting to a mail server.
Public property | StringEncoding | Gets or sets the encoding used to convert strings sent to the proxy server to bytes.
Top
Remarks
The following properties of MailBee classes have ProxyServer type: Pop3.Proxy, Imap.Proxy, SmtpServer.Proxy.
See Also

Reference

MailBee.Proxy Namespace


ProxyServer Methods

ProxyServer Methods

The ProxyServer type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer Properties

ProxyServer Properties

The ProxyServer type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets or sets the user account name on the proxy server.
Public property | Name | Gets or sets the IP address or the domain name of the proxy server.
Public property | Password | Gets or sets the user account password on the proxy server.
Public property | Port | Gets or sets the port number on which to communicate with the proxy server.
Public property | Protocol | Gets or sets which proxy protocol (if any) should be used when connecting to a mail server.
Public property | StringEncoding | Gets or sets the encoding used to convert strings sent to the proxy server to bytes.
Top
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer.AccountName Property

ProxyServerAccountName Property
Gets or sets the user account name on the proxy server.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; set; }
Public Property AccountName As String
    Get
    Set

Property Value

Type: String
The user account name on the proxy server. The default value is an empty string.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
Usually, SOCKS5 and HTTP proxies require authentication (and thus AccountName and Password properties set) while SOCKS4 proxies do not use authentication.
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer.Name Property

ProxyServerName Property
Gets or sets the IP address or the domain name of the proxy server.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; set; }
Public Property Name As String
    Get
    Set

Property Value

Type: String
The IP address string or the domain name of the proxy server. The default value is an empty string.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer.Password Property

ProxyServerPassword Property
Gets or sets the user account password on the proxy server.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; set; }
Public Property Password As String
    Get
    Set

Property Value

Type: String
The user account password on the proxy server. The default value is an empty string.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
Usually, SOCKS5 and HTTP proxies require authentication (and thus AccountName and Password properties set) while SOCKS4 proxies do not use authentication.
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer.Port Property

ProxyServerPort Property
Gets or sets the port number on which to communicate with the proxy server.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Port { get; set; }
Public Property Port As Integer
    Get
    Set

Property Value

Type: Int32
The port number on which to communicate with the proxy server. The default value is 1080.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is an invalid port number.
Remarks
Usually, the default value of 1080 is ok for SOCKS4 and SOCKS5 proxy servers. HTTP proxy, however, usually operates on port 808.
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer.Protocol Property

ProxyServerProtocol Property
Gets or sets which proxy protocol (if any) should be used when connecting to a mail server.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ProxyProtocol Protocol { get; set; }
Public Property Protocol As ProxyProtocol
    Get
    Set

Property Value

Type: ProxyProtocol
One of ProxyProtocol values specifying which proxy protocol to use when establishing connection with a mail server via a proxy server. The default value is NoProxy which means the proxy server won't be used at all and the connection will be made directly with a mail server.
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


ProxyServer.StringEncoding Property

ProxyServerStringEncoding Property
Gets or sets the encoding used to convert strings sent to the proxy server to bytes.

Namespace: MailBee.Proxy
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding StringEncoding { get; set; }
Public Property StringEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert strings sent to the proxy server to bytes. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
Setting this property may only be required if you have non-ASCII characters in the proxy username or password.
See Also

Reference

ProxyServer Class
MailBee.Proxy Namespace


MailBee.Security Namespace

MailBee.Security Namespace

MailBee.Security namespace contains additional types specific to TLS/SSL functionality, S/MIME support, certificates and certificate stores, DomainKeys/DKIM anti-spam technology.

The option to connect to SSL/TSL enabled mail server is available at no additional cost. The same applies to DomainKeys/DKIM - it's considered as a basic feature. You can sign e-mails with DomainKeys/DKIM signatures and verify DomainKeys/DKIM signatures of existing e-mails (this is a popular antispam check, many mail services nowdays accept only DomainKeys-signed e-mails).

With the help of advanced features (Security.Powerup license required), the developer can:

  • Work with certificates and their Windows registry and file stores
  • Examine or validate server certificates and specify client certificates within TLS/SSL connections
  • Encrypt, decrypt, verify, and sign e-mail messages
  • Let the current thread programmatically impersonate another user (useful if the application needs to access resources, such as certificate stores, which belong to another user)

Classes
 | Class | Description
 | Algorithm | Represents a cryptographic algorithm used for signing and encryption operations.
 | Certificate | Provides methods and properties for accessing a digital certificate.
 | CertificateCollection | Provides methods and properties for accessing collections of Certificate objects.
 | CertificateStore | Provides the methods and properties for accessing certificate stores.
 | ClientServerCertificates | Provides methods and properties for accessing client and server certificates which are used in order to establish secure SSL connection with a mail server.
 | CryptoServiceProvider | Provides methods and properties for accessing or examining Cryptographic Service Providers (CSPs) registered in the system.
 | DomainKeys | Provides methods for signing e-mails with DomainKeys and DKIM signatures and verifying signatures of incoming e-mails.
 | Impersonation | Provides access to the impersonation functions.
Public class | MailBeeCertificateException | An abstract parent for all exceptions that are thrown on errors which occur during accessing certificates.
Public class | MailBeeCertificateParsingException | The exception which is thrown when it's not possible to parse the certificate data or when the certificate password is incorrect.
Public class | MailBeeCertificateStoreException | An abstract parent for all exceptions that are thrown on errors which occur during accessing certificate stores.
Public class | MailBeeCertificateStoreWin32Exception | The exception which is thrown when the underlying WinAPI function related to certificate store management returns an error.
 | MailBeeCertificateValidationException | The exception which is thrown during TLS/SSL handshake when automatic certificate validation is enabled and the server certificate does not pass the specified validation conditions.
Public class | MailBeeCertificateWin32Exception | The exception which is thrown when the underlying WinAPI function related to certificate management returns an error.
Public class | MailBeeCryptoProviderException | An abstract parent for all exceptions that are thrown on errors which occur during obtaining or examining Cryptographic Service Provider (CSP) system objects.
Public class | MailBeeCryptoProviderWin32Exception | The exception which is thrown when the underlying CSP-related WinAPI function returns an error.
Public class | MailBeeDomainKeysException | The exception that is thrown when DomainKeys operation (signing or verification) cannot be performed.
Public class | MailBeeImpersonationException | An abstract parent for all exceptions that are thrown on errors which occur during starting or termniating the impersonation.
Public class | MailBeeImpersonationWin32Exception | The exception which is thrown when the underlying WinAPI function related to impersonation returns an error.
Public class | MailBeeSmimeException | An abstract parent for all exceptions that are thrown on errors which occur during performing S/MIME operations.
Public class | MailBeeSmimeWin32Exception | The exception which is thrown when the underlying S/MIME WinAPI function responsible for decrypting, encrypting or signing data returns an error.
Public class | MailBeeSslException | An abstract parent for all exceptions that are thrown on TLS/SSL negotiation, decryption and encryption errors.
Public class | MailBeeSslNegotiationException | The exception that is thrown when the underlying SslStream throws an exception during SSL negotiation.
Public class | MailBeeSslWin32Exception | The exception that is thrown when underlying Win32 Schannel implementation of TLS/SSL functions returns an error.
Public class | Powerup | Explains which features of MailBee.Security namespace require Security license.
 | Smime | Provides properties and methods for encrypting, decrypting, signing and verifying e-mail messages.
 | SmimeResult | Provides access to the decrypted message, signature verification status and other values returned by the methods of Smime class.
Enumerations
 | Enumeration | Description
Public enumeration | AlgorithmCategory | Defines purposes of cryptographic algorithms.
Public enumeration | CertFileType | Defines types of certificate files and data.
Public enumeration | CertificateFields | Defines certificate fields available for search with FindCertificates(String, CertificateFields) method.
Public enumeration | CertificateValidationFlags | Defines flags indicating errors of certificate validation.
Public enumeration | CertStoreFileType | Defines types of certificate store files.
Public enumeration | CertStoreType | Defines certificate store types.
Public enumeration | DomainKeysTypes | Defines the supported types of DomainKeys technology (classic DK and DKIM).
Public enumeration | DomainKeysVerifyResult | Defines the return values of Verify(MailMessage, Smtp) method.
Public enumeration | MessageVerificationFlags | Defines criteria of verification of e-mail message signatures.
Public enumeration | RegistryStoreLocation | Defines branches of the Windows registry where the system certificate stores can reside.
Public enumeration | SecurityProtocol | Specifies the protocols to be used for performing TLS/SSL negotiation and data encryption.
Public enumeration | SslStartupMode | Specifies in which way the mailer component should switch the connection into TLS/SSL mode.


MailBeeCertificateException Class

MailBeeCertificateException Class
An abstract parent for all exceptions that are thrown on errors which occur during accessing certificates.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCertificateException
MailBee.SecurityMailBeeCertificateParsingException
MailBee.SecurityMailBeeCertificateValidationException
MailBee.SecurityMailBeeCertificateWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class MailBeeCertificateException : MailBeeLocalException
Public Class MailBeeCertificateException
    Inherits MailBeeLocalException

The MailBeeCertificateException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCertificateException | Initializes a new instance of the MailBeeCertificateException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Security Namespace


MailBeeCertificateException Constructor

MailBeeCertificateException Constructor
Initializes a new instance of the MailBeeCertificateException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCertificateException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCertificateException Class
MailBee.Security Namespace


MailBeeCertificateException Methods

MailBeeCertificateException Methods

The MailBeeCertificateException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateException Class
MailBee.Security Namespace


MailBeeCertificateException Properties

MailBeeCertificateException Properties

The MailBeeCertificateException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateException Class
MailBee.Security Namespace


MailBeeCertificateException Events

MailBeeCertificateException Events

The MailBeeCertificateException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateException Class
MailBee.Security Namespace


MailBeeCertificateParsingException Class

MailBeeCertificateParsingException Class
The exception which is thrown when it's not possible to parse the certificate data or when the certificate password is incorrect.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCertificateException
MailBee.SecurityMailBeeCertificateParsingException

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeCertificateParsingException : MailBeeCertificateException
<SerializableAttribute>
Public Class MailBeeCertificateParsingException
    Inherits MailBeeCertificateException

The MailBeeCertificateParsingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCertificateParsingException | Initializes a new instance of the MailBeeCertificateParsingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This exception is typically thrown on attempt to create Certificate object from invalid data. For instance, this may occur on attempt to open a certificate as Pfx while it's actually P7b. Another case is invalid .PFX password.
See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificate


MailBeeCertificateParsingException Constructor

MailBeeCertificateParsingException Constructor
Initializes a new instance of the MailBeeCertificateParsingException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCertificateParsingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCertificateParsingException Class
MailBee.Security Namespace


MailBeeCertificateParsingException Methods

MailBeeCertificateParsingException Methods

The MailBeeCertificateParsingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateParsingException Class
MailBee.Security Namespace


MailBeeCertificateParsingException Properties

MailBeeCertificateParsingException Properties

The MailBeeCertificateParsingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateParsingException Class
MailBee.Security Namespace


MailBeeCertificateParsingException Events

MailBeeCertificateParsingException Events

The MailBeeCertificateParsingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateParsingException Class
MailBee.Security Namespace


MailBeeCertificateStoreException Class

MailBeeCertificateStoreException Class
An abstract parent for all exceptions that are thrown on errors which occur during accessing certificate stores.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCertificateStoreException
MailBee.SecurityMailBeeCertificateStoreWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeCertificateStoreException : MailBeeLocalException
Public MustInherit Class MailBeeCertificateStoreException
    Inherits MailBeeLocalException

The MailBeeCertificateStoreException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCertificateStoreException | Initializes a new instance of the MailBeeCertificateStoreException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Security Namespace


MailBeeCertificateStoreException Constructor

MailBeeCertificateStoreException Constructor
Initializes a new instance of the MailBeeCertificateStoreException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCertificateStoreException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCertificateStoreException Class
MailBee.Security Namespace


MailBeeCertificateStoreException Methods

MailBeeCertificateStoreException Methods

The MailBeeCertificateStoreException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateStoreException Class
MailBee.Security Namespace


MailBeeCertificateStoreException Properties

MailBeeCertificateStoreException Properties

The MailBeeCertificateStoreException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateStoreException Class
MailBee.Security Namespace


MailBeeCertificateStoreException Events

MailBeeCertificateStoreException Events

The MailBeeCertificateStoreException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateStoreException Class
MailBee.Security Namespace


MailBeeCertificateStoreWin32Exception Class

MailBeeCertificateStoreWin32Exception Class
The exception which is thrown when the underlying WinAPI function related to certificate store management returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCertificateStoreException
MailBee.SecurityMailBeeCertificateStoreWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeCertificateStoreWin32Exception : MailBeeCertificateStoreException,
    IMailBeeWin32Exception
<SerializableAttribute>
Public Class MailBeeCertificateStoreWin32Exception
    Inherits MailBeeCertificateStoreException
    Implements IMailBeeWin32Exception

The MailBeeCertificateStoreWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCertificateStoreWin32Exception | Initializes a new instance of the MailBeeCertificateStoreWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is typically thrown when the underlying CryptoAPI functions cannot open the certificate store accordingly the specified parameters.

The developer can obtain Win32 code of the occurred error from NativeErrorCode property.

See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificateStore


MailBeeCertificateStoreWin32Exception Constructor

MailBeeCertificateStoreWin32Exception Constructor
Initializes a new instance of the MailBeeCertificateStoreWin32Exception class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCertificateStoreWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCertificateStoreWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateStoreWin32Exception Methods

MailBeeCertificateStoreWin32Exception Methods

The MailBeeCertificateStoreWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateStoreWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateStoreWin32Exception Properties

MailBeeCertificateStoreWin32Exception Properties

The MailBeeCertificateStoreWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateStoreWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateStoreWin32Exception.NativeErrorCode Property

MailBeeCertificateStoreWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by the WinAPI function.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by the WinAPI function related to certificate store management.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeCertificateStoreWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateStoreWin32Exception Events

MailBeeCertificateStoreWin32Exception Events

The MailBeeCertificateStoreWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateStoreWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateValidationException Class

MailBeeCertificateValidationException Class
The exception which is thrown during TLS/SSL handshake when automatic certificate validation is enabled and the server certificate does not pass the specified validation conditions.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCertificateException
MailBee.SecurityMailBeeCertificateValidationException

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeCertificateValidationException : MailBeeCertificateException
<SerializableAttribute>
Public Class MailBeeCertificateValidationException
    Inherits MailBeeCertificateException

The MailBeeCertificateValidationException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCertificateValidationException | Initializes a new instance of the MailBeeCertificateValidationException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
 | Status | A set of flags which indicate the validation conditions which have not been met during validation of the server certificate.
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
To determine the exact conditions which failed to be met during validation, use Status property.
Examples
The example is available in ClientServerCertificates topic.
See Also

Reference

MailBee.Security Namespace
ClientServerCertificatesAutoValidation


MailBeeCertificateValidationException Constructor

MailBeeCertificateValidationException Constructor
Initializes a new instance of the MailBeeCertificateValidationException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCertificateValidationException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCertificateValidationException Class
MailBee.Security Namespace


MailBeeCertificateValidationException Methods

MailBeeCertificateValidationException Methods

The MailBeeCertificateValidationException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateValidationException Class
MailBee.Security Namespace


MailBeeCertificateValidationException Properties

MailBeeCertificateValidationException Properties

The MailBeeCertificateValidationException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
 | Status | A set of flags which indicate the validation conditions which have not been met during validation of the server certificate.
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateValidationException Class
MailBee.Security Namespace


MailBeeCertificateValidationException.Status Property

MailBeeCertificateValidationExceptionStatus Property
A set of flags which indicate the validation conditions which have not been met during validation of the server certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateValidationFlags Status { get; }
Public ReadOnly Property Status As CertificateValidationFlags
    Get

Property Value

Type: CertificateValidationFlags
A bitwise combination of CertificateValidationFlags which indicate the problems with the server certificate.
Remarks
This value lists all CertificateValidationFlags the validation has failed for, regardless if AutoValidation property value listed them or not. For instance, if AutoValidation value was IsNotTimeValid and the validation process found that all the certificate fields are invalid (not just its datetime), Status property will return All, not just IsNotTimeValid. Thus, AutoValidation only controls whether the exception should be thrown if certain validation conditions are not met but it does not affect the returned value of Status property.
Examples
The example is available in ClientServerCertificates topic.
See Also

Reference

MailBeeCertificateValidationException Class
MailBee.Security Namespace


MailBeeCertificateValidationException Events

MailBeeCertificateValidationException Events

The MailBeeCertificateValidationException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateValidationException Class
MailBee.Security Namespace


MailBeeCertificateWin32Exception Class

MailBeeCertificateWin32Exception Class
The exception which is thrown when the underlying WinAPI function related to certificate management returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCertificateException
MailBee.SecurityMailBeeCertificateWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeCertificateWin32Exception : MailBeeCertificateException,
    IMailBeeWin32Exception
<SerializableAttribute>
Public Class MailBeeCertificateWin32Exception
    Inherits MailBeeCertificateException
    Implements IMailBeeWin32Exception

The MailBeeCertificateWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCertificateWin32Exception | Initializes a new instance of the MailBeeCertificateWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is typically thrown when the underlying CryptoAPI functions cannot open the certificate accordingly the specified parameters.

The developer can obtain Win32 code of the occurred error from NativeErrorCode property.

See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificate


MailBeeCertificateWin32Exception Constructor

MailBeeCertificateWin32Exception Constructor
Initializes a new instance of the MailBeeCertificateWin32Exception class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCertificateWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCertificateWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateWin32Exception Methods

MailBeeCertificateWin32Exception Methods

The MailBeeCertificateWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateWin32Exception Properties

MailBeeCertificateWin32Exception Properties

The MailBeeCertificateWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateWin32Exception.NativeErrorCode Property

MailBeeCertificateWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by the WinAPI function.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by the WinAPI function related to certificate management.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeCertificateWin32Exception Class
MailBee.Security Namespace


MailBeeCertificateWin32Exception Events

MailBeeCertificateWin32Exception Events

The MailBeeCertificateWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCertificateWin32Exception Class
MailBee.Security Namespace


MailBeeCryptoProviderException Class

MailBeeCryptoProviderException Class
An abstract parent for all exceptions that are thrown on errors which occur during obtaining or examining Cryptographic Service Provider (CSP) system objects.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCryptoProviderException
MailBee.SecurityMailBeeCryptoProviderWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeCryptoProviderException : MailBeeLocalException
Public MustInherit Class MailBeeCryptoProviderException
    Inherits MailBeeLocalException

The MailBeeCryptoProviderException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCryptoProviderException | Initializes a new instance of the MailBeeCryptoProviderException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Security Namespace


MailBeeCryptoProviderException Constructor

MailBeeCryptoProviderException Constructor
Initializes a new instance of the MailBeeCryptoProviderException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCryptoProviderException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCryptoProviderException Class
MailBee.Security Namespace


MailBeeCryptoProviderException Methods

MailBeeCryptoProviderException Methods

The MailBeeCryptoProviderException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCryptoProviderException Class
MailBee.Security Namespace


MailBeeCryptoProviderException Properties

MailBeeCryptoProviderException Properties

The MailBeeCryptoProviderException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCryptoProviderException Class
MailBee.Security Namespace


MailBeeCryptoProviderException Events

MailBeeCryptoProviderException Events

The MailBeeCryptoProviderException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCryptoProviderException Class
MailBee.Security Namespace


MailBeeCryptoProviderWin32Exception Class

MailBeeCryptoProviderWin32Exception Class
The exception which is thrown when the underlying CSP-related WinAPI function returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeCryptoProviderException
MailBee.SecurityMailBeeCryptoProviderWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeCryptoProviderWin32Exception : MailBeeCryptoProviderException,
    IMailBeeWin32Exception
<SerializableAttribute>
Public Class MailBeeCryptoProviderWin32Exception
    Inherits MailBeeCryptoProviderException
    Implements IMailBeeWin32Exception

The MailBeeCryptoProviderWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeCryptoProviderWin32Exception | Initializes a new instance of the MailBeeCryptoProviderWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by CSP-related WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is typically thrown when the name of the Cryptographic Service Provider (CSP) is specified incorrectly during creating an instance of CryptoServiceProvider class.

The developer can obtain Win32 code of the occurred error from NativeErrorCode property.

See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCryptoServiceProvider


MailBeeCryptoProviderWin32Exception Constructor

MailBeeCryptoProviderWin32Exception Constructor
Initializes a new instance of the MailBeeCryptoProviderWin32Exception class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeCryptoProviderWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeCryptoProviderWin32Exception Class
MailBee.Security Namespace


MailBeeCryptoProviderWin32Exception Methods

MailBeeCryptoProviderWin32Exception Methods

The MailBeeCryptoProviderWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCryptoProviderWin32Exception Class
MailBee.Security Namespace


MailBeeCryptoProviderWin32Exception Properties

MailBeeCryptoProviderWin32Exception Properties

The MailBeeCryptoProviderWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by CSP-related WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCryptoProviderWin32Exception Class
MailBee.Security Namespace


MailBeeCryptoProviderWin32Exception.NativeErrorCode Property

MailBeeCryptoProviderWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by CSP-related WinAPI function.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by CSP-related WinAPI function.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeCryptoProviderWin32Exception Class
MailBee.Security Namespace


MailBeeCryptoProviderWin32Exception Events

MailBeeCryptoProviderWin32Exception Events

The MailBeeCryptoProviderWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeCryptoProviderWin32Exception Class
MailBee.Security Namespace


MailBeeDomainKeysException Class

MailBeeDomainKeysException Class
The exception that is thrown when DomainKeys operation (signing or verification) cannot be performed.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeDomainKeysException

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDomainKeysException : MailBeeLocalException
<SerializableAttribute>
Public Class MailBeeDomainKeysException
    Inherits MailBeeLocalException

The MailBeeDomainKeysException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDomainKeysException | Initializes a new instance of the MailBeeDomainKeysException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Security Namespace


MailBeeDomainKeysException Constructor

MailBeeDomainKeysException Constructor
Initializes a new instance of the MailBeeDomainKeysException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDomainKeysException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDomainKeysException Class
MailBee.Security Namespace


MailBeeDomainKeysException Methods

MailBeeDomainKeysException Methods

The MailBeeDomainKeysException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDomainKeysException Class
MailBee.Security Namespace


MailBeeDomainKeysException Properties

MailBeeDomainKeysException Properties

The MailBeeDomainKeysException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDomainKeysException Class
MailBee.Security Namespace


MailBeeDomainKeysException Events

MailBeeDomainKeysException Events

The MailBeeDomainKeysException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDomainKeysException Class
MailBee.Security Namespace


MailBeeImpersonationException Class

MailBeeImpersonationException Class
An abstract parent for all exceptions that are thrown on errors which occur during starting or termniating the impersonation.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeImpersonationException
MailBee.SecurityMailBeeImpersonationWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeImpersonationException : MailBeeLocalException
Public MustInherit Class MailBeeImpersonationException
    Inherits MailBeeLocalException

The MailBeeImpersonationException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImpersonationException | Initializes a new instance of the MailBeeImpersonationException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
The only methods which can throw such exceptions are LogonAs(String, String, String) and Logoff.
See Also

Reference

MailBee.Security Namespace


MailBeeImpersonationException Constructor

MailBeeImpersonationException Constructor
Initializes a new instance of the MailBeeImpersonationException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImpersonationException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImpersonationException Class
MailBee.Security Namespace


MailBeeImpersonationException Methods

MailBeeImpersonationException Methods

The MailBeeImpersonationException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImpersonationException Class
MailBee.Security Namespace


MailBeeImpersonationException Properties

MailBeeImpersonationException Properties

The MailBeeImpersonationException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImpersonationException Class
MailBee.Security Namespace


MailBeeImpersonationException Events

MailBeeImpersonationException Events

The MailBeeImpersonationException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImpersonationException Class
MailBee.Security Namespace


MailBeeImpersonationWin32Exception Class

MailBeeImpersonationWin32Exception Class
The exception which is thrown when the underlying WinAPI function related to impersonation returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeImpersonationException
MailBee.SecurityMailBeeImpersonationWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeImpersonationWin32Exception : MailBeeImpersonationException,
    IMailBeeWin32Exception
<SerializableAttribute>
Public Class MailBeeImpersonationWin32Exception
    Inherits MailBeeImpersonationException
    Implements IMailBeeWin32Exception

The MailBeeImpersonationWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeImpersonationWin32Exception | Initializes a new instance of the MailBeeImpersonationWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This exception can only be thrown by Impersonation class methods.
See Also

Reference

MailBee.Security Namespace
MailBee.SecurityImpersonation


MailBeeImpersonationWin32Exception Constructor

MailBeeImpersonationWin32Exception Constructor
Initializes a new instance of the MailBeeImpersonationWin32Exception class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeImpersonationWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeImpersonationWin32Exception Class
MailBee.Security Namespace


MailBeeImpersonationWin32Exception Methods

MailBeeImpersonationWin32Exception Methods

The MailBeeImpersonationWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImpersonationWin32Exception Class
MailBee.Security Namespace


MailBeeImpersonationWin32Exception Properties

MailBeeImpersonationWin32Exception Properties

The MailBeeImpersonationWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by the WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImpersonationWin32Exception Class
MailBee.Security Namespace


MailBeeImpersonationWin32Exception.NativeErrorCode Property

MailBeeImpersonationWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by the WinAPI function.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by the WinAPI function related to impersonation.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeImpersonationWin32Exception Class
MailBee.Security Namespace


MailBeeImpersonationWin32Exception Events

MailBeeImpersonationWin32Exception Events

The MailBeeImpersonationWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeImpersonationWin32Exception Class
MailBee.Security Namespace


MailBeeSmimeException Class

MailBeeSmimeException Class
An abstract parent for all exceptions that are thrown on errors which occur during performing S/MIME operations.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeSmimeException
MailBee.SecurityMailBeeSmimeWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeSmimeException : MailBeeLocalException
Public MustInherit Class MailBeeSmimeException
    Inherits MailBeeLocalException

Field Value

Type:
S/MIME operations include encypting, decrypting and signing messages. Signature verification, being an S/MIME operation as well, does not produce MailBeeSmimeException, however. Verify(MailMessage, MessageVerificationFlags, CertificateStore) method returns MessageTampered if the signature is invalid but no MailBeeSmimeException is thrown.

The MailBeeSmimeException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmimeException | Initializes a new instance of the MailBeeSmimeException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Security Namespace


MailBeeSmimeException Constructor

MailBeeSmimeException Constructor
Initializes a new instance of the MailBeeSmimeException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmimeException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmimeException Class
MailBee.Security Namespace


MailBeeSmimeException Methods

MailBeeSmimeException Methods

The MailBeeSmimeException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmimeException Class
MailBee.Security Namespace


MailBeeSmimeException Properties

MailBeeSmimeException Properties

The MailBeeSmimeException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmimeException Class
MailBee.Security Namespace


MailBeeSmimeException Events

MailBeeSmimeException Events

The MailBeeSmimeException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmimeException Class
MailBee.Security Namespace


MailBeeSmimeWin32Exception Class

MailBeeSmimeWin32Exception Class
The exception which is thrown when the underlying S/MIME WinAPI function responsible for decrypting, encrypting or signing data returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.SecurityMailBeeSmimeException
MailBee.SecurityMailBeeSmimeWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmimeWin32Exception : MailBeeSmimeException,
    IMailBeeWin32Exception
<SerializableAttribute>
Public Class MailBeeSmimeWin32Exception
    Inherits MailBeeSmimeException
    Implements IMailBeeWin32Exception

The MailBeeSmimeWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmimeWin32Exception | Initializes a new instance of the MailBeeSmimeWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by S/MIME-related WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This exception is typically thrown if there is no certificate with a private key which can be used in order to decrypt an encoded message. Another common case takes place when the message is signed with the certificate which does not have the private key.

The developer can obtain Win32 code of the occurred error from NativeErrorCode property.

See Also

Reference

MailBee.Security Namespace
MailBee.SecuritySmime


MailBeeSmimeWin32Exception Constructor

MailBeeSmimeWin32Exception Constructor
Initializes a new instance of the MailBeeSmimeWin32Exception class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmimeWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmimeWin32Exception Class
MailBee.Security Namespace


MailBeeSmimeWin32Exception Methods

MailBeeSmimeWin32Exception Methods

The MailBeeSmimeWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmimeWin32Exception Class
MailBee.Security Namespace


MailBeeSmimeWin32Exception Properties

MailBeeSmimeWin32Exception Properties

The MailBeeSmimeWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by S/MIME-related WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmimeWin32Exception Class
MailBee.Security Namespace


MailBeeSmimeWin32Exception.NativeErrorCode Property

MailBeeSmimeWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by S/MIME-related WinAPI function.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by the WinAPI function related to S/MIME.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeSmimeWin32Exception Class
MailBee.Security Namespace


MailBeeSmimeWin32Exception Events

MailBeeSmimeWin32Exception Events

The MailBeeSmimeWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmimeWin32Exception Class
MailBee.Security Namespace


MailBeeSslException Class

MailBeeSslException Class
An abstract parent for all exceptions that are thrown on TLS/SSL negotiation, decryption and encryption errors.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBee.SecurityMailBeeSslException
MailBee.SecurityMailBeeSslNegotiationException
MailBee.SecurityMailBeeSslWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeSslException : MailBeeException
Public MustInherit Class MailBeeSslException
    Inherits MailBeeException

The MailBeeSslException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSslException | Initializes a new instance of the MailBeeSslException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Security Namespace


MailBeeSslException Constructor

MailBeeSslException Constructor
Initializes a new instance of the MailBeeSslException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSslException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSslException Class
MailBee.Security Namespace


MailBeeSslException Methods

MailBeeSslException Methods

The MailBeeSslException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslException Class
MailBee.Security Namespace


MailBeeSslException Properties

MailBeeSslException Properties

The MailBeeSslException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslException Class
MailBee.Security Namespace


MailBeeSslException Events

MailBeeSslException Events

The MailBeeSslException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslException Class
MailBee.Security Namespace


MailBeeSslNegotiationException Class

MailBeeSslNegotiationException Class
The exception that is thrown when the underlying SslStream throws an exception during SSL negotiation.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBee.SecurityMailBeeSslException
MailBee.SecurityMailBeeSslNegotiationException

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSslNegotiationException : MailBeeSslException,
    IMailBeeSocketMustCloseException
<SerializableAttribute>
Public Class MailBeeSslNegotiationException
    Inherits MailBeeSslException
    Implements IMailBeeSocketMustCloseException

The MailBeeSslNegotiationException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSslNegotiationException | Initializes a new instance of the MailBeeSslNegotiationException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
Typical reasons of this exception is when the selected SSL protocol is not supported by the client or server. For instance, SSL 2.0 and SSL 3.0 may often be not supported nowadays.
See Also

Reference

MailBee.Security Namespace


MailBeeSslNegotiationException Constructor

MailBeeSslNegotiationException Constructor
Initializes a new instance of the MailBeeSslNegotiationException class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSslNegotiationException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSslNegotiationException Class
MailBee.Security Namespace


MailBeeSslNegotiationException Methods

MailBeeSslNegotiationException Methods

The MailBeeSslNegotiationException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslNegotiationException Class
MailBee.Security Namespace


MailBeeSslNegotiationException Properties

MailBeeSslNegotiationException Properties

The MailBeeSslNegotiationException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslNegotiationException Class
MailBee.Security Namespace


MailBeeSslNegotiationException Events

MailBeeSslNegotiationException Events

The MailBeeSslNegotiationException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslNegotiationException Class
MailBee.Security Namespace


MailBeeSslWin32Exception Class

MailBeeSslWin32Exception Class
The exception that is thrown when underlying Win32 Schannel implementation of TLS/SSL functions returns an error.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBee.SecurityMailBeeSslException
MailBee.SecurityMailBeeSslWin32Exception

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSslWin32Exception : MailBeeSslException,
    IMailBeeWin32Exception, IMailBeeSocketMustCloseException
<SerializableAttribute>
Public Class MailBeeSslWin32Exception
    Inherits MailBeeSslException
    Implements IMailBeeWin32Exception, IMailBeeSocketMustCloseException

The MailBeeSslWin32Exception type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSslWin32Exception | Initializes a new instance of the MailBeeSslWin32Exception class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by SSL-related WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is usually thrown on attempt to connect to a wrong port (for instance, if the client attempts to initiate TLS/SSL secure POP3 connection on port 110 instead of dedicated TLS/SSL port 995).

If the dedicated TLS/SSL port is closed on the mail server, the client should attempt to connect using regular port (such as 110 for POP3) and then switch into TLS/SSL mode via STARTTLS (either using StartTls method of the mail component or specifying UseStartTls as SslMode property value).

Another reason of having this exception thrown is an attempt to establish SSL connection using a client certificate when wrong password for this certificate was specified.

The developer can obtain Win32 code of the occurred error from NativeErrorCode property.

See Also

Reference

MailBee.Security Namespace


MailBeeSslWin32Exception Constructor

MailBeeSslWin32Exception Constructor
Initializes a new instance of the MailBeeSslWin32Exception class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSslWin32Exception(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSslWin32Exception Class
MailBee.Security Namespace


MailBeeSslWin32Exception Methods

MailBeeSslWin32Exception Methods

The MailBeeSslWin32Exception type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslWin32Exception Class
MailBee.Security Namespace


MailBeeSslWin32Exception Properties

MailBeeSslWin32Exception Properties

The MailBeeSslWin32Exception type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | NativeErrorCode | The Win32 error code value returned by SSL-related WinAPI function.
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslWin32Exception Class
MailBee.Security Namespace


MailBeeSslWin32Exception.NativeErrorCode Property

MailBeeSslWin32ExceptionNativeErrorCode Property
The Win32 error code value returned by SSL-related WinAPI function.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int NativeErrorCode { get; }
Public ReadOnly Property NativeErrorCode As Integer
    Get

Property Value

Type: Int32
An integer value representing the error code returned by one of the functions of Microsoft Schannel security package.

Implements

IMailBeeWin32ExceptionNativeErrorCode
See Also

Reference

MailBeeSslWin32Exception Class
MailBee.Security Namespace


MailBeeSslWin32Exception Events

MailBeeSslWin32Exception Events

The MailBeeSslWin32Exception type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSslWin32Exception Class
MailBee.Security Namespace


Algorithm Class

Algorithm Class
Represents a cryptographic algorithm used for signing and encryption operations.
Inheritance Hierarchy
SystemObject
MailBee.SecurityAlgorithm

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Algorithm
Public Class Algorithm

The Algorithm type exposes the following members.

Methods
 | Name | Description
 | CreateInstanceById | Returns Algorithm object by the specified identifier.
 | CreateInstanceByOid | Returns Algorithm object by the specified system object identifier.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | BitLength | Gets the length of key used for message encryption in the cryptographic algorithm.
Public property | Category | Gets the category (type) of cryptographic algorithm.
 | ID | Gets the unique cryptographic algorithm identifier used by CryptoAPI.
 | Name | Gets the name of cryptographic algorithm.
 | Oid | Gets the unique string used by the operating system to identify this cryptographic algorithm.
Top
Remarks

MailBee automatically selects the appropriate algorithms accordingly Windows defaults.

Use this class only if the application logic requires using certain cryptographic algorithms. To select algorithms to be used by S/MIME functions of MailBee, set Smime.EncryptionAlgorithm or Smime.HashAlgorithm properties.

Examples
The example is available in EncryptionAlgorithm topic.
See Also

Reference

MailBee.Security Namespace
SmimeEncryptionAlgorithm
SmimeHashAlgorithm
MailBee.SecurityCryptoServiceProvider


Algorithm Methods

Algorithm Methods

The Algorithm type exposes the following members.

Methods
 | Name | Description
 | CreateInstanceById | Returns Algorithm object by the specified identifier.
 | CreateInstanceByOid | Returns Algorithm object by the specified system object identifier.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Algorithm Class
MailBee.Security Namespace


Algorithm.CreateInstanceById Method

AlgorithmCreateInstanceById Method
Returns Algorithm object by the specified identifier.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static Algorithm CreateInstanceById(
    int algId
)
Public Shared Function CreateInstanceById (
    algId As Integer
) As Algorithm

Parameters

algId
Type: SystemInt32
The integer value representing the algorithm identifier (ID).

Return Value

Type: Algorithm
The corresponding Algorithm object, or a null reference (Nothing in Visual Basic) if no algorithm matching the specified ID was found.
See Also

Reference

Algorithm Class
MailBee.Security Namespace
AlgorithmID
AlgorithmCreateInstanceByOid(String)


Algorithm.CreateInstanceByOid Method

AlgorithmCreateInstanceByOid Method
Returns Algorithm object by the specified system object identifier.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static Algorithm CreateInstanceByOid(
    string oid
)
Public Shared Function CreateInstanceByOid (
    oid As String
) As Algorithm

Parameters

oid
Type: SystemString
The string containing the object identifier (OID) of the cryptographic algorithm.

Return Value

Type: Algorithm
The corresponding Algorithm object, or a null reference (Nothing in Visual Basic) if no algorithm matching the specified OID was found.
Remarks

To view the full list of encryption and hash algorithms, refer to CRYPT_ALGORITHM_IDENTIFIER page of MSDN library.

For instance, to obtain RC4 algorithm (used for encryption), pass "1.2.840.113549.3.4" string to this method.

Or, to obtain MD5 hash algorithm (used for signing), pass "1.2.840.113549.1.1.4" string instead.

Note Note
RC4 and MD5 will not be available if the current system is FIPS compliant. They are considered weak.
See Also

Reference

Algorithm Class
MailBee.Security Namespace
AlgorithmOid
AlgorithmCreateInstanceById(Int32)


Algorithm Properties

Algorithm Properties

The Algorithm type exposes the following members.

Properties
 | Name | Description
 | BitLength | Gets the length of key used for message encryption in the cryptographic algorithm.
Public property | Category | Gets the category (type) of cryptographic algorithm.
 | ID | Gets the unique cryptographic algorithm identifier used by CryptoAPI.
 | Name | Gets the name of cryptographic algorithm.
 | Oid | Gets the unique string used by the operating system to identify this cryptographic algorithm.
Top
See Also

Reference

Algorithm Class
MailBee.Security Namespace


Algorithm.BitLength Property

AlgorithmBitLength Property
Gets the length of key used for message encryption in the cryptographic algorithm.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int BitLength { get; }
Public ReadOnly Property BitLength As Integer
    Get

Property Value

Type: Int32
An integer valuer specifying the length of the key of the cryptographic algorithm.
Remarks
The same cryptographic algorithm can have a different length of key. A larger key provides a stronger encryption.
Examples
The example is available in SignatureAlgorithm topic.
See Also

Reference

Algorithm Class
MailBee.Security Namespace


Algorithm.Category Property

AlgorithmCategory Property
Gets the category (type) of cryptographic algorithm.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AlgorithmCategory Category { get; }
Public ReadOnly Property Category As AlgorithmCategory
    Get

Property Value

Type: AlgorithmCategory
An AlgorithmCategory value specifying the category of the algorithm.
Remarks
EncryptionAlgorithm and HashAlgorithm algorithms must have the appropriate categories. For instance, an algorithm having Signature category can be used as HashAlgorithm but not as EncryptionAlgorithm.
See Also

Reference

Algorithm Class
MailBee.Security Namespace
SmimeEncryptionAlgorithm
SmimeHashAlgorithm


Algorithm.ID Property

AlgorithmID Property
Gets the unique cryptographic algorithm identifier used by CryptoAPI.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int ID { get; }
Public ReadOnly Property ID As Integer
    Get

Property Value

Type: Int32
An integer value of the unique identifier of the cryptographic algorithm.
Remarks
The developers of new custom cryptographic algorithms and new Cryptographic Service Providers can define new unique ID values.
Examples
The example is available in SignatureAlgorithm topic.
See Also

Reference

Algorithm Class
MailBee.Security Namespace
MailBee.SecurityCryptoServiceProvider
AlgorithmOid


Algorithm.Name Property

AlgorithmName Property
Gets the name of cryptographic algorithm.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; }
Public ReadOnly Property Name As String
    Get

Property Value

Type: String
A string containing the algorithm name.
Examples
The example is available in SignatureAlgorithm topic.
See Also

Reference

Algorithm Class
MailBee.Security Namespace


Algorithm.Oid Property

AlgorithmOid Property
Gets the unique string used by the operating system to identify this cryptographic algorithm.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Oid { get; }
Public ReadOnly Property Oid As String
    Get

Property Value

Type: String
A string identifying the algorithm in the operating system.
Remarks
An object identifier is a string consisting of a numeric sequence delimited by dots (i.e. "1.2.840.113549.1.1.4", "1.2.840.113549.3.4", "2.5", etc). Some algorithms, however, may have no object identifier assigned.
Examples
The example is available in SignatureAlgorithm topic.
See Also

Reference

Algorithm Class
MailBee.Security Namespace
AlgorithmID


AlgorithmCategory Enumeration

AlgorithmCategory Enumeration
Defines purposes of cryptographic algorithms.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum AlgorithmCategory
Public Enumeration AlgorithmCategory
Members
Member name | Value | Description
DataEncryption | 0 | The purpose is data encryption, corresponds to ALG_CLASS_DATA_ENCRYPT in WinAPI. Typical examples are RC2 and RC4.
Hash | 1 | The purpose is creating an irreversible hash of some data, corresponds to ALG_CLASS_HASH in WinAPI. Typical examples are MD2, MD5, SHA-1, and MAC.
KeyExchange | 2 | The purpose is key exchange, corresponds to ALG_CLASS_KEY_EXCHANGE in WinAPI. A typical example is RSA_KEYX.
Signature | 3 | The purpose is creating a signature of some data, corresponds to ALG_CLASS_SIGNATURE in WinAPI. A typical example is RSA_SIGN.
Unknown | 4 | The purpose is unknown.
Remarks

In WinAPI, algorithm category is known as algorithm class.

To determine the purpose of a certain algorithm represented by Algorithm object, examine its Category property.

See Also

Reference

MailBee.Security Namespace
AlgorithmCategory


CertFileType Enumeration

CertFileType Enumeration
Defines types of certificate files and data.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum CertFileType
Public Enumeration CertFileType
Members
Member name | Value | Description
Cer | 0 | The certificate file or data in X.509 format (.CER file). May contain public key only.
P7b | 1 | The certificate file or data in PKCS #7 format (.P7B file). May contain public key only.
Pfx | 2 | The certificate file or data in Personal Information Exchange format (.PFX file). May contain both public and private keys.
Remarks
To open a certificate file of a certain type, use Certificate(string, CertFileType, string) constructor. To open a certificate from memory, use Certificate(byte[], CertFileType, string) constructor. To save an existing certificate into a file of a certain type, use SaveToFile(String, CertFileType, String) method.
See Also

Reference

MailBee.Security Namespace
CertificateSaveToFile(String, CertFileType, String)


Certificate Class

Certificate Class
Provides methods and properties for accessing a digital certificate.
Inheritance Hierarchy
SystemObject
MailBee.SecurityCertificate

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Certificate : IDisposable
Public Class Certificate
    Implements IDisposable

The Certificate type exposes the following members.

Constructors
 | Name | Description
Public method | Certificate(X509Certificate2) | Initializes certificate from X509Certificate2 object.
Public method | Certificate(Byte, CertFileType, String) | Loads the certificate from binary data and returns it as Certificate object.
Public method | Certificate(String, CertFileType, String) | Loads the certificate from a file and returns it as Certificate object.
Top
Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the Certificate object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | LoadFromFileAsync | async/await version of Certificate(String, CertFileType, String).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | SaveToFile | Saves the certificate into a file on disk.
Public method | SaveToFileAsync | async/await version of SaveToFile(String, CertFileType, String).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Validate | Checks if the certificate is valid.
Public method | Validate(CertificateStore) | Checks if the certificate is valid.
Top
Properties
 | Name | Description
Public property | AsX509Certificate | Gets the certificate as X509Certificate object.
 | EmailAddress | Gets the e-mail address of the certificate principal.
 | HasPrivateKey | Gets whether the certificate has a private key.
 | IssuedBy | Gets the name of the certification authority that issued the X.509 certificate.
 | IssuedTo | Gets the name of the entity this certificate was issued to.
 | IssuerDetails | Gets the name of the certification authority which issued this X.509 certificate.
 | KeyAlgorithmString | Gets a string containing OID of algorithm used to generate a public key of X.509 certificate.
Public property | LastResult | Gets a numeric code of the last error.
 | Name | Gets the details about the principal to which the certificate was issued.
Public property | PublicKey | Gets a public key for X.509 certificate as a byte array.
 | PublicKeyString | Gets a string containing a public key for X.509 certificate.
 | RawData | Gets the raw X.509 certificate data as a byte array.
Public property | SerialNumber | Gets the serial number of the X.509-formatted certificate as a byte array.
 | SerialNumberString | Gets the serial number of the X.509-formatted certificate as a string.
 | SignatureAlgorithm | Gets the information about cryptographic algorithm used to sign the certificate.
 | Subject | Gets the subject of X.509 certificate.
Public property | SubjectAlternativeName | Gets the subject's alternative name of X.509 certificate.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Public property | Thumbprint | Gets the thumbprint of a certificate.
 | ValidFromDate | Gets the date the certificate is valid from.
 | ValidToDate | Gets the date the certificate certificate is no longer valid from.
Top
Remarks

Certificate class represents a digital certificate in MailBee.

Digital certificate is a statement which uses a digital signature to bind together a public key of an entity with information about this entity. After the trusted organization (also called a certification authority, CA) has verified the entity, it issues the requested certificate to the entity.

Certificates can contain different types of data, such as the serial number of the certificate, the algorithm used to sign the certificate, the name of the CA that issued the certificate, the name and public key of the entity requesting the certificate, and the CA's signature.

EmailAddress and HasPrivateKey are the most important properties of the certificate.

Note Note
To use this class, make sure MailBee.NET Security is licensed (MailBee.NET Objects full bundle does include the license).
Note Note
For Xamarin users: certificates currently work on Windows only. You'll get PlatformNotSupportedException on other platforms on an attempt to create an instance of Certificate class.
Examples
This sample loads the certificate from the specified file and displays its fields.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code.
using MailBee.Security;

// The actual code (put it into a method of your class).
Certificate cert = new Certificate(@"C:\Temp\certificate.cer", CertFileType.Cer, null);

Console.WriteLine("Email address: " + cert.EmailAddress);
Console.WriteLine("Private key available: " + cert.HasPrivateKey);
Console.WriteLine("Issued by: " + cert.IssuedBy);
Console.WriteLine("Issued to: " + cert.IssuedTo);
Console.WriteLine("Issuer: " + cert.IssuedBy);
Console.WriteLine("Key algorithm: " + cert.KeyAlgorithmString);
Console.WriteLine("Name: " + cert.Name);
Console.WriteLine("Public key: " + cert.PublicKeyString);
Console.WriteLine("Serial number: " + cert.SerialNumberString);
Console.WriteLine("Subject: " + cert.Subject);
Console.WriteLine("Valid from " + cert.ValidFromDate + " till " + cert.ValidToDate);
' To use the code below, import MailBee namespace at the top of your code.
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim cert As Certificate = New Certificate("C:\Temp\certificate.cer", CertFileType.Cer, Nothing)

Console.WriteLine("Email address: " & cert.EmailAddress)
Console.WriteLine("Private key available: " & cert.HasPrivateKey.ToString())
Console.WriteLine("Issued by: " & cert.IssuedBy)
Console.WriteLine("Issued to: " & cert.IssuedTo)
Console.WriteLine("Issuer: " & cert.IssuedBy)
Console.WriteLine("Key algorithm: " & cert.KeyAlgorithmString)
Console.WriteLine("Name: " & cert.Name)
Console.WriteLine("Public key: " & cert.PublicKeyString)
Console.WriteLine("Serial number: " & cert.SerialNumberString)
Console.WriteLine("Subject: " & cert.Subject)
Console.WriteLine("Valid from " & cert.ValidFromDate & " till " & cert.ValidToDate)
See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificateStore
MailBee.SecurityClientServerCertificates
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate Constructor

Certificate Constructor
Overload List
 | Name | Description
Public method | Certificate(X509Certificate2) | Initializes certificate from X509Certificate2 object.
Public method | Certificate(Byte, CertFileType, String) | Loads the certificate from binary data and returns it as Certificate object.
Public method | Certificate(String, CertFileType, String) | Loads the certificate from a file and returns it as Certificate object.
Top
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate Constructor (X509Certificate2)

Certificate Constructor (X509Certificate2)
Initializes certificate from X509Certificate2 object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate(
    X509Certificate2 x509Cert2
)
Public Sub New (
    x509Cert2 As X509Certificate2
)

Parameters

x509Cert2
Type: System.Security.Cryptography.X509CertificatesX509Certificate2
X509Certificate2 object to initialize certificate from.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | x509Cert2 is a null reference (Nothing in Visual Basic).
See Also

Reference

Certificate Class
Certificate Overload
MailBee.Security Namespace


Certificate Constructor (Byte[], CertFileType, String)

Certificate Constructor (Byte, CertFileType, String)
Loads the certificate from binary data and returns it as Certificate object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate(
    byte[] bytes,
    CertFileType fileType,
    string pfxFilePassword
)
Public Sub New (
    bytes As Byte(),
    fileType As CertFileType,
    pfxFilePassword As String
)

Parameters

bytes
Type: SystemByte
Binary content of the certificate data.
fileType
Type: MailBee.SecurityCertFileType
The format of the certificate data.
pfxFilePassword
Type: SystemString
The .PFX (PKCS #12) file password, or a null reference (Nothing in Visual Basic) if fileType is not Pfx.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | bytes is a null reference (Nothing in Visual Basic).
MailBeeCertificateParsingException | bytes is not a certificate data of the specified format.
MailBeeCertificateWin32Exception | Win32 returned an error during during processing the certificate data.
MailBeeLicenseException | MailBee.NET Security Powerup not licensed.
See Also

Reference

Certificate Class
Certificate Overload
MailBee.Security Namespace


Certificate Constructor (String, CertFileType, String)

Certificate Constructor (String, CertFileType, String)
Loads the certificate from a file and returns it as Certificate object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate(
    string filename,
    CertFileType fileType,
    string pfxFilePassword
)
Public Sub New (
    filename As String,
    fileType As CertFileType,
    pfxFilePassword As String
)

Parameters

filename
Type: SystemString
The path to the certificate file.
fileType
Type: MailBee.SecurityCertFileType
The certificate file type.
pfxFilePassword
Type: SystemString
The .PFX (.P12, PKCS #12) file password, or a null reference (Nothing in Visual Basic) if fileType is not Pfx.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | The specified file can not be opened or read.
MailBeeCertificateParsingException | filename does not designate the certificate of the specified type.
MailBeeCertificateWin32Exception | Win32 returned an error during processing the certificate data.
MailBeeLicenseException | MailBee.NET Security Powerup not licensed.
See Also

Reference

Certificate Class
Certificate Overload
MailBee.Security Namespace


Certificate Methods

Certificate Methods

The Certificate type exposes the following members.

Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the Certificate object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | LoadFromFileAsync | async/await version of Certificate(String, CertFileType, String).
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | SaveToFile | Saves the certificate into a file on disk.
Public method | SaveToFileAsync | async/await version of SaveToFile(String, CertFileType, String).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Validate | Checks if the certificate is valid.
Public method | Validate(CertificateStore) | Checks if the certificate is valid.
Top
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.Dispose Method

CertificateDispose Method
Releases the resources associated with the Certificate object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
This method exists for backward compatibility. MailBee.NET Objects library now uses managed certificates which do not require disposing.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.LoadFromFileAsync Method

CertificateLoadFromFileAsync Method
async/await version of Certificate(String, CertFileType, String).

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static Task<Certificate> LoadFromFileAsync(
    string filename,
    CertFileType fileType,
    string pfxFilePassword
)
Public Shared Function LoadFromFileAsync (
    filename As String,
    fileType As CertFileType,
    pfxFilePassword As String
) As Task(Of Certificate)

Parameters

filename
Type: SystemString
The path to the certificate file.
fileType
Type: MailBee.SecurityCertFileType
The certificate file type.
pfxFilePassword
Type: SystemString
The .PFX (.P12, PKCS #12) file password, or a null reference (Nothing in Visual Basic) if fileType is not Pfx.

Return Value

Type: Task Certificate
A task that represents the asynchronous operation. The value of TResult parameter is the Certificate object.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | The specified file can not be opened or read.
MailBeeCertificateParsingException | filename does not designate the certificate of the specified type.
MailBeeCertificateWin32Exception | Win32 returned an error during processing the certificate data.
MailBeeLicenseException | MailBee.NET Security Powerup not licensed.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.SaveToFile Method

CertificateSaveToFile Method
Saves the certificate into a file on disk.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveToFile(
    string filename,
    CertFileType fileType,
    string pfxPassword
)
Public Function SaveToFile (
    filename As String,
    fileType As CertFileType,
    pfxPassword As String
) As Boolean

Parameters

filename
Type: SystemString
The path to the file.
fileType
Type: MailBee.SecurityCertFileType
The format of the file to save.
pfxPassword
Type: SystemString
PFX password if fileType is Pfx, or a null reference (Nothing in Visual Basic).

Return Value

Type: Boolean
true if the certificate was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | The specified file can not be written to.
MailBeeCertificateWin32Exception | Win32 returned an error during during processing the certificate data.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateCertificate(String, CertFileType, String)
CertificateCertificate(Byte, CertFileType, String)


Certificate.SaveToFileAsync Method

CertificateSaveToFileAsync Method
async/await version of SaveToFile(String, CertFileType, String).

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SaveToFileAsync(
    string filename,
    CertFileType fileType,
    string pfxPassword
)
Public Function SaveToFileAsync (
    filename As String,
    fileType As CertFileType,
    pfxPassword As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The path to the file.
fileType
Type: MailBee.SecurityCertFileType
The format of the file to save.
pfxPassword
Type: SystemString
PFX password if fileType is Pfx, or a null reference (Nothing in Visual Basic).

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the certificate was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | The specified file can not be written to.
MailBeeCertificateWin32Exception | Win32 returned an error during during processing the certificate data.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.Validate Method

CertificateValidate Method
Overload List
 | Name | Description
 | Validate | Checks if the certificate is valid.
Public method | Validate(CertificateStore) | Checks if the certificate is valid.
Top
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.Validate Method

CertificateValidate Method
Checks if the certificate is valid.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateValidationFlags Validate()
Public Function Validate As CertificateValidationFlags

Return Value

Type: CertificateValidationFlags
A bitwise combination of CertificateValidationFlags indicating criteria the validation failed for, or None if the certificate is valid.
Exceptions
Exception | Condition
MailBeeCertificateWin32Exception | Win32 returned an error during during processing the certificate data.
Remarks
You may get IsUntrustedRoot value returned by this method even if you know the certificate is trusted. This may happen if the certification authority (CA) which issued the given certificate is not present in the system CA store. This often happens with ASP.NET applications because ASP.NET user by default has only a few CA's in its system store. You can either add more CA's there or export your CA (one or more) into a file and use it as an extra store. See Validate(CertificateStore) overload or ASP.NET S/MIME demo projects shipped with the product for more details.
Examples
This sample loads the certificate store from disk and validates all the certificates contained in this store.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code.
using System;
using MailBee.Security;

// The actual code (put it into a method of your class).
CertificateStore store = new CertificateStore(@"C:\Temp\certificate.p7b", CertStoreType.PublicFile, null);
CertificateCollection coll = store.GetAllCertificates();

foreach (Certificate cert in coll)
{
    Console.WriteLine(cert.Name);
    CertificateValidationFlags status = cert.Validate();
    if (status != CertificateValidationFlags.None)
    {
        Console.WriteLine("Untrusted");
        if ((status & CertificateValidationFlags.IsNotTimeValid) > 0)
        {
            Console.WriteLine("Certificate expired!");
        }
    }
    else
    {
        Console.WriteLine("Trusted");
    }
    Console.WriteLine("--------------------------------");
}
' To use the code below, import MailBee namespace at the top of your code.
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim store As CertificateStore = New CertificateStore("C:\Temp\certificate.p7b", CertStoreType.PublicFile, Nothing)
Dim coll As CertificateCollection = store.GetAllCertificates()

For Each cert As Certificate In coll
    Console.WriteLine(cert.Name)
    Dim status As CertificateValidationFlags = cert.Validate()

    If status <> CertificateValidationFlags.None Then
        Console.WriteLine("Untrusted")
        If ((status And CertificateValidationFlags.IsNotTimeValid) > 0) Then
            Console.WriteLine("Certificate expired!")
        End If
    Else
        Console.WriteLine("Trusted")
    End If
    Console.WriteLine("--------------------------------")
Next
See Also

Reference

Certificate Class
Validate Overload
MailBee.Security Namespace
MailBee.SecurityCertificateValidationFlags


Certificate.Validate Method (CertificateStore)

CertificateValidate Method (CertificateStore)
Checks if the certificate is valid.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateValidationFlags Validate(
    CertificateStore extraStore
)
Public Function Validate (
    extraStore As CertificateStore
) As CertificateValidationFlags

Parameters

extraStore
Type: MailBee.SecurityCertificateStore
A reference to the additional store of certification authorities, or a null reference (Nothing in Visual Basic) if only the system store should be used.

Return Value

Type: CertificateValidationFlags
A bitwise combination of CertificateValidationFlags indicating criteria the validation failed for, or None if the certificate is valid.
Exceptions
Exception | Condition
MailBeeCertificateWin32Exception | Win32 returned an error during during processing the certificate data.
Remarks
You may get IsUntrustedRoot value returned by this method even if you know the certificate is trusted. This may happen if the certification authority (CA) which issued the given certificate is not present in the system CA store. This often happens with ASP.NET applications because ASP.NET user by default has only a few CA's in its system store. You can either add more CA's there or export your CA (one or more) into a file and use it as extraStore. See ASP.NET S/MIME demo projects shipped with the product for more details.
See Also

Reference

Certificate Class
Validate Overload
MailBee.Security Namespace
MailBee.SecurityCertificateValidationFlags


Certificate Properties

Certificate Properties

The Certificate type exposes the following members.

Properties
 | Name | Description
Public property | AsX509Certificate | Gets the certificate as X509Certificate object.
 | EmailAddress | Gets the e-mail address of the certificate principal.
 | HasPrivateKey | Gets whether the certificate has a private key.
 | IssuedBy | Gets the name of the certification authority that issued the X.509 certificate.
 | IssuedTo | Gets the name of the entity this certificate was issued to.
 | IssuerDetails | Gets the name of the certification authority which issued this X.509 certificate.
 | KeyAlgorithmString | Gets a string containing OID of algorithm used to generate a public key of X.509 certificate.
Public property | LastResult | Gets a numeric code of the last error.
 | Name | Gets the details about the principal to which the certificate was issued.
Public property | PublicKey | Gets a public key for X.509 certificate as a byte array.
 | PublicKeyString | Gets a string containing a public key for X.509 certificate.
 | RawData | Gets the raw X.509 certificate data as a byte array.
Public property | SerialNumber | Gets the serial number of the X.509-formatted certificate as a byte array.
 | SerialNumberString | Gets the serial number of the X.509-formatted certificate as a string.
 | SignatureAlgorithm | Gets the information about cryptographic algorithm used to sign the certificate.
 | Subject | Gets the subject of X.509 certificate.
Public property | SubjectAlternativeName | Gets the subject's alternative name of X.509 certificate.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Public property | Thumbprint | Gets the thumbprint of a certificate.
 | ValidFromDate | Gets the date the certificate is valid from.
 | ValidToDate | Gets the date the certificate certificate is no longer valid from.
Top
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.AsX509Certificate Property

CertificateAsX509Certificate Property
Gets the certificate as X509Certificate object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public X509Certificate2 AsX509Certificate { get; }
Public ReadOnly Property AsX509Certificate As X509Certificate2
    Get

Property Value

Type: X509Certificate2
An X509Certificate object which represents the certificate.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.EmailAddress Property

CertificateEmailAddress Property
Gets the e-mail address of the certificate principal.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string EmailAddress { get; }
Public ReadOnly Property EmailAddress As String
    Get

Property Value

Type: String
A string containing the e-mail address of the certificate principal.
Remarks
With regard to using certificates in e-mail area, EmailAddress is the most important field of the certificate.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateName
CertificateSubject


Certificate.HasPrivateKey Property

CertificateHasPrivateKey Property
Gets whether the certificate has a private key.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool HasPrivateKey { get; }
Public ReadOnly Property HasPrivateKey As Boolean
    Get

Property Value

Type: Boolean
true if certificate includes the private key; otherwise, false.
Remarks
Certificates with private key can be using for all S/MIME operations (signing, encryption, checking a signature, decryption). Public certificates (without private key) can only be used for encryption and checking a signature.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificatePublicKey


Certificate.IssuedBy Property

CertificateIssuedBy Property
Gets the name of the certification authority that issued the X.509 certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string IssuedBy { get; }
Public ReadOnly Property IssuedBy As String
    Get

Property Value

Type: String
A string containing the name of certificate authority that issued the certificate.
Remarks

To get more detailed information about X.509 certificate issuer, the developer can use the IssuerDetails property.

Also, the IssuedBy property can be used to determine whom this X.509 certificate was issued by.

Examples
The example is available in Certificate class documentation.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateIssuedTo
CertificateIssuerDetails
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.IssuedTo Property

CertificateIssuedTo Property
Gets the name of the entity this certificate was issued to.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string IssuedTo { get; }
Public ReadOnly Property IssuedTo As String
    Get

Property Value

Type: String
A string containing the name of a person/organization whom the certificate was issued to.
Remarks
To get the information about X.509 certificate issuer, the developer can use the IssuerDetails or IssuedBy property.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateIssuerDetails
CertificateIssuedBy
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.IssuerDetails Property

CertificateIssuerDetails Property
Gets the name of the certification authority which issued this X.509 certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string IssuerDetails { get; }
Public ReadOnly Property IssuerDetails As String
    Get

Property Value

Type: String
A string containing the name of certification authority which issued the certificate.
Remarks
The developer can perform search over this property value during searching for certificates in a certificate store using FindCertificates(String, CertificateFields) method.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateIssuedTo
CertificateIssuedBy
CertificateStoreFindCertificates(String, CertificateFields)
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.KeyAlgorithmString Property

CertificateKeyAlgorithmString Property
Gets a string containing OID of algorithm used to generate a public key of X.509 certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string KeyAlgorithmString { get; }
Public ReadOnly Property KeyAlgorithmString As String
    Get

Property Value

Type: String
An Algorithm object containing the information about the cryptographic key.
Remarks
To know more about OID, refer to Algorithm.Oid property.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
AlgorithmOid
CertificateSignatureAlgorithm
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.LastResult Property

CertificateLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateThrowExceptions


Certificate.Name Property

CertificateName Property
Gets the details about the principal to which the certificate was issued.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; }
Public ReadOnly Property Name As String
    Get

Property Value

Type: String
A string containing the name of the principal the certificate was issued to.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.PublicKey Property

CertificatePublicKey Property
Gets a public key for X.509 certificate as a byte array.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] PublicKey { get; }
Public ReadOnly Property PublicKey As Byte()
    Get

Property Value

Type: Byte
A public key as an array of bytes.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificatePublicKeyString
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.PublicKeyString Property

CertificatePublicKeyString Property
Gets a string containing a public key for X.509 certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string PublicKeyString { get; }
Public ReadOnly Property PublicKeyString As String
    Get

Property Value

Type: String
A string containing the hexadecimal public key.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificatePublicKey
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.RawData Property

CertificateRawData Property
Gets the raw X.509 certificate data as a byte array.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] RawData { get; }
Public ReadOnly Property RawData As Byte()
    Get

Property Value

Type: Byte
The certificate as an array of bytes.
Examples

This sample selects the first certificate from the system store called "MY" ("Personal" tab of Certificates dialog in Internet Explorer) and saves the certificate raw data into the specified file to disk.

Note Note
To save the certificate to disk, this sample uses standard binary writer for demonstration purposes only. The developer can call the SaveToFile(String, CertFileType, String) method to save the certificate to disk.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code.
using System.IO;
using MailBee.Security;

// The actual code (put it into a method of your class).
CertificateStore store = new CertificateStore(CertificateStore.Personal, CertStoreType.System, null);
CertificateCollection collection = store.GetAllCertificates();
if (collection.Count > 0)
{
    Certificate cert = collection[0];
    using (BinaryWriter bw = new BinaryWriter(File.Open(@"C:\Temp\newcert.cer", FileMode.Create)))
    {
        bw.Write(cert.RawData);
        bw.Flush();
    }
}
' To use the code below, import MailBee namespace at the top of your code.
Imports System.IO
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim store As CertificateStore = New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)
Dim collection As CertificateCollection = store.GetAllCertificates()

If collection.Count > 0 Then
    Dim cert As Certificate = collection(0)
    Dim bw As New BinaryWriter(File.Open("C:\Temp\newcert.cer", FileMode.Create))

    bw.Write(cert.RawData)
    bw.Flush()
End If
See Also

Reference

Certificate Class
MailBee.Security Namespace
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.SerialNumber Property

CertificateSerialNumber Property
Gets the serial number of the X.509-formatted certificate as a byte array.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public byte[] SerialNumber { get; }
Public ReadOnly Property SerialNumber As Byte()
    Get

Property Value

Type: Byte
A byte array representation of the certificate serial number.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateSerialNumberString
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.SerialNumberString Property

CertificateSerialNumberString Property
Gets the serial number of the X.509-formatted certificate as a string.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SerialNumberString { get; }
Public ReadOnly Property SerialNumberString As String
    Get

Property Value

Type: String
A string containing hexadecimal serial number of a digital certificate.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateSerialNumber
System.Security.Cryptography.X509CertificatesX509Certificate


Certificate.SignatureAlgorithm Property

CertificateSignatureAlgorithm Property
Gets the information about cryptographic algorithm used to sign the certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Algorithm SignatureAlgorithm { get; }
Public ReadOnly Property SignatureAlgorithm As Algorithm
    Get

Property Value

Type: Algorithm
Object of Algorithm class representing information about the signature algorithm.
Examples
This sample loads a certificate from the specified file and displays information about it.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class)
Certificate cert = new Certificate(@"C:\Temp\certificate.cer", CertFileType.Cer, null);

Console.WriteLine("Key algorithm name: " + cert.SignatureAlgorithm.Name);
Console.WriteLine("Key algorithm OID: " + cert.SignatureAlgorithm.Oid);
Console.WriteLine("Key algorithm ID: " + cert.SignatureAlgorithm.ID);
Console.WriteLine("Key algorithm bit length: " + cert.SignatureAlgorithm.BitLength);
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class)
Dim cert As Certificate = New Certificate("C:\Temp\certificate.cer", CertFileType.Cer, Nothing)

Console.WriteLine("Key algorithm name: " & cert.SignatureAlgorithm.Name)
Console.WriteLine("Key algorithm OID: " & cert.SignatureAlgorithm.Oid)
Console.WriteLine("Key algorithm ID: " & cert.SignatureAlgorithm.ID.ToString())
Console.WriteLine("Key algorithm bit length: " & cert.SignatureAlgorithm.BitLength.ToString())
See Also

Reference

Certificate Class
MailBee.Security Namespace
MailBee.SecurityAlgorithm
CertificateKeyAlgorithmString


Certificate.Subject Property

CertificateSubject Property
Gets the subject of X.509 certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Subject { get; }
Public ReadOnly Property Subject As String
    Get

Property Value

Type: String
A string containing the certificate subject.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.SubjectAlternativeName Property

CertificateSubjectAlternativeName Property
Gets the subject's alternative name of X.509 certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SubjectAlternativeName { get; }
Public ReadOnly Property SubjectAlternativeName As String
    Get

Property Value

Type: String
A string containing the certificate subject's alternative name.
Remarks
This property returns a null reference (Nothing in Visual Basic) in .NET 1.1 version as it's only supported from .NET 2.0 and above.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.ThrowExceptions Property

CertificateThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the object will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the object methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee.NET usage will still be thrown.

Typical example of such errors is passing invalid arguments to methods. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.Thumbprint Property

CertificateThumbprint Property
Gets the thumbprint of a certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Thumbprint { get; }
Public ReadOnly Property Thumbprint As String
    Get

Property Value

Type: String
A string containing the thumbprint of the certificate.
See Also

Reference

Certificate Class
MailBee.Security Namespace


Certificate.ValidFromDate Property

CertificateValidFromDate Property
Gets the date the certificate is valid from.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime ValidFromDate { get; }
Public ReadOnly Property ValidFromDate As DateTime
    Get

Property Value

Type: DateTime
A DateTime value representing the date from which the certificate gets no longer valid, or MinValue if the date could not be parsed.
Exceptions
Exception | Condition
MailBeeDateParsingException | A date parsing error occurred and ThrowExceptions is true.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateValidToDate


Certificate.ValidToDate Property

CertificateValidToDate Property
Gets the date the certificate certificate is no longer valid from.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DateTime ValidToDate { get; }
Public ReadOnly Property ValidToDate As DateTime
    Get

Property Value

Type: DateTime
A DateTime value representing the date when the certificate expires and becomes no longer valid, or MinValue if the date could not be parsed.
Exceptions
Exception | Condition
MailBeeDateParsingException | A date parsing error occurred and ThrowExceptions is true.
Examples
The example is available in Certificate topic.
See Also

Reference

Certificate Class
MailBee.Security Namespace
CertificateValidFromDate


CertificateCollection Class

CertificateCollection Class
Provides methods and properties for accessing collections of Certificate objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBee.SecurityCertificateCollection

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class CertificateCollection : CollectionBase
Public Class CertificateCollection
    Inherits CollectionBase

The CertificateCollection type exposes the following members.

Constructors
 | Name | Description
Public method | CertificateCollection | Initializes a new instance of the CertificateCollection class
Top
Methods
 | Name | Description
Public method | Add | Adds the specified certificate to the collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
 | Contains | Checks whether the specified certificate is contained in the collection or not.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove(String) | Removes the certificate with the specified name of the entity this certificate was issued to.
 | Remove(Certificate) | Removes the specified Certificate from the collection.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets the certificate at the specified zero-based index.
Public property | ItemString | Gets the certificate by the name of the principal to which this certificate was issued.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

CertificateCollection class represents a group of Certificate objects in MailBee.

On other hand, CertificateStore class represents a group of certificates which exists on operating system level (for instance, certain certificate stores can be used by S/MIME functions to validate certificates) and has certain physical location: file store, system (Windows registry) store, memory store, etc. A certificate store, being an operating system level object, can be persistent and available to other applications while CertificateCollection is only used by those functions of MailBee which can accept or return values containing multiple Certificate objects.

The contents of a certificate store can be represented as CertificateCollection though. You can use CertificateStore.FindCertificates or CertificateStore.GetAllCertificates methods for this.

Examples
This sample opens "CA" system certificate store, finds all the certificates issued by Microsoft, creates a new certificate store, adds all the found certificates to this store and saves the store to disk as a file. The sample demonstrates using both CertificateCollection and CertificateStore classes.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

CertificateStore store = new CertificateStore(CertificateStore.IntermediateCA, CertStoreType.System, null);
CertificateCollection coll = store.FindCertificates("Microsoft", CertificateFields.Issuer);
store = new CertificateStore(null, CertStoreType.Memory, null);
store.AddCertificates(coll, true);
store.SaveToFile(@"C:\Temp\microsoft_certificates.sst", CertStoreFileType.Sst, null);
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

Dim store As CertificateStore = New CertificateStore("CA", CertStoreType.System, Nothing)
Dim coll As CertificateCollection = store.FindCertificates("microsoft", CertificateFields.Issuer)
store = New CertificateStore(Nothing, CertStoreType.Memory, Nothing)
store.AddCertificates(coll, True)
store.SaveToFile("C:\Temp\microsoft_certificates.sst", CertStoreFileType.Sst, Nothing)
See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificateStore
MailBee.SecurityCertificate


CertificateCollection Constructor

CertificateCollection Constructor
Initializes a new instance of the CertificateCollection class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateCollection()
Public Sub New
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace


CertificateCollection Methods

CertificateCollection Methods

The CertificateCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds the specified certificate to the collection.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
 | Contains | Checks whether the specified certificate is contained in the collection or not.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove(String) | Removes the certificate with the specified name of the entity this certificate was issued to.
 | Remove(Certificate) | Removes the specified Certificate from the collection.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace


CertificateCollection.Add Method

CertificateCollectionAdd Method
Adds the specified certificate to the collection.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    Certificate cert
)
Public Sub Add (
    cert As Certificate
)

Parameters

cert
Type: MailBee.SecurityCertificate
The certificate that should be added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | cert is a null reference (Nothing in Visual Basic).
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace
MailBee.SecurityCertificate
CertificateStoreAddCertificate(Certificate, Boolean)


CertificateCollection.Contains Method

CertificateCollectionContains Method
Checks whether the specified certificate is contained in the collection or not.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Contains(
    Certificate cert
)
Public Function Contains (
    cert As Certificate
) As Boolean

Parameters

cert
Type: MailBee.SecurityCertificate
The certificate that should be checked.

Return Value

Type: Boolean
true if the certificate was found in the collection; otherwise, false.
Examples
This sample adds the certificate to the collection if it's not already present there.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class)
Certificate cert = new Certificate(@"C:\Temp\certificate.cer", CertFileType.Cer, null);
CertificateStore store = new CertificateStore(@"C:\Temp\my_store.p7b", CertStoreType.PublicFile, null);
CertificateCollection collection = store.GetAllCertificates();

// Add certificate to the collection if it doesn't contain such certificate
if (!collection.Contains(cert))
{
    store.AddCertificate(cert, false);
}
store.SaveToFile(@"C:\Temp\my_store.p7b", CertStoreFileType.P7b, null);
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class)
Dim cert As Certificate = New Certificate("C:\Temp\certificate.cer", CertFileType.Cer, Nothing)
Dim store As CertificateStore = New CertificateStore("C:\Temp\my_store.p7b", CertStoreType.PublicFile, Nothing)
Dim Collection As CertificateCollection = store.GetAllCertificates()

' Add certificate to the collection if it doesn't contain such certificate
If Not Collection.Contains(cert) Then
    store.AddCertificate(cert, False)
End If

store.SaveToFile("C:\Temp\my_store.p7b", CertStoreFileType.P7b, Nothing)
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace
MailBee.SecurityCertificate
CertificateStoreFindCertificates(String, CertificateFields)


CertificateCollection.Remove Method

CertificateCollectionRemove Method
Removes the specified certificate from the collection.
Overload List
 | Name | Description
Public method | Remove(String) | Removes the certificate with the specified name of the entity this certificate was issued to.
 | Remove(Certificate) | Removes the specified Certificate from the collection.
Top
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace


CertificateCollection.Remove Method (String)

CertificateCollectionRemove Method (String)
Removes the certificate with the specified name of the entity this certificate was issued to.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    string issuedTo
)
Public Function Remove (
    issuedTo As String
) As Boolean

Parameters

issuedTo
Type: SystemString
The name of the person/organization this certificate was issued to.

Return Value

Type: Boolean
true if at least one item was removed from the collection; false if the collection does not contain any certificates with the given principal name.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | issuedTo is a null reference (Nothing in Visual Basic).
Remarks
All the certificates having IssuedTo equal to issuedTo will be removed from the collection. The string comparison is case-insensitive (no difference between abc and ABC).
See Also

Reference

CertificateCollection Class
Remove Overload
MailBee.Security Namespace
MailBee.SecurityCertificate
CertificateStoreDeleteCertificate(Certificate)


CertificateCollection.Remove Method (Certificate)

CertificateCollectionRemove Method (Certificate)
Removes the specified Certificate from the collection.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Remove(
    Certificate cert
)
Public Function Remove (
    cert As Certificate
) As Boolean

Parameters

cert
Type: MailBee.SecurityCertificate
The certificate that should be removed from the collection.

Return Value

Type: Boolean
true if the certificate was removed from the collection; false if the certificate is not contained in the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | cert is a null reference (Nothing in Visual Basic).
Examples
The sample removes all the certificates without private key from the collection.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class)

CertificateStore store = new CertificateStore(@"C:\Temp\certificate.pfx", CertStoreType.PfxFile, "password");
CertificateCollection col = store.GetAllCertificates();

// Remove all certificates which don't have any private key
for (int i = col.Count - 1; i >= 0 ; i--)
{
    if (!col[i].HasPrivateKey)
    {
        col.Remove(col[i]);
    }
}
// Save changes to disk
if (col.Count > 0)
{
    CertificateStore newStore = new CertificateStore();
    newStore.AddCertificates(col, true);
    newStore.SaveToFile(@"C:\Temp\private.sst", CertStoreFileType.Sst, null);
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class)

Dim store As CertificateStore = New CertificateStore("C:\Temp\certificate.pfx", CertStoreType.PfxFile, "password")
Dim col As CertificateCollection = store.GetAllCertificates()

' Remove all certificates that do not have any private key
For i As Integer = col.Count - 1 To 0 Step -1
    If Not col(i).HasPrivateKey Then
        col.Remove(col(i))
    End If
Next

' Save changes to disk
If col.Count > 0 Then
    Dim newStore As CertificateStore = New CertificateStore
    newStore.AddCertificates(col, True)
    newStore.SaveToFile("C:\Temp\private.sst", CertStoreFileType.Sst, Nothing)
End If
See Also

Reference

CertificateCollection Class
Remove Overload
MailBee.Security Namespace
MailBee.SecurityCertificate
CertificateStoreDeleteCertificate(Certificate)


CertificateCollection Properties

CertificateCollection Properties

The CertificateCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
 | ItemInt32 | Gets the certificate at the specified zero-based index.
Public property | ItemString | Gets the certificate by the name of the principal to which this certificate was issued.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace


CertificateCollection.Item Property

CertificateCollectionItem Property
Overload List
 | Name | Description
 | ItemInt32 | Gets the certificate at the specified zero-based index.
Public property | ItemString | Gets the certificate by the name of the principal to which this certificate was issued.
Top
See Also

Reference

CertificateCollection Class
MailBee.Security Namespace


CertificateCollection.Item Property (Int32)

CertificateCollectionItem Property (Int32)
Gets the certificate at the specified zero-based index.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As Certificate
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the certificate in the collection.

Property Value

Type: Certificate
A Certificate object having the specified zero-based index in the collection.
Examples
The example is available in Remove(Certificate) method documentation.
See Also

Reference

CertificateCollection Class
Item Overload
MailBee.Security Namespace
MailBee.SecurityCertificate


CertificateCollection.Item Property (String)

CertificateCollectionItem Property (String)
Gets the certificate by the name of the principal to which this certificate was issued.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate this[
    string issuedTo
] { get; }
Public ReadOnly Default Property Item (
    issuedTo As String
) As Certificate
    Get

Parameters

issuedTo
Type: SystemString
The name of the entity the certificate was issued to.

Property Value

Type: Certificate
A Certificate object corresponding to the given principal name, or a null reference (Nothing in Visual Basic) if no matching certificate was found.
Remarks

This method compares value with IssuedTo values of the certificates in the collection. The string comparison is case-insensitive (no difference between abc and ABC).

If there are more than one certificate having the specified principal name, only the first certificate found will be returned.

See Also

Reference

CertificateCollection Class
Item Overload
MailBee.Security Namespace
MailBee.SecurityCertificate


CertificateFields Enumeration

CertificateFields Enumeration
Defines certificate fields available for search with FindCertificates(String, CertificateFields) method.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum CertificateFields
<FlagsAttribute>
Public Enumeration CertificateFields
Members
Member name | Value | Description
Name | 1 | Corresponds to Name field.
Subject | 2 | Corresponds to Subject field.
Issuer | 4 | Corresponds to IssuerDetails field.
SerialNumber | 8 | Corresponds to SerialNumberString field.
PublicKey | 16 | Corresponds to PublicKeyString field.
EmailAddress | 32 | Corresponds to EmailAddress field.
Thumbprint | 64 | Corresponds to Thumbprint field.
All | 127 | All of the fields listed above.
See Also

Reference

MailBee.Security Namespace
CertificateStoreFindCertificates(String, CertificateFields)


CertificateStore Class

CertificateStore Class
Provides the methods and properties for accessing certificate stores.
Inheritance Hierarchy
SystemObject
MailBee.SecurityCertificateStore

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class CertificateStore : IDisposable
Public Class CertificateStore
    Implements IDisposable

The CertificateStore type exposes the following members.

Constructors
 | Name | Description
Public method | CertificateStore | Creates a new certificate store in memory.
Public method | CertificateStore(Byte, String) | Opens an existing store of certificates from a memory footprint of a PFX (.P12, PKCS #12) file.
Public method | CertificateStore(Byte, CertStoreType, CryptoServiceProvider) | Opens an existing store of certificates from a memory footprint of a PKCS #7 (.P7B) or Serialized Certificate Storage (.SST) file.
 | CertificateStore(String, CertStoreType, String) | Opens an existing or creates a new store of certificates.
Public method | CertificateStore(String, CertStoreType, String, CryptoServiceProvider, RegistryStoreLocation) | Opens an existing or creates a new store of certificates.
Top
Methods
 | Name | Description
 | AddCertificate | Adds the specified certificate to the store.
 | AddCertificates | Adds all the certificates from the specified collection to the store.
 | DeleteCertificate | Removes the specified certificate from the store.
Public method | Dispose | Releases the resources associated with the current CertificateStore object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | FindCertificates | Searches the certificates in the store by the specified criteria.
 | GetAllCertificates | Creates and returns a collection of all the certificates contained in the certificate store.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | RegisterSystemStore | Registers a new system certificate store.
 | SaveToFile | Saves the certificate store into a file.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | UnregisterSystemStore | Unregisters an existing system certificate store.
Top
Fields
Name | Description
IntermediateCA | Gets the name of the system certificate store containing certificates of intermediate certification authorities.
OtherPeople | Gets the name of the system certificate store containing certificates of other entities such as your address book members.
Personal | Gets the name of the system certificate store containing personal certificates.
RootCA | Gets the name of the system certificate store containing certificates of trusted root certification authorities.
Top
Properties
 | Name | Description
Public property | LastResult | Gets a numeric code of the last error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks

Certificate store is a persistent or memory storage of certificates. There are a number of types of certificate stores supported by Windows (and therefore by MailBee), listed in CertStoreType enumeration.

Stores of System type play key role in many security procedures. You can view the contents of the system stores in "Internet Options/Content/Certificates" dialog of Internet Explorer. CertificateStore class defines several constants which refer to the standard system stores (such as Personal). Also, you can create your own system stores with RegisterSystemStore(String, RegistryStoreLocation) method.

Note Note
ASP.NET application developers should be aware that the system certificate stores of ASP.NET user may contain less number of certificates in comparison to those of regular users. See S/MIME Demo for ASP.NET sample project shipped with the product for more information on how to deal with this.
Examples
This sample opens the standard system store and displays the details for each certificate.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class).
CertificateStore store = new CertificateStore(CertificateStore.Personal, CertStoreType.System, null);
CertificateCollection coll = store.GetAllCertificates();

foreach (Certificate cert in coll)
{
    Console.WriteLine("Issued to: " + cert.IssuedTo);
    Console.WriteLine("Issued by: " + cert.IssuedBy);
    Console.WriteLine("Email: " + cert.EmailAddress);
    Console.WriteLine("Valid to: " + cert.ValidToDate);
    Console.WriteLine("Has private key: " + cert.HasPrivateKey);
    Console.WriteLine("------------------------------");
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim store As CertificateStore = New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)
Dim coll As CertificateCollection = store.GetAllCertificates()

For Each cert As Certificate In coll
    Console.WriteLine("Issued to: " & cert.IssuedTo)
    Console.WriteLine("Issued by: " & cert.IssuedBy)
    Console.WriteLine("Email: " & cert.EmailAddress)
    Console.WriteLine("Valid to: " & cert.ValidToDate)
    Console.WriteLine("Has private key: " & cert.HasPrivateKey)
    Console.WriteLine("------------------------------")
Next
See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificate
MailBee.SecurityCertificateCollection


CertificateStore Constructor

CertificateStore Constructor
Opens an existing or creates a new store of certificates.
Overload List
 | Name | Description
Public method | CertificateStore | Creates a new certificate store in memory.
Public method | CertificateStore(Byte, String) | Opens an existing store of certificates from a memory footprint of a PFX (.P12, PKCS #12) file.
Public method | CertificateStore(Byte, CertStoreType, CryptoServiceProvider) | Opens an existing store of certificates from a memory footprint of a PKCS #7 (.P7B) or Serialized Certificate Storage (.SST) file.
 | CertificateStore(String, CertStoreType, String) | Opens an existing or creates a new store of certificates.
Public method | CertificateStore(String, CertStoreType, String, CryptoServiceProvider, RegistryStoreLocation) | Opens an existing or creates a new store of certificates.
Top
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore Constructor

CertificateStore Constructor
Creates a new certificate store in memory.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateStore()
Public Sub New
Remarks
This overload is typically used for creating a store which can then be filled with one or more certificates and either saved to a file or passed to a method which accepts CertificateStore as a parameter. The latter case is useful when you need to notify a method about a store with some certificates in it but you do not already have such a store. For instance, you can call Validate(CertificateStore) method with extraStore parameter pointing to a store containing certificates of all certification authorities needed for validation. However, it's possible that some of these certificates reside in another store. Since you cannot pass two stores to Validate(CertificateStore) method, you should either create a persistent store containing all the certificates from the both stores, or combine them at runtime by creating a new memory store and then adding certificates from both stores to the memory one. The latter approach does not require permissions to create files or new registry entries (which would be needed for modifying persistent certificate stores which reside in files or Windows registry).
See Also

Reference

CertificateStore Class
CertificateStore Overload
MailBee.Security Namespace


CertificateStore Constructor (Byte[], String)

CertificateStore Constructor (Byte, String)
Opens an existing store of certificates from a memory footprint of a PFX (.P12, PKCS #12) file.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateStore(
    byte[] pfxData,
    string pfxPassword
)
Public Sub New (
    pfxData As Byte(),
    pfxPassword As String
)

Parameters

pfxData
Type: SystemByte
A byte array containing the memory footprint of a PFX file.
pfxPassword
Type: SystemString
PFX password.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | pfxData is a null reference (Nothing in Visual Basic).
MailBeeInvalidArgumentException | pfxData is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error during opening the certificate store.
Remarks
You can use this constructor when you have PFX (.P12, PKCS #12) data in memory. For instance, if you upload PFX data to a web server and do not want to save it into a file.
See Also

Reference

CertificateStore Class
CertificateStore Overload
MailBee.Security Namespace


CertificateStore Constructor (Byte[], CertStoreType, CryptoServiceProvider)

CertificateStore Constructor (Byte, CertStoreType, CryptoServiceProvider)
Opens an existing store of certificates from a memory footprint of a PKCS #7 (.P7B) or Serialized Certificate Storage (.SST) file.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateStore(
    byte[] storeData,
    CertStoreType storeType,
    CryptoServiceProvider csp
)
Public Sub New (
    storeData As Byte(),
    storeType As CertStoreType,
    csp As CryptoServiceProvider
)

Parameters

storeData
Type: SystemByte
A byte array containing the memory footprint of a PKCS #7 or serialized file.
storeType
Type: MailBee.SecurityCertStoreType
Pkcs7Bytes or SerializedBytes.
csp
Type: MailBee.SecurityCryptoServiceProvider
A reference to CryptoServiceProvider instance descripting Cryptographic service provider (CSP) to be used for the given store, or a null reference (Nothing in Visual Basic) if the default CSP should be used.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | storeData is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error during opening the certificate store.
Remarks
To open a .PFX (.P12, PKCS #12) file, use CertificateStore(Byte, String) overload.
See Also

Reference

CertificateStore Class
CertificateStore Overload
MailBee.Security Namespace


CertificateStore Constructor (String, CertStoreType, String)

CertificateStore Constructor (String, CertStoreType, String)
Opens an existing or creates a new store of certificates.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateStore(
    string storeName,
    CertStoreType storeType,
    string pfxPassword
)
Public Sub New (
    storeName As String,
    storeType As CertStoreType,
    pfxPassword As String
)

Parameters

storeName
Type: SystemString
The name of the certificate store or the filename if the store is a file.
storeType
Type: MailBee.SecurityCertStoreType
The type of the certificate store.
pfxPassword
Type: SystemString
PFX (.P12, PKCS #12) password if storeType is Pfx; otherwise, can be a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | storeName is a null reference (Nothing in Visual Basic) or an empty string while storeType is neither Memory nor PfxBytes.
MailBeeIOException | The specified PFX file can not be opened or read.
MailBeeCertificateStoreWin32Exception | Win32 returned an error during opening the certificate store.
Remarks

Only Memory stores can be created. Other stores can only be opened. It's possible, however, to create a memory store and then save it into a file using SaveToFile(String, CertStoreFileType, String) method. To create a new system store, use RegisterSystemStore(String, RegistryStoreLocation) method.

If you open a file store and then modify its contents, it won't be updated on disk until you save it back to the file. A system store, however, gets updated immediately in its registry location each time you call any method which modifies this store.

Note Note
This overload opens system stores which are located in HKEY_CURRENT_USER registry branch only. To open a system store located in another branch of the registry (such as HKEY_LOCAL_MACHINE which is user-independent), use CertificateStore(String, CertStoreType, String, CryptoServiceProvider, RegistryStoreLocation) overload.
Examples
The example is available in CertificateStore topic.
See Also

Reference

CertificateStore Class
CertificateStore Overload
MailBee.Security Namespace


CertificateStore Constructor (String, CertStoreType, String, CryptoServiceProvider, RegistryStoreLocation)

CertificateStore Constructor (String, CertStoreType, String, CryptoServiceProvider, RegistryStoreLocation)
Opens an existing or creates a new store of certificates.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateStore(
    string storeName,
    CertStoreType storeType,
    string pfxPassword,
    CryptoServiceProvider csp,
    RegistryStoreLocation registryLocation
)
Public Sub New (
    storeName As String,
    storeType As CertStoreType,
    pfxPassword As String,
    csp As CryptoServiceProvider,
    registryLocation As RegistryStoreLocation
)

Parameters

storeName
Type: SystemString
The name of the certificate store or the filename if the store is a file.
storeType
Type: MailBee.SecurityCertStoreType
The type of the certificate store.
pfxPassword
Type: SystemString
PFX (.P12, PKCS #12) password if storeType is Pfx; otherwise, not used and can be a null reference (Nothing in Visual Basic).
csp
Type: MailBee.SecurityCryptoServiceProvider
A reference to CryptoServiceProvider instance descripting Cryptographic service provider (CSP) to be used for the given store, or a null reference (Nothing in Visual Basic) if the default CSP should be used. CSP is not used with PFX stores.
registryLocation
Type: MailBee.SecurityRegistryStoreLocation
Windows registry location of the system store if storeType is System; otherwise, not used and can be any RegistryStoreLocation value.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | storeName is a null reference (Nothing in Visual Basic) or an empty string while storeType is neither Memory nor PfxBytes.
MailBeeIOException | The specified PFX file can not be opened or read.
MailBeeCertificateStoreWin32Exception | Win32 returned an error during opening the certificate store.
Remarks

Only Memory stores can be created. Other stores can only be opened. It's possible, however, to create a memory store and then save it into a file using SaveToFile(String, CertStoreFileType, String) method. To create a new system store, use RegisterSystemStore(String, RegistryStoreLocation) method.

If you open a file store and then modify its contents, it won't be updated on disk until you save it back to the file. A system store, however, gets updated immediately in its registry location each time you call any method which modifies this store.

See Also

Reference

CertificateStore Class
CertificateStore Overload
MailBee.Security Namespace


CertificateStore Fields

CertificateStore Fields

The CertificateStore type exposes the following members.

Fields
Name | Description
IntermediateCA | Gets the name of the system certificate store containing certificates of intermediate certification authorities.
OtherPeople | Gets the name of the system certificate store containing certificates of other entities such as your address book members.
Personal | Gets the name of the system certificate store containing personal certificates.
RootCA | Gets the name of the system certificate store containing certificates of trusted root certification authorities.
Top
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.IntermediateCA Field

CertificateStoreIntermediateCA Field
Gets the name of the system certificate store containing certificates of intermediate certification authorities.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string IntermediateCA
Public Const IntermediateCA As String

Field Value

Type: String
Gets "CA" string.
Remarks

"CA" store corresponds to "Intermediate Certification Authorities" tab of Certificates dialog in Internet Explorer options.

The common use of this store is holding certificates of organizations which issue end-user certificates.

To open a system certificate store by its name, use CertificateStore(String, CertStoreType, String) constructor.

See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.OtherPeople Field

CertificateStoreOtherPeople Field
Gets the name of the system certificate store containing certificates of other entities such as your address book members.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string OtherPeople
Public Const OtherPeople As String

Field Value

Type: String
Gets "AddressBook" string.
Remarks

"AddressBook" store corresponds to "Other People" tab of Certificates dialog in Internet Explorer options.

The common use of this store with S/MIME is checking signatures fo e-mails you receive or encrypting e-mails you send.

To open a system certificate store by its name, use CertificateStore(String, CertStoreType, String) constructor.

See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.Personal Field

CertificateStorePersonal Field
Gets the name of the system certificate store containing personal certificates.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string Personal
Public Const Personal As String

Field Value

Type: String
Gets "MY" string.
Remarks

"MY" store corresponds to "Personal" tab of Certificates dialog in Internet Explorer options.

The common use of this store with S/MIME is signing e-mails you send or decrypting e-mails you receive.

To open a system certificate store by its name, use CertificateStore(String, CertStoreType, String) constructor.

See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.RootCA Field

CertificateStoreRootCA Field
Gets the name of the system certificate store containing certificates of trusted root certification authorities.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string RootCA
Public Const RootCA As String

Field Value

Type: String
Gets "Root" string.
Remarks

"Root" store corresponds to "Trusted Root Certification Authorities" tab of Certificates dialog in Internet Explorer options.

The common use of this store is holding certificates of organizations which issue end-user certificates.

To open a system certificate store by its name, use CertificateStore(String, CertStoreType, String) constructor.

See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore Methods

CertificateStore Methods

The CertificateStore type exposes the following members.

Methods
 | Name | Description
 | AddCertificate | Adds the specified certificate to the store.
 | AddCertificates | Adds all the certificates from the specified collection to the store.
 | DeleteCertificate | Removes the specified certificate from the store.
Public method | Dispose | Releases the resources associated with the current CertificateStore object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | FindCertificates | Searches the certificates in the store by the specified criteria.
 | GetAllCertificates | Creates and returns a collection of all the certificates contained in the certificate store.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | RegisterSystemStore | Registers a new system certificate store.
 | SaveToFile | Saves the certificate store into a file.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | UnregisterSystemStore | Unregisters an existing system certificate store.
Top
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.AddCertificate Method

CertificateStoreAddCertificate Method
Adds the specified certificate to the store.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AddCertificate(
    Certificate cert,
    bool overwrite
)
Public Function AddCertificate (
    cert As Certificate,
    overwrite As Boolean
) As Boolean

Parameters

cert
Type: MailBee.SecurityCertificate
The certificate that should be added.
overwrite
Type: SystemBoolean
Sets whether the same certificate (if it already exists in the store) should be overwritten or not.

Return Value

Type: Boolean
true if certificate was successfully added to the store; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | cert is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error on attempt to add the certificate to the store and ThrowExceptions is true.
Examples
This sample registers a new certificate store, reads a certificate from a file and adds this certificate to the newly created store.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

CertificateStore.RegisterSystemStore(@"TestStore", RegistryStoreLocation.CurrentUser);
CertificateStore store = new CertificateStore(@"TestStore", CertStoreType.System, null);
Certificate cert = new Certificate(@"C:\Temp\test.cer", CertFileType.Cer, null);
store.AddCertificate(cert, true);
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

CertificateStore.RegisterSystemStore("TestStore", RegistryStoreLocation.CurrentUser)
Dim store As CertificateStore = New CertificateStore("TestStore", CertStoreType.System, Nothing)
Dim cert As Certificate = New Certificate("C:\Temp\test.cer", CertFileType.Cer, Nothing)
store.AddCertificate(cert, True)
See Also

Reference

CertificateStore Class
MailBee.Security Namespace
CertificateStoreAddCertificates(CertificateCollection, Boolean)


CertificateStore.AddCertificates Method

CertificateStoreAddCertificates Method
Adds all the certificates from the specified collection to the store.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AddCertificates(
    CertificateCollection certs,
    bool overwrite
)
Public Function AddCertificates (
    certs As CertificateCollection,
    overwrite As Boolean
) As Boolean

Parameters

certs
Type: MailBee.SecurityCertificateCollection
The collection of the certificates to be added to the store.
overwrite
Type: SystemBoolean
Sets whether the same certificates should be overwritten if they already exist in the store.

Return Value

Type: Boolean
true if the certificates were successfully added to the store; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | certs is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error on attempt to add any of the certificates to the store and ThrowExceptions is true.
Remarks
If this method successfully added at least one certificate from the collection and then failed while adding the next certificate, those certificates which have already been added will remain in the store. In other words, adding multiple certificates is not a single transaction.
Examples
This sample creates a special store and fills it with the certificates belonging to user@domain.com entity and saves this store to disk.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class).
CertificateStore newStore = new CertificateStore("", CertStoreType.Memory, null);
CertificateStore myStore = new CertificateStore(CertificateStore.Personal, CertStoreType.System, null);
CertificateCollection coll = myStore.FindCertificates("user@domain.com", CertificateFields.EmailAddress);

newStore.AddCertificates(coll, false);
newStore.SaveToFile(@"C:\Temp\store.sst", CertStoreFileType.Sst, null);
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim newStore As CertificateStore = New CertificateStore("", CertStoreType.Memory, Nothing)
Dim myStore As CertificateStore = New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)
Dim coll As CertificateCollection = myStore.FindCertificates("user@domain.com", CertificateFields.EmailAddress)

newStore.AddCertificates(coll, False)
newStore.SaveToFile("C:\Temp\store.sst", CertStoreFileType.Sst, Nothing)
See Also

Reference

CertificateStore Class
MailBee.Security Namespace
MailBee.SecurityCertificateCollection
CertificateStoreAddCertificate(Certificate, Boolean)


CertificateStore.DeleteCertificate Method

CertificateStoreDeleteCertificate Method
Removes the specified certificate from the store.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool DeleteCertificate(
    Certificate cert
)
Public Function DeleteCertificate (
    cert As Certificate
) As Boolean

Parameters

cert
Type: MailBee.SecurityCertificate
The certificate that should be removed from the store.

Return Value

Type: Boolean
true if the specified certificate was successfully removed; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | cert is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error on attempt to remove the certificates from the store and ThrowExceptions is true.
Examples
This sample removes all certificates having the specified e-mail address from the store.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class).
CertificateStore store = new CertificateStore("TestStore", CertStoreType.System, null);
CertificateCollection coll = store.FindCertificates("user@domain.com", CertificateFields.EmailAddress);

foreach (Certificate cert in coll)
{
    store.DeleteCertificate(cert);
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim store As CertificateStore = New CertificateStore("TestStore", CertStoreType.System, Nothing)
Dim coll As CertificateCollection = store.FindCertificates("user@domain.com", CertificateFields.EmailAddress)

For Each cert As Certificate In coll
    store.DeleteCertificate(cert)
Next
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.Dispose Method

CertificateStoreDispose Method
Releases the resources associated with the current CertificateStore object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
The certificate store is an unmanaged resource, it's recommended to manually dispose it when you no longer need it.
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.FindCertificates Method

CertificateStoreFindCertificates Method
Searches the certificates in the store by the specified criteria.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateCollection FindCertificates(
    string substring,
    CertificateFields fields
)
Public Function FindCertificates (
    substring As String,
    fields As CertificateFields
) As CertificateCollection

Parameters

substring
Type: SystemString
The string to be searched in the specified fields of the certificates in the store.
fields
Type: MailBee.SecurityCertificateFields
The set of certificate fields where to perform the search.

Return Value

Type: CertificateCollection
A CertificateCollection of all matching certificates.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | substring is a null reference (Nothing in Visual Basic).
Remarks
Search is case-insensitive (ABC and abc are treated the same). For instance, if substring is John and the corresponding certificate field is "johndoe@company.com", this certificate will appear in the resulting collection.
Examples
The example is available in DeleteCertificate(Certificate) topic.
See Also

Reference

CertificateStore Class
MailBee.Security Namespace
MailBee.SecurityCertificateFields
MailBee.SecurityCertificateCollection


CertificateStore.GetAllCertificates Method

CertificateStoreGetAllCertificates Method
Creates and returns a collection of all the certificates contained in the certificate store.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateCollection GetAllCertificates()
Public Function GetAllCertificates As CertificateCollection

Return Value

Type: CertificateCollection
A CertificateCollection object containing all the certificates in the certificate store.
Remarks

The returned collection is not bound to the originating certificate store. For instance, when a certificate is removed from the returned collection, it will remain in the store. To remove a certificate from the store, use DeleteCertificate(Certificate) method.

Examples
The example is available in CertificateStore class documentation.
See Also

Reference

CertificateStore Class
MailBee.Security Namespace
CertificateStoreFindCertificates(String, CertificateFields)


CertificateStore.RegisterSystemStore Method

CertificateStoreRegisterSystemStore Method
Registers a new system certificate store.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static void RegisterSystemStore(
    string name,
    RegistryStoreLocation registryLocation
)
Public Shared Sub RegisterSystemStore (
    name As String,
    registryLocation As RegistryStoreLocation
)

Parameters

name
Type: SystemString
The system store name.
registryLocation
Type: MailBee.SecurityRegistryStoreLocation
The store location in the registry.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error on attempt to register a store.
Remarks
Use this method to create your own system stores.
Examples
The example is available in AddCertificate(Certificate, Boolean) topic.
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.SaveToFile Method

CertificateStoreSaveToFile Method
Saves the certificate store into a file.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SaveToFile(
    string filename,
    CertStoreFileType fileType,
    string pfxPassword
)
Public Function SaveToFile (
    filename As String,
    fileType As CertStoreFileType,
    pfxPassword As String
) As Boolean

Parameters

filename
Type: SystemString
The filename of the file to be saved.
fileType
Type: MailBee.SecurityCertStoreFileType
The format of the file store to be saved.
pfxPassword
Type: SystemString
PFX password to protect the store from unauthorized access, or a null reference (Nothing in Visual Basic) if fileType is not Pfx.

Return Value

Type: Boolean
true if the store was successfully saved to disk; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error on attempt to save the store to disk and ThrowExceptions is true.
Examples
The example is available in AddCertificates(CertificateCollection, Boolean) topic.
See Also

Reference

CertificateStore Class
MailBee.Security Namespace
MailBee.SecurityCertStoreFileType


CertificateStore.UnregisterSystemStore Method

CertificateStoreUnregisterSystemStore Method
Unregisters an existing system certificate store.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static void UnregisterSystemStore(
    string name,
    RegistryStoreLocation registryLocation
)
Public Shared Sub UnregisterSystemStore (
    name As String,
    registryLocation As RegistryStoreLocation
)

Parameters

name
Type: SystemString
The name of the existing system store.
registryLocation
Type: MailBee.SecurityRegistryStoreLocation
The store location in the registry.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | Win32 returned an error on attempt to register a store.
Remarks
Unregistering the store physically removes the store along with all the certificates.
Note Note
It's not recommended to unregister system stores unless they had been created by your applications. Unregistering a store which is used by the operating system may cause unpredictable results.
Examples
This sample registers a store, fills it with some certificates (copied from another store), and unregisters it.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class).
CertificateStore.RegisterSystemStore("TestStore", RegistryStoreLocation.CurrentUser);
CertificateStore newStore = new CertificateStore("TestStore", CertStoreType.System, null);
CertificateStore myStore = new CertificateStore(CertificateStore.Personal, CertStoreType.System, null);
CertificateCollection coll = myStore.FindCertificates("thawte", CertificateFields.EmailAddress);

newStore.AddCertificates(coll, false);
coll = newStore.GetAllCertificates();

foreach (Certificate cert in coll)
{
    Console.WriteLine(cert.IssuedTo);
    Console.WriteLine(cert.IssuedBy);
    Console.WriteLine(cert.EmailAddress);
    Console.WriteLine(cert.ValidToDate);
    Console.WriteLine("Has private key: " + cert.HasPrivateKey);
    Console.WriteLine("------------------------------");
}
CertificateStore.UnregisterSystemStore("TestStore", RegistryStoreLocation.CurrentUser);
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class).
CertificateStore.RegisterSystemStore("TestStore", RegistryStoreLocation.CurrentUser)
Dim newStore As CertificateStore = New CertificateStore("TestStore", CertStoreType.System, Nothing)
Dim myStore As CertificateStore = New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)
Dim coll As CertificateCollection = myStore.FindCertificates("thawte", CertificateFields.EmailAddress)

newStore.AddCertificates(coll, False)
coll = newStore.GetAllCertificates()

For Each cert As Certificate In coll
    Console.WriteLine(cert.IssuedTo)
    Console.WriteLine(cert.IssuedBy)
    Console.WriteLine(cert.EmailAddress)
    Console.WriteLine(cert.ValidToDate)
    Console.WriteLine("Has private key: " & cert.HasPrivateKey)
    Console.WriteLine("------------------------------")
Next
CertificateStore.UnregisterSystemStore("TestStore", RegistryStoreLocation.CurrentUser)
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore Properties

CertificateStore Properties

The CertificateStore type exposes the following members.

Properties
 | Name | Description
Public property | LastResult | Gets a numeric code of the last error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateStore.LastResult Property

CertificateStoreLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of the constants defined in ErrorCodes class.
See Also

Reference

CertificateStore Class
MailBee.Security Namespace
CertificateStoreThrowExceptions


CertificateStore.ThrowExceptions Property

CertificateStoreThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the object will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the object methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee.NET usage will still be thrown.

Typical example of such errors is passing invalid arguments to methods. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

See Also

Reference

CertificateStore Class
MailBee.Security Namespace


CertificateValidationFlags Enumeration

CertificateValidationFlags Enumeration
Defines flags indicating errors of certificate validation.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum CertificateValidationFlags
<FlagsAttribute>
Public Enumeration CertificateValidationFlags
Members
Member name | Value | Description
None | 0 | No errors.
IsNotTimeValid | 1 | This certificate or one of the certificates in the certificate chain is not time-valid.
IsNotTimeNested | 2 | Certificates in the chain are not properly time-nested.
IsRevoked | 4 | Trust for this certificate or one of the certificates in the chain has been revoked.
IsNotSignatureValid | 8 | The certificate or one of the certificates in the chain does not have a valid signature.
IsNotValidForUsage | 16 | The certificate or the chain is not valid in its proposed usage.
IsUntrustedRoot | 32 | The certificate or the chain is based on an untrusted root.
RevocationStatusUnknown | 64 | The revocation status of the certificate or one of the certificates in the chain is unknown.
IsCyclic | 128 | One of the certificates in the chain was issued by a certification authority which had certified the original certificate.
IsPartialChain | 65536 | The certificate chain is not complete.
IsNotTimeValidCtl | 131072 | A CTL used to create this chain was not time-valid.
IsNotSignatureValidCtl | 262144 | A CTL used to create this chain did not have a valid signature.
IsNotValidForUsageCtl | 524288 | A CTL used to create this chain is not valid for this usage.
NameMismatch | 16777216 | Certificate name mismatch.
All | 17760447 | All the flags listed above.
Remarks

Validate method returns CertificateValidationFlags value for the given certificate.

When checking S/MIME signatures of e-mail messages, you can use Verify(MailMessage, MessageVerificationFlags, CertificateStore) method which can perform complex verification of the message signature including validating its certificate.

When making SSL connections to mail servers, you can set AutoValidation property to tell MailBee to automatically validate the server certificate accordingly the specified criteria and throw MailBeeCertificateValidationException if the validation process fails for any of the criteria.

See Also

Reference

MailBee.Security Namespace
CertificateValidate
ClientServerCertificatesAutoValidation


CertStoreFileType Enumeration

CertStoreFileType Enumeration
Defines types of certificate store files.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum CertStoreFileType
Public Enumeration CertStoreFileType
Members
Member name | Value | Description
Sst | 1 | Serialized storage (.SST file). May contain certificates with public keys only.
P7b | 2 | PKCS #7 signed message (.P7B file). May contain certificates with public keys only.
Pfx | 3 | Personal Information Exchange (.PFX, PKCS #12, .P12 file). May contain certificates with public and private keys and can be protected with a password.
Remarks
To save a certificate store into a file of a certain type, use SaveToFile(String, CertStoreFileType, String) method.
See Also

Reference

MailBee.Security Namespace


CertStoreType Enumeration

CertStoreType Enumeration
Defines certificate store types.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum CertStoreType
Public Enumeration CertStoreType
Members
Member name | Value | Description
PublicFile | 8 | A file in SST or PKCS #7 (.P7B) format which contains certificates with public keys only.
System | 10 | Standard system store (stored in Windows registry, examples are Personal, OtherPeople, etc). May contain certificates with public and private keys.
Memory | 2 | Temporary memory storage. Often used to create a new store which can then be saved into a file. May contain certificates with public and private keys.
Pkcs7Bytes | 5 | A byte array in PKCS #7 (.P7B) format. Used with CertificateStore(Byte, CertStoreType, CryptoServiceProvider) overload.
SerializedBytes | 6 | A byte array in SST format. Used with CertificateStore(Byte, CertStoreType, CryptoServiceProvider) overload.
Ldap | 16 | A storage populated with certificates, CRLs, and CTLs obtained from the results of the query specified by an LDAP URL. To perform write operations for the store, the URL must specify a BASE query with no filter and a single attribute.
PfxFile | 17 | A file in PFX (Personal Information Exchange, PKCS #12) format which may contain certificates with public and private keys. PFX files can be protected with a password.
PfxBytes | 18 | A byte array in PFX format. All characteristics of PfxFile apply. To open a certificate store from PFX bytes array, use CertificateStore(Byte, String) constructor.
Remarks
To open a certificate store of a certain type, create CertificateStore object using CertificateStore(String, CertStoreType, String) constructor or its overloads.
See Also

Reference

MailBee.Security Namespace


ClientServerCertificates Class

ClientServerCertificates Class
Provides methods and properties for accessing client and server certificates which are used in order to establish secure SSL connection with a mail server.
Inheritance Hierarchy
SystemObject
MailBee.SecurityClientServerCertificates

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class ClientServerCertificates : IDisposable
Public Class ClientServerCertificates
    Implements IDisposable

The ClientServerCertificates type exposes the following members.

Constructors
 | Name | Description
Public method | ClientServerCertificates | Initializes a new instance of the ClientServerCertificates class
Top
Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the current ClientServerCertificates object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | AutoValidation | Gets or sets the flags against which the server certificate should be automatically validated.
Public property | CheckCertificateRevocation | Gets or sets whether the certificate revocation list is checked during authentication.
 | Client | Gets or sets the client certificate.
 | Server | Gets the server certificate.
Top
Remarks

You can use this class to assign the client certificate to be presented to the mail server during SSL handshakes, or to access the server certificate which becomes available to the client once SSL handshake is done, or both. Also, you can tell MailBee to automatically validate the server certificate against any of the available criteria and throw exception if the server certificate does not pass the test.

ClientServerCertificates instance is available through SmtpServer.SslCertificates, Pop3.SslCertificates and Imap.SslCertificates properties.

Note Note
To use this class, make sure MailBee.NET Security is licensed (MailBee.NET Objects full bundle does include the license).
Examples
This sample attempts to select a client certificate to be presented to the mail server, connects to the server (dedicated SSL connection, not STARTTLS), and automatically validates the server certificate. If the server certificate is invalid, the sample reports what exactly is wrong with the server certificate.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Security;

class Sample
{
    static void Main(string[] args)
    {
        Pop3 pop = new Pop3();

        // Start SSL handshake on "connecting to server" stage (dedicated port connection).
        // If you wish to use STARTTLS (regular port connection), select UseStartTls value
        // (port would be 110 and SSL handshake would occur later on StartTls or Login call).
        pop.SslMode = SslStartupMode.OnConnect;

        // Open Personal store of certificates, attempt to find the certificate containing
        // "john" in the email address or name, and present this certificate to the server.
        CertificateStore store = new CertificateStore(CertificateStore.Personal,
            CertStoreType.System, null);
        CertificateCollection certs = store.FindCertificates("john",
            CertificateFields.EmailAddress | CertificateFields.Name);
        store.Dispose();
        if (certs.Count > 0)
        {
            pop.SslCertificates.Client = certs[0];
            Console.WriteLine("Client certificate set.");
        }
        else
        {
            // Most servers do not require clients to authenticate themselves via SSL
            // certificates so that anonymous SSL connection usually works too unless
            // your server is an exception.
            Console.WriteLine("Client certificate not set, the connection will be anonymous.");
        }

        // Tell MailBee to automatically validate the server certificate and
        // throw exception if any of the available conditions is not met.
        pop.SslCertificates.AutoValidation = CertificateValidationFlags.All;
        try
        {
            pop.Connect("mail.domain.com", 995);    // 995 is dedicated S/POP3 port.
            pop.Disconnect();
        }
        catch (MailBeeCertificateValidationException e)
        {
            // Server certificate is not valid.
            Console.WriteLine(e.Message);

            // Build a string which lists the names of all the flags
            // the certificate validation process has failed for.
            string reasons = string.Empty;
            CertificateValidationFlags flags = e.Status;
            int mask = 1;
            while (flags > 0)
            {
                CertificateValidationFlags flag = flags & (CertificateValidationFlags)mask;
                if (flag != CertificateValidationFlags.None)
                {
                    if (reasons.Length > 0)
                    {
                        reasons += ", ";
                    }
                    reasons += flag.ToString();
                    flags &= (CertificateValidationFlags)~mask;
                }
                mask <<= 1;
            }

            Console.WriteLine("Reasons: " + reasons);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Security

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim pop As Pop3 = New Pop3

        ' Start SSL handshake on "connecting to server" stage (dedicated port connection).
        ' If you wish to use STARTTLS (regular port connection), select UseStartTls value
        ' (port would be 110 and SSL handshake would occur later on StartTls or Login call).
        pop.SslMode = SslStartupMode.OnConnect

        ' Open Personal store of certificates, attempt to find the certificate containing
        ' "john" in the email address or name, and present this certificate to the server.
        Dim store As CertificateStore = New CertificateStore(CertificateStore.Personal, _
                         CertStoreType.System, Nothing)
        Dim certs As CertificateCollection = store.FindCertificates("john", _
                            CertificateFields.EmailAddress Or CertificateFields.Name)
        store.Dispose()
        If certs.Count > 0 Then
            pop.SslCertificates.Client = certs(0)
            Console.WriteLine("Client certificate set.")
        Else
            ' Most servers do not require clients to authenticate themselves via SSL
            ' certificates so that anonymous SSL connection usually works too unless
            ' your server is an exception.
            Console.WriteLine("Client certificate not set, the connection will be anonymous.")
        End If

        ' Tell MailBee to automatically validate the server certificate and
        ' throw exception if any of the available conditions is not met.
        pop.SslCertificates.AutoValidation = CertificateValidationFlags.All
        Try
            pop.Connect("mail.domain.com", 995) ' 995 is dedicated S/POP3 port.
            pop.Disconnect()
        Catch e As MailBeeCertificateValidationException
            ' Server certificate is not valid.
            Console.WriteLine(e.Message)

            ' Build a string which lists the names of all the flags
            ' the certificate validation process has failed for.
            Dim reasons As String = String.Empty
            Dim flags As CertificateValidationFlags = e.Status
            Dim mask As Integer = 1
            While flags > 0
                Dim flag As CertificateValidationFlags = flags & CType(mask, CertificateValidationFlags)
                If flag <> CertificateValidationFlags.None Then
                    If reasons.Length > 0 Then
                        reasons &= ", "
                    End If
                    reasons &= flag.ToString()
                    flags = flags And CType(Not (mask), CertificateValidationFlags)
                End If
                mask <<= 1
            End While

            Console.WriteLine("Reasons: " & reasons)
        End Try
    End Sub
End Class
See Also

Reference

MailBee.Security Namespace
MailBee.SecurityCertificate


ClientServerCertificates Constructor

ClientServerCertificates Constructor
Initializes a new instance of the ClientServerCertificates class

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ClientServerCertificates()
Public Sub New
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace


ClientServerCertificates Methods

ClientServerCertificates Methods

The ClientServerCertificates type exposes the following members.

Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the current ClientServerCertificates object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace


ClientServerCertificates.Dispose Method

ClientServerCertificatesDispose Method
Releases the resources associated with the current ClientServerCertificates object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace


ClientServerCertificates Properties

ClientServerCertificates Properties

The ClientServerCertificates type exposes the following members.

Properties
 | Name | Description
 | AutoValidation | Gets or sets the flags against which the server certificate should be automatically validated.
Public property | CheckCertificateRevocation | Gets or sets whether the certificate revocation list is checked during authentication.
 | Client | Gets or sets the client certificate.
 | Server | Gets the server certificate.
Top
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace


ClientServerCertificates.AutoValidation Property

ClientServerCertificatesAutoValidation Property
Gets or sets the flags against which the server certificate should be automatically validated.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CertificateValidationFlags AutoValidation { get; set; }
Public Property AutoValidation As CertificateValidationFlags
    Get
    Set

Property Value

Type: CertificateValidationFlags
A combination of one or more CertificateValidationFlags values. The default value is None.
Remarks

If this property value is not None and SSL handshake starts, MailBee will automatically validate the server certificate against all the flags specified.

If the server certificate fails to pass validation against any of the flags specified, MailBee closes the connection and throws MailBeeCertificateValidationException.

Note Note
This feature does not work in UWP apps. Use SocketCreating event instead (similar event also exists for Pop3 and Smtp classes).
Examples
The example is available in ClientServerCertificates topic.
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace
CertificateValidate
ClientServerCertificatesServer


ClientServerCertificates.CheckCertificateRevocation Property

ClientServerCertificatesCheckCertificateRevocation Property
Gets or sets whether the certificate revocation list is checked during authentication.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool CheckCertificateRevocation { get; set; }
Public Property CheckCertificateRevocation As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the certificate revocation list is checked during authentication; otherwise, false. The default value is false.
Remarks
MailBee passes this value to AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean) method as checkCertificateRevocation parameter. Enabling this check can improve security but it comes at a cost of significant delays during authentication against some servers (up to 15 seconds).
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace


ClientServerCertificates.Client Property

ClientServerCertificatesClient Property
Gets or sets the client certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate Client { get; set; }
Public Property Client As Certificate
    Get
    Set

Property Value

Type: Certificate
A Certificate object representing the client's certificate if specified by the application. The default value is a null reference (Nothing in Visual Basic).
Remarks
This certificate represents the client during the SSL handshake. If this certificate is not valid or missing, the server may break the connection. Most servers, however, do not require the client to present a certificate.
Examples
The example is available in ClientServerCertificates topic.
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace
ClientServerCertificatesServer


ClientServerCertificates.Server Property

ClientServerCertificatesServer Property
Gets the server certificate.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate Server { get; }
Public ReadOnly Property Server As Certificate
    Get

Property Value

Type: Certificate
A Certificate object representing the certificate that was received from the server once SSL handshake was completed, or a null reference (Nothing in Visual Basic) if SSL handshake is not yet completed or not connected to the server. The default value is a null reference.
Remarks
To tell MailBee to validate the server certificate automatically during SSL handshake, use AutoValidation property. To validate it manulally, use Validate method of Server object once SSL handshake is done. You can also subscribe to TlsStarted event published by mailer components such as Pop3 to catch the very moment when the SSL handshake is done.
Examples
The example is available in ClientServerCertificates topic.
See Also

Reference

ClientServerCertificates Class
MailBee.Security Namespace
ClientServerCertificatesClient


CryptoServiceProvider Class

CryptoServiceProvider Class
Provides methods and properties for accessing or examining Cryptographic Service Providers (CSPs) registered in the system.
Inheritance Hierarchy
SystemObject
MailBee.SecurityCryptoServiceProvider

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class CryptoServiceProvider : IDisposable
Public Class CryptoServiceProvider
    Implements IDisposable

The CryptoServiceProvider type exposes the following members.

Constructors
 | Name | Description
Public method | CryptoServiceProvider | Creates a new instance of CryptoServiceProvider class.
Public method | CryptoServiceProvider(String) | Creates a new instance of CryptoServiceProvider class.
Top
Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the current CryptoServiceProvider object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetKeyContainer | Gets the name of the key container.
 | GetProviderName | Gets the name of the CSP represented by this object.
 | GetProviderVersion | Gets the version of the CSP represented by this object.
 | GetSupportedAlgorithms | Gets the array of all cryptographic algorithms supported by the CSP.
 | GetSystemProviders | Gets the list of all CPSs that are registered in the operating system.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Fields
Name | Description
Base | Gets Microsoft Base Cryptographic Provider name.
Enhanced | Gets Microsoft Enhanced Cryptographic Provider name.
Strong | Gets Microsoft Strong Cryptographic Provider name.
Top
Properties
 | Name | Description
Public property | LastResult | Gets a numeric code of the last error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks
CSP is an independent software module which performs cryptographic algorithms for authentication, encoding and encryption procedures. Each CSP supports its own set of algorithms.
Note Note
MailBee handles CSPs automatically. Usually there is no need to use CryptoServiceProvider class unless you need to use specific CSP.
Examples
This sample displays the details of the default CSP to be used by MailBee, then changes the default CSP and displays its details, then creates a new CSP and displays its details.
C#
VB
Copy
// To use the code below, import these namespace at the top of your code
using System;
using MailBee.Security;

// The actual code (put it into a method of your class)

Smime objSmime = new Smime();

// Use default CSP.
Console.WriteLine(objSmime.Provider.GetProviderName());
Console.WriteLine(objSmime.Provider.GetProviderVersion());
Console.WriteLine(objSmime.Provider.GetKeyContainer());
Console.WriteLine("-----------------------------------");

// Set new default for CSP.
objSmime.Provider = new CryptoServiceProvider(CryptoServiceProvider.Enhanced);

// Use the new default CSP.
Console.WriteLine(objSmime.Provider.GetProviderName());
Console.WriteLine(objSmime.Provider.GetProviderVersion());
Console.WriteLine(objSmime.Provider.GetKeyContainer());
Console.WriteLine("-----------------------------------");

// Set new default for CSP.
CryptoServiceProvider strongProvider = new CryptoServiceProvider(CryptoServiceProvider.Strong);
objSmime.Provider = strongProvider;

// Use another CSP.
Console.WriteLine(objSmime.Provider.GetProviderName());
Console.WriteLine(objSmime.Provider.GetProviderVersion());
Console.WriteLine(objSmime.Provider.GetKeyContainer());
Console.WriteLine("-----------------------------------");
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class)

Dim objSmime As New Smime

' Use default CSP.
Console.WriteLine(objSmime.Provider.GetProviderName())
Console.WriteLine(objSmime.Provider.GetProviderVersion())
Console.WriteLine(objSmime.Provider.GetKeyContainer())
Console.WriteLine("-----------------------------------")

' Set new default for CSP.
objSmime.Provider = New CryptoServiceProvider(CryptoServiceProvider.Enhanced)

' Use the new default CSP.
Console.WriteLine(objSmime.Provider.GetProviderName())
Console.WriteLine(objSmime.Provider.GetProviderVersion())
Console.WriteLine(objSmime.Provider.GetKeyContainer())
Console.WriteLine("-----------------------------------")

' Set new default for CSP.
Dim strongProvider As New CryptoServiceProvider(CryptoServiceProvider.Strong)
objSmime.Provider = strongProvider

' Use another CSP.
Console.WriteLine(objSmime.Provider.GetProviderName())
Console.WriteLine(objSmime.Provider.GetProviderVersion())
Console.WriteLine(objSmime.Provider.GetKeyContainer())
Console.WriteLine("-----------------------------------")
See Also

Reference

MailBee.Security Namespace


CryptoServiceProvider Constructor

CryptoServiceProvider Constructor
Overload List
 | Name | Description
Public method | CryptoServiceProvider | Creates a new instance of CryptoServiceProvider class.
Public method | CryptoServiceProvider(String) | Creates a new instance of CryptoServiceProvider class.
Top
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider Constructor

CryptoServiceProvider Constructor
Creates a new instance of CryptoServiceProvider class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CryptoServiceProvider()
Public Sub New
Remarks
This overload creates a new instance of CryptoServiceProvider class which represents Base CSP.
See Also

Reference

CryptoServiceProvider Class
CryptoServiceProvider Overload
MailBee.Security Namespace


CryptoServiceProvider Constructor (String)

CryptoServiceProvider Constructor (String)
Creates a new instance of CryptoServiceProvider class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CryptoServiceProvider(
    string name
)
Public Sub New (
    name As String
)

Parameters

name
Type: SystemString
The name of the Cryptographic Service Provider to be represented by this instance.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
MailBeeCryptoProviderWin32Exception | An error occurred and ThrowExceptions is true.
Remarks
CryptoServiceProvider class provides several string constants which contain names of most widely used CSPs:
  • Base
  • Strong
  • Enhanced
GetSystemProviders method can be used to obtain the list of all CSPs supported by the operating system.
See Also

Reference

CryptoServiceProvider Class
CryptoServiceProvider Overload
MailBee.Security Namespace


CryptoServiceProvider Fields

CryptoServiceProvider Fields

The CryptoServiceProvider type exposes the following members.

Fields
Name | Description
Base | Gets Microsoft Base Cryptographic Provider name.
Enhanced | Gets Microsoft Enhanced Cryptographic Provider name.
Strong | Gets Microsoft Strong Cryptographic Provider name.
Top
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.Base Field

CryptoServiceProviderBase Field
Gets Microsoft Base Cryptographic Provider name.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string Base
Public Const Base As String

Field Value

Type: String
Remarks
This is the default CSP used by MailBee.
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace
CryptoServiceProviderCryptoServiceProvider(String)


CryptoServiceProvider.Enhanced Field

CryptoServiceProviderEnhanced Field
Gets Microsoft Enhanced Cryptographic Provider name.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string Enhanced
Public Const Enhanced As String

Field Value

Type: String
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace
CryptoServiceProviderCryptoServiceProvider(String)


CryptoServiceProvider.Strong Field

CryptoServiceProviderStrong Field
Gets Microsoft Strong Cryptographic Provider name.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public const string Strong
Public Const Strong As String

Field Value

Type: String
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace
CryptoServiceProviderCryptoServiceProvider(String)


CryptoServiceProvider Methods

CryptoServiceProvider Methods

The CryptoServiceProvider type exposes the following members.

Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the current CryptoServiceProvider object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetKeyContainer | Gets the name of the key container.
 | GetProviderName | Gets the name of the CSP represented by this object.
 | GetProviderVersion | Gets the version of the CSP represented by this object.
 | GetSupportedAlgorithms | Gets the array of all cryptographic algorithms supported by the CSP.
 | GetSystemProviders | Gets the list of all CPSs that are registered in the operating system.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.Dispose Method

CryptoServiceProviderDispose Method
Releases the resources associated with the current CryptoServiceProvider object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.GetKeyContainer Method

CryptoServiceProviderGetKeyContainer Method
Gets the name of the key container.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetKeyContainer()
Public Function GetKeyContainer As String

Return Value

Type: String
The key container string of the CSP if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeCryptoProviderWin32Exception | An error occurred and ThrowExceptions is true.
Remarks
The name of the current user is usually used as a key container name.
Examples
The example is available in CryptoServiceProvider topic.
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.GetProviderName Method

CryptoServiceProviderGetProviderName Method
Gets the name of the CSP represented by this object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetProviderName()
Public Function GetProviderName As String

Return Value

Type: String
The name of the CSP if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeCryptoProviderWin32Exception | An error occurred and ThrowExceptions is true.
Examples
The example is available in CryptoServiceProvider topic.
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.GetProviderVersion Method

CryptoServiceProviderGetProviderVersion Method
Gets the version of the CSP represented by this object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetProviderVersion()
Public Function GetProviderVersion As String

Return Value

Type: String
The version string of the CSP if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeCryptoProviderWin32Exception | An error occurred and ThrowExceptions is true.
Examples
The example is available in CryptoServiceProvider topic.
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.GetSupportedAlgorithms Method

CryptoServiceProviderGetSupportedAlgorithms Method
Gets the array of all cryptographic algorithms supported by the CSP.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Algorithm[] GetSupportedAlgorithms()
Public Function GetSupportedAlgorithms As Algorithm()

Return Value

Type: Algorithm
A reference to the array of Algorithm objects representing all algorithms supported by this CSP if succeeded; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeCryptoProviderWin32Exception | An error occurred and ThrowExceptions is true.
Examples
The example is available in EncryptionAlgorithm topic.
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.GetSystemProviders Method

CryptoServiceProviderGetSystemProviders Method
Gets the list of all CPSs that are registered in the operating system.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static string[] GetSystemProviders()
Public Shared Function GetSystemProviders As String()

Return Value

Type: String
A reference to the array of string names of all CSPs supported by the operating system.
Examples
This sample displays the names of all supported CSPs.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee.Security;

// The actual code (put it into a method of your class).
string[] cryptoProviderNames = CryptoServiceProvider.GetSystemProviders();

foreach (string name in cryptoProviderNames)
{
    Console.WriteLine(name);
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim cryptoProviderNames As String() = CryptoServiceProvider.GetSystemProviders()

For Each name As String In cryptoProviderNames
    Console.WriteLine(name)
Next
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace
CryptoServiceProviderCryptoServiceProvider(String)


CryptoServiceProvider Properties

CryptoServiceProvider Properties

The CryptoServiceProvider type exposes the following members.

Properties
 | Name | Description
Public property | LastResult | Gets a numeric code of the last error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


CryptoServiceProvider.LastResult Property

CryptoServiceProviderLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is the one of the constants defined in ErrorCodes class.
See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace
CryptoServiceProviderThrowExceptions


CryptoServiceProvider.ThrowExceptions Property

CryptoServiceProviderThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the object will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the object methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee.NET usage will still be thrown.

Typical example of such errors is passing invalid arguments to methods. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

See Also

Reference

CryptoServiceProvider Class
MailBee.Security Namespace


DomainKeys Class

DomainKeys Class
Provides methods for signing e-mails with DomainKeys and DKIM signatures and verifying signatures of incoming e-mails.
Inheritance Hierarchy
SystemObject
MailBee.SecurityDomainKeys

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DomainKeys
Public Class DomainKeys

The DomainKeys type exposes the following members.

Constructors
 | Name | Description
Public method | DomainKeys | Initializes a new instance of DomainKeys class.
Public method | DomainKeys(Boolean) | Initializes a new instance of DomainKeys class for use in web applications.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Sign(MailMessage, String, Byte, String) | Signs a mail message with DomainKeys and DKIM signatures.
Public method | Sign(MailMessage, String, Byte, String, DomainKeysTypes) | Signs a mail message with DomainKeys and/or DKIM signatures.
 | Sign(MailMessage, String, String, Boolean, String) | Signs a mail message with DomainKeys and DKIM signatures.
Public method | Sign(MailMessage, String, String, Boolean, String, DomainKeysTypes) | Signs a mail message with DomainKeys and/or DKIM signatures.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Verify(MailMessage, Smtp) | Verifies the DomainKeys and DKIM signatures of the mail message.
 | Verify(MailMessage, Smtp, Header) | Verifies the specified DomainKeys and/or DKIM signature of the mail message.
Public method | Verify(MailMessage, Smtp, DomainKeysTypes) | Verifies the DomainKeys and/or DKIM signatures of the mail message.
Public method | VerifyAsync(MailMessage, Smtp) | async/await version of Verify(MailMessage, Smtp).
Public method | VerifyAsync(MailMessage, Smtp, Header) | async/await version of Verify(MailMessage, Smtp, Header).
Public method | VerifyAsync(MailMessage, Smtp, DomainKeysTypes) | async/await version of Verify(MailMessage, Smtp, DomainKeysTypes).
Top
Properties
 | Name | Description
Public property | LastResult | Gets a numeric code of the last error.
 | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks
This class serves two purposes:
  • Signing e-mails to be sent out with DomainKeys (and/or DKIM) signature. The domain you're sending from (i.e. company.com if the From: address is j.doe@company.com) should have valid DomainKeys DNS TXT records containing the public key of your domain (this record should be placed not directly for sending domain but rather for its sub-domain called selector). The e-mails are signed with the private key for this domain. You can use Sign(MailMessage, String, String, Boolean, String) method and its overloads to sign messages with your private key. This method also accepts selector parameter so that you can use any name for selector sub-domain. For instance, Gmail currently uses "gamma" as selector value so that the entire DomainKeys domain name is "gamma._domainkey.gmail.com" where "._domainkey." suffix is predefined by DomainKeys standard. It's important to understand there can be no actual host under that name, it's just a DNS record.
  • Verifying DomainKeys (and/or DKIM) signatures of e-mails you receive. This involves using Smtp component for retrieving DomainKeys DNS record of the domain which sent the e-mail message in question, extracting the public key from that DNS record, and testing whether the signature matches that public key. No special DNS records are required on the receiving domain. Thus, you can always verify DomainKeys signatures regardless whether your domain has DomainKeys DNS record or not.
Note Note
In many cases, you can use DomainKeysSign(Boolean, String, String, Boolean, String, DomainKeysTypes) and DomainKeysVerify methods of MailMessage class to deal with DomainKeys and DKIM signatures. They are easier to use than DomainKeys class and do not require you to supply Smtp object.

If your domain does not have the necessary DNS TXT record holding DomainKeys data, you need to create one or contact your server administrator on this matter. You can create a public/private key pair with a tool such as OpenSSL. With OpenSSL, be sure to set the private key length to 1024 bits or more (DKIM itself does work with weaker keys but some providers like Gmail will not accept them). See RFC 4870 for more information on creating these keys.

Note Note
This class supports classic DomainKeys (DK) and newer DKIM technology. DK is always supported while DKIM support may require the system to support SHA256 algorithm. In case of a FIPS-compliant system, you should enable FipsMode and make sure you're using MailBee.NET.dll for .NET 4.0+. Read more on on SHA256 availability in DomainKeysVerifyResult topic.

Although DK and DKIM are different technologies, DKIM uses the same DNS records, public/private keys and selectors as DK. Thus, checking both DK and DKIM signatures won't force Verify(MailMessage, Smtp) method to send two DNS queries (for DK and DKIM). Only a single query regarding DomainKeys record will be made.

Examples
General examples are available in Sign(MailMessage, String, String, Boolean, String) and Verify(MailMessage, Smtp) topics. Another Sign(MailMessage, String, Byte, String) example shows advanced usage of signing.
See Also

Reference

MailBee.Security Namespace


DomainKeys Constructor

DomainKeys Constructor
Overload List
 | Name | Description
Public method | DomainKeys | Initializes a new instance of DomainKeys class.
Public method | DomainKeys(Boolean) | Initializes a new instance of DomainKeys class for use in web applications.
Top
See Also

Reference

DomainKeys Class
MailBee.Security Namespace


DomainKeys Constructor

DomainKeys Constructor
Initializes a new instance of DomainKeys class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DomainKeys()
Public Sub New
Remarks
This overload should not be used for web applications. ASP.NET web applications must use DomainKeys(Boolean) overload.
See Also

Reference

DomainKeys Class
DomainKeys Overload
MailBee.Security Namespace


DomainKeys Constructor (Boolean)

DomainKeys Constructor (Boolean)
Initializes a new instance of DomainKeys class for use in web applications.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DomainKeys(
    bool isWebApp
)
Public Sub New (
    isWebApp As Boolean
)

Parameters

isWebApp
Type: SystemBoolean
Must be true if your application is a web (ASP.NET) application. Otherwise, false.
Remarks
Web applications use CryptoAPI in a different way. Thus, this overload allows you to specify if your code is a web application.
See Also

Reference

DomainKeys Class
DomainKeys Overload
MailBee.Security Namespace


DomainKeys Methods

DomainKeys Methods

The DomainKeys type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | Sign(MailMessage, String, Byte, String) | Signs a mail message with DomainKeys and DKIM signatures.
Public method | Sign(MailMessage, String, Byte, String, DomainKeysTypes) | Signs a mail message with DomainKeys and/or DKIM signatures.
 | Sign(MailMessage, String, String, Boolean, String) | Signs a mail message with DomainKeys and DKIM signatures.
Public method | Sign(MailMessage, String, String, Boolean, String, DomainKeysTypes) | Signs a mail message with DomainKeys and/or DKIM signatures.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Verify(MailMessage, Smtp) | Verifies the DomainKeys and DKIM signatures of the mail message.
 | Verify(MailMessage, Smtp, Header) | Verifies the specified DomainKeys and/or DKIM signature of the mail message.
Public method | Verify(MailMessage, Smtp, DomainKeysTypes) | Verifies the DomainKeys and/or DKIM signatures of the mail message.
Public method | VerifyAsync(MailMessage, Smtp) | async/await version of Verify(MailMessage, Smtp).
Public method | VerifyAsync(MailMessage, Smtp, Header) | async/await version of Verify(MailMessage, Smtp, Header).
Public method | VerifyAsync(MailMessage, Smtp, DomainKeysTypes) | async/await version of Verify(MailMessage, Smtp, DomainKeysTypes).
Top
See Also

Reference

DomainKeys Class
MailBee.Security Namespace


DomainKeys.Sign Method

DomainKeysSign Method
Overload List
 | Name | Description
 | Sign(MailMessage, String, Byte, String) | Signs a mail message with DomainKeys and DKIM signatures.
Public method | Sign(MailMessage, String, Byte, String, DomainKeysTypes) | Signs a mail message with DomainKeys and/or DKIM signatures.
 | Sign(MailMessage, String, String, Boolean, String) | Signs a mail message with DomainKeys and DKIM signatures.
Public method | Sign(MailMessage, String, String, Boolean, String, DomainKeysTypes) | Signs a mail message with DomainKeys and/or DKIM signatures.
Top
See Also

Reference

DomainKeys Class
MailBee.Security Namespace


DomainKeys.Sign Method (MailMessage, String[], Byte[], String)

DomainKeysSign Method (MailMessage, String, Byte, String)
Signs a mail message with DomainKeys and DKIM signatures.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Sign(
    MailMessage msg,
    string[] headersToSign,
    byte[] privateKey,
    string selector
)
Public Function Sign (
    msg As MailMessage,
    headersToSign As String(),
    privateKey As Byte(),
    selector As String
) As MailMessage

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be signed.
headersToSign
Type: SystemString
The array of the names of the headers to be included in the signature, or a null reference (Nothing in Visual Basic) if all the message headers should be included in the signature.
privateKey
Type: SystemByte
The binary contents of the DomainKeys/DKIM private key.
selector
Type: SystemString
The prefix of the sub-domain serving DomainKeys/DKIM for the sender domain.

Return Value

Type: MailMessage
The signed mail message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or privateKey or selector is a null reference (Nothing in Visual Basic) or the message to be signed does not include the header specifying the sender (Sender or From or X-Sender header) or headersToSign array (if not null) does not list the name of that header or the sender's e-mail address domain is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This methods and its overloads are for advanced DomainKeys/DKIM signing. In most cases, you can choose DomainKeysSign(Boolean, String, String, Boolean, String, DomainKeysTypes) method which is easier to use (although not so flexible). Moreover, in ideal case it should be your your mail server's job to sign outgoing e-mails with DomainKeys/DKIM signatures. Use MailBee only if you cannot enable this feature on your mail server.

To sign a message with DomainKeys/DKIM signatures, you must have a private key. For instance, you can create it with OpenSSL utility (see DomainKeys topic for more information). The key data is actually the bytes retrieved from base64 decoding of the key file. Thus, if you have a key file, you can directly use Sign(MailMessage, String, String, Boolean, String) overload.

Note Note
When composing and sending a new message, no headers get changed after the message had been signed and the signature remains valid. See Sign(MailMessage, String, String, Boolean, String) topic for a simple code sample. If you, however, sign an existing message (for instance, forwarding a message previously received from a POP3 server), then read the below on how to correctly create the signature.

DK/DKIM standard requires the message to be signed must have Sender or From or X-Sender header and the e-mail address in that header must contain non-empty domain part. You can include all the headers into the signature (passing a null reference as headersToSign value) so that any change in the headers the message originally had would make the signature invalid. In this case, you must set all the headers prior to signing the message and make sure MailBee won't change these headers during sending.

Alternatively, you may include only certain headers into the signature (at least Sender or From) so that other headers can be changed. This is useful if you want to make sure the signature won't appear invalid when some headers get changed after the message has been signed. Typical case is when the mail server alters the headers of the signed message (changes Date, Message-ID or other headers).

In other words, make sure that all headers listed in the signature have not changed their value after signing. To do this, either do not list these headers in the signature omitting them in headersToSign array or add these headers to the message AFTER it has been signed. Adding new headers does not invalidate the signature, while changing the existing headers does.

In the sample code to this topic, we take care of Date and Message-ID because we sign an existing message, not a new one. Thus, Date and Message-ID may already be present in the message being signed. Then, when MailBee sends the message, it by default sets Date and Message-ID to new values and this action makes the signature invalid. Four ways to prevent this:

  1. Set Date and Message-ID manually BEFORE signing and suppress automatic setting of these values by MailBee during sending. The sample code to this topic uses this method.
  2. Simply clear Date and Message-ID prior to signing. This way, Date and Message-ID headers won't be included into the signature at all and thus automatic setting of these headers by MailBee during sending won't invalidate the signature. The recommended and the easiest method.
  3. Sign only certain headers of the message (using headersToSign parameter). In this case, if Message-ID and Date headers are not included into the signature and you are free to modify them as you wish. Use this method if your mail server may change some headers and for some reason the message being signed already has these headers (i.e. you can't add them AFTER signing).
  4. Just suppress automatic setting of Message-ID and Date headers by MailBee during sending. In this case, the message being sent will retain the original Message-ID and Date values. This approach is not recommended because any e-mail ever sent should have unique Message-ID and having two messages with same Message-ID may cause some mail systems to think that such messages are duplicates.

If you want to sign empty headers as well (to avoid tampering them), set [!:KeepEmptyHeaders] property of Builder object to true.

To make MailBee automatically DK/DKIM sign all outgoing e-mail messages created from certain MailMessage instance, call SetDomainKeysSignOnSend(Boolean, Boolean, String, String, Boolean, String, DomainKeysTypes) method of Builder object.

Note Note
Be sure to enable FipsMode if the current system is FIPS-compliant.
Examples
This console sample loads a message from file, signs it with DomainKeys signature (DomainKeys private key is taken from a file), and sends it out. Date and Message-ID headers are assigned BEFORE signing because they may already exist in the loaded message and thus would be included in the signature. Later, when the message gets sent, they would be set automatically and thus the signature would become invalid. We overcome this by manual settings of these headers before signing and disabling their automatic setting at the moment of sending.
Note Note
Alternatively, we could simply clear Date and Message-ID prior to signing to prevent inclusion of these headers into the signature.
C#
VB
Copy
using System;
using System.IO;
using MailBee;
using MailBee.Mime;
using MailBee.Security;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file.
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\msg.eml");

        // Set new values of Date and Message-ID. These values will be included
        // into the signature.
        msg.Date = DateTime.Now;
        msg.SetUniqueMessageID(null);

        // Here we load the private key from file only to demonstrate
        // how to use Sign method with binary array. We could simply use
        // another overload and pass a filename.
        byte[] privateKey = null;
        using (Stream stream = new FileStream(@"C:\Temp\private.der", FileMode.Open, FileAccess.Read))
        {
            privateKey = new byte[stream.Length];
            stream.Read(privateKey, 0, privateKey.Length);
        }

        // We will send the message with this object.
        Smtp mailer = new Smtp();

        // Sign the message and assign the signed message for sending.
        // We assume "dk" is sub-domain for which DomainKeys DNS record of the
        // sending domain is defined. I.e. if the sending domain is company.com
        // (email is sent from "someone@company.com"), then DNS records of
        // "dk._domainkey.company.com" domain must contain DomainKeys info.
        // "._domainkey." suffix is required by DomainKeys standard.
        DomainKeys dk = new DomainKeys();
        mailer.Message = dk.Sign(msg, null, privateKey, "dk");

        // Suppress automatic setting of Date and Message-ID during sending.
        mailer.Message.Builder.SetDateOnSend = false;
        mailer.Message.Builder.SetMessageIDOnSend = false;

        // Send the message via SMTP server (authentication is not used in this sample).
        mailer.SmtpServers.Add("mail.company.com");
        mailer.Send();
    }
}
Imports System
Imports System.IO
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security
Imports MailBee.SmtpMail

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file.
        Dim msg As New MailMessage
        msg.LoadMessage("C:\Docs\msg.eml")

        ' Set new values of Date and Message-ID. These values will be included
        ' into the signature.
        msg.Date = DateTime.Now
        msg.SetUniqueMessageID(Nothing)

        ' Here we load the private key from file only to demonstrate
        ' how to use Sign method with binary array. We could simply use
        ' another overload and pass a filename.
        Dim privateKey As Byte()
        Dim stream As stream
        Try
            stream = New FileStream("C:\Temp\private.der", FileMode.Open, FileAccess.Read)
            stream.Read(privateKey, 0, privateKey.Length)
        Finally
            If Not stream Is Nothing Then
                stream.Close()
            End If
        End Try

        ' We will send the message with this object.
        Dim mailer As New Smtp

        ' Sign the message and assign the signed message for sending.
        ' We assume "dk" is sub-domain for which DomainKeys DNS record of the
        ' sending domain is defined. I.e. if the sending domain is company.com
        ' (email is sent from "someone@company.com"), then DNS records of
        ' "dk._domainkey.company.com" domain must contain DomainKeys info.
        ' "._domainkey." suffix is required by DomainKeys standard.
        Dim dk As New DomainKeys
        mailer.Message = dk.Sign(msg, Nothing, privateKey, "dk")

        ' Suppress automatic setting of Date and Message-ID during sending.
        mailer.Message.Builder.SetDateOnSend = False
        mailer.Message.Builder.SetMessageIDOnSend = False

        ' Send the message via SMTP server (authentication is not used in this sample).
        mailer.SmtpServers.Add("mail.company.com")
        mailer.Send()
    End Sub
End Module
See Also

Reference

DomainKeys Class
Sign Overload
MailBee.Security Namespace


DomainKeys.Sign Method (MailMessage, String[], Byte[], String, DomainKeysTypes)

DomainKeysSign Method (MailMessage, String, Byte, String, DomainKeysTypes)
Signs a mail message with DomainKeys and/or DKIM signatures.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Sign(
    MailMessage msg,
    string[] headersToSign,
    byte[] privateKey,
    string selector,
    DomainKeysTypes dkTypes
)
Public Function Sign (
    msg As MailMessage,
    headersToSign As String(),
    privateKey As Byte(),
    selector As String,
    dkTypes As DomainKeysTypes
) As MailMessage

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be signed.
headersToSign
Type: SystemString
The array of the names of the headers to be included in the signature, or a null reference (Nothing in Visual Basic) if all the message headers should be included in the signature.
privateKey
Type: SystemByte
The binary contents of the DomainKeys/DKIM private key.
selector
Type: SystemString
The prefix of the sub-domain serving DomainKeys/DKIM for the sender domain.
dkTypes
Type: MailBee.SecurityDomainKeysTypes
Specifies which signatures to create (classic DK, newer DKIM, or both).

Return Value

Type: MailMessage
The signed mail message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or privateKey or selector is a null reference (Nothing in Visual Basic) or the message to be signed does not include the header specifying the sender (Sender or From or X-Sender header) or headersToSign array (if not null) does not list the name of that header or the sender's e-mail address domain is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This overload of Sign(MailMessage, String, Byte, String) allows you to select which methods to use (classic DK, newer DKIM, or both).
Note Note
Be sure to enable FipsMode if the current system is FIPS-compliant.
See Also

Reference

DomainKeys Class
Sign Overload
MailBee.Security Namespace


DomainKeys.Sign Method (MailMessage, String[], String, Boolean, String)

DomainKeysSign Method (MailMessage, String, String, Boolean, String)
Signs a mail message with DomainKeys and DKIM signatures.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Sign(
    MailMessage msg,
    string[] headersToSign,
    string privateKeyStr,
    bool isFilename,
    string selector
)
Public Function Sign (
    msg As MailMessage,
    headersToSign As String(),
    privateKeyStr As String,
    isFilename As Boolean,
    selector As String
) As MailMessage

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be signed.
headersToSign
Type: SystemString
The array of the names of the headers to be included in the signature, or a null reference (Nothing in Visual Basic) if all the message headers should be included in the signature.
privateKeyStr
Type: SystemString
The contents or the filename of the DomainKeys/DKIM private key.
isFilename
Type: SystemBoolean
If true, privateKeyStr denotes the private key filename; otherwise, the contents.
selector
Type: SystemString
The prefix of the sub-domain serving DomainKeys/DKIM for the sender domain.

Return Value

Type: MailMessage
The signed mail message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or privateKeyStr or selector is a null reference (Nothing in Visual Basic) or the message to be signed does not include the header specifying the sender (Sender or From header) or headersToSign array (if not null) does not list the name of that header or the sender's e-mail address domain is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

To sign a message with DomainKeys/DKIM signatures, you must have a private key (for instance, you can create it with OpenSSL utility).

The private key string (of file contents) looks like: -----BEGIN RSA PRIVATE KEY-----Base64-encoded key-----END RSA PRIVATE KEY-----. At least 1024-bit key length is recommended.

The message to be signed must have Sender or From header and the e-mail address in that header must contain non-empty domain part. You can include all the headers into the signature (passing a null reference as headersToSign value) so that any change in the headers the message originally had will make the signature invalid. Alternatively, you may include only certain headers into the signature (at least Sender or From) so that other headers can be changed. This is useful if the signature should not become invalid if you change some headers after the message has been signed. Typical case is when the mail server alters the headers of the signed message (changes Date, Message-ID or other headers).

If you want to sign empty headers as well (to avoid tampering them), set [!:KeepEmptyHeaders] property of Builder object to true.

To make MailBee automatically DK/DKIM sign all outgoing e-mail messages created from certain MailMessage instance, call SetDomainKeysSignOnSend(Boolean, Boolean, String, String, Boolean, String, DomainKeysTypes) method of Builder object.

Note Note
Be sure to enable FipsMode if the current system is FIPS-compliant.
Examples
This console sample composes a new mail message, signs it with DomainKeys/DKIM signatures (DomainKeys private key is taken from a file) and sends it out.
Note Note
See Sign(MailMessage, String, String, Boolean, String) example if you need to sign a message which may already contain Date or Message-ID headers which can be modified after the message gets sent (that sample contains alternative approach to the one listed in Remarks section).
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        // Compose a message.
        MailMessage msg = new MailMessage();
        msg.From.Email = "from@domain1.com";
        msg.To.Add("to@domain2.com");
        msg.Subject = "Hello";
        msg.BodyPlainText = "Hello, World!";

        // We will send the message with this object.
        Smtp mailer = new Smtp();

        // Sign the message and assign the signed message for sending.
        DomainKeys dk = new DomainKeys();
        mailer.Message = dk.Sign(msg, null, @"C:\Temp\rsa512.private", true, "dk");

        // Send the message via SMTP server (authentication is used in this sample).
        mailer.SmtpServers.Add("mail.domain1.com", "from@domain1.com", "secret");
        mailer.Send();
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security
Imports MailBee.SmtpMail

Module Sample
    Sub Main(ByVal args As String())
        ' Compose a message.
        Dim msg As New MailMessage
        msg.From.Email = "from@domain1.com"
        msg.To.Add("to@domain2.com")
        msg.Subject = "Hello"
        msg.BodyPlainText = "Hello, World!"

        ' We will send the message with this object.
        Dim mailer As New Smtp

        ' Sign the message and assign the signed message for sending.
        Dim dk As New DomainKeys
        mailer.Message = dk.Sign(msg, Nothing, "C:\Temp\rsa512.private", True, "dk")

        ' Send the message via SMTP server (authentication is used in this sample).
        mailer.SmtpServers.Add("mail.domain1.com", "from@domain1.com", "secret")
        mailer.Send()
    End Sub
End Module
See Also

Reference

DomainKeys Class
Sign Overload
MailBee.Security Namespace


DomainKeys.Sign Method (MailMessage, String[], String, Boolean, String, DomainKeysTypes)

DomainKeysSign Method (MailMessage, String, String, Boolean, String, DomainKeysTypes)
Signs a mail message with DomainKeys and/or DKIM signatures.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Sign(
    MailMessage msg,
    string[] headersToSign,
    string privateKeyStr,
    bool isFilename,
    string selector,
    DomainKeysTypes dkTypes
)
Public Function Sign (
    msg As MailMessage,
    headersToSign As String(),
    privateKeyStr As String,
    isFilename As Boolean,
    selector As String,
    dkTypes As DomainKeysTypes
) As MailMessage

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be signed.
headersToSign
Type: SystemString
The array of the names of the headers to be included in the signature, or a null reference (Nothing in Visual Basic) if all the message headers should be included in the signature.
privateKeyStr
Type: SystemString
The contents or the filename of the DomainKeys/DKIM private key.
isFilename
Type: SystemBoolean
If true, privateKeyStr denotes the private key filename; otherwise, the contents.
selector
Type: SystemString
The prefix of the sub-domain serving DomainKeys/DKIM for the sender domain.
dkTypes
Type: MailBee.SecurityDomainKeysTypes
Specifies which signatures to create (classic DK, newer DKIM, or both).

Return Value

Type: MailMessage
The signed mail message.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or privateKeyStr or selector is a null reference (Nothing in Visual Basic) or the message to be signed does not include the header specifying the sender (Sender or From or X-Sender header) or headersToSign array (if not null) does not list the name of that header or the sender's e-mail address domain is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This overload of Sign(MailMessage, String, String, Boolean, String) allows you to select which methods to use (classic DK, newer DKIM, or both).
Note Note
Be sure to enable FipsMode if the current system is FIPS-compliant.
See Also

Reference

DomainKeys Class
Sign Overload
MailBee.Security Namespace


DomainKeys.Verify Method

DomainKeysVerify Method
Overload List
 | Name | Description
 | Verify(MailMessage, Smtp) | Verifies the DomainKeys and DKIM signatures of the mail message.
 | Verify(MailMessage, Smtp, Header) | Verifies the specified DomainKeys and/or DKIM signature of the mail message.
Public method | Verify(MailMessage, Smtp, DomainKeysTypes) | Verifies the DomainKeys and/or DKIM signatures of the mail message.
Top
See Also

Reference

DomainKeys Class
MailBee.Security Namespace


DomainKeys.Verify Method (MailMessage, Smtp)

DomainKeysVerify Method (MailMessage, Smtp)
Verifies the DomainKeys and DKIM signatures of the mail message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DomainKeysVerifyResult Verify(
    MailMessage msg,
    Smtp dnsRequestor
)
Public Function Verify (
    msg As MailMessage,
    dnsRequestor As Smtp
) As DomainKeysVerifyResult

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be verified.
dnsRequestor
Type: MailBee.SmtpMailSmtp
The instance of Smtp class to be used for making DNS queries.

Return Value

Type: DomainKeysVerifyResult
The result of the verification.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or dnsRequestor is a null reference (Nothing in Visual Basic) or dnsRequestor.DnsServers collection is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

In order to verify DomainKeys/DKIM signature of e-mails, this method has to make DNS queries to the DomainKeys server of the sender. MailBee uses Smtp class for this. Thus, you must have the appropriate license for Smtp component. Or, you can use DomainKeysVerify which is simpler to use and does not require Smtp license (but it's more limited in features).

There is a chance your mail server may already check DomainKeys/DKIM signatures of incoming e-mails. If it's so, you should simply check extra headers which contain DomainKeys/DKIM checking results and get added by your mail server to the message. For instance, Gmail adds "Authentication-Results" header for that purpose.

If your message has multiple DKIM signatures and you need to check them all, use Verify(MailMessage, Smtp, Header) overload.

Note Note
This method may take significant time to execute because it needs to make a network operation - DNS query. Also, if there is a problem with the DNS server, it may fail (return DnsQueryFailed) even if the DomainKeys signature itself is correct. Also, if the message has both classic DomainKeys (DK) and newer DKIM signatures, the method will verify both of them to check if they match (this may double the execution time in case if DNS information for DK and DKIM records of the sending domain is different). If you wish to check only one type of DomainKeys signature, use Verify(MailMessage, Smtp, DomainKeysTypes) overload.

This method is thread-safe: you can call Verify(MailMessage, Smtp) method for the same instance of DomainKeys class to speed up validating signatures of multiple e-mails. However, you should pass separate instance of Smtp class as dnsRequestor value for each Verify(MailMessage, Smtp) method call.

Note Note
If the current system is FIPS-compliant and runs .NET 2.0/3.5 and the message contains only DKIM signature created using SHA256 algorithm, the method will return Sha256NotSupported or throw an exception if ThrowExceptions is enabled. This can only occur with older .NET versions (before 4.0) because there was no FIPS-certified SHA256 implementation at that time. On a FIPS system, use MailBee.NET.dll for .NET 4.0+ to avoid these issues. All classic DK signatures and those DKIM signatures which use SHA1 algorithm are fully supported on all Windows platforms, including FIPS-compliant ones. You'll still need to enable FipsMode to use FIPS-compliant versions of security algorithms.
Examples
This sample loads an e-mail message from file, prepares Smtp object for making DNS queries and verifies that message.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        // Load the message from file (we could also
        // get if from the mail server or elsewhere).
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\msg.eml");

        // Prepare Smtp instance for making DNS queries.
        // We assume Smtp license key is already set in config file.
        Smtp mailer = new Smtp();
        mailer.DnsServers.Autodetect();

        // Verify DomainKeys signature.
        DomainKeys dk = new DomainKeys();
        DomainKeysVerifyResult dkResult = dk.Verify(msg, mailer);
        Console.WriteLine(dkResult.ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security
Imports MailBee.SmtpMail

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file (we could also
        ' get if from the mail server or elsewhere).
        Dim msg As MailMessage = New MailMessage
        msg.LoadMessage("C:\Docs\msg.eml")

        ' Prepare Smtp instance for making DNS queries.
        ' We assume Smtp license key is already set in config file.
        Dim mailer As Smtp = New Smtp
        mailer.DnsServers.Autodetect()

        ' Verify DomainKeys signature.
        Dim dk As DomainKeys = New DomainKeys
        Dim dkResult As DomainKeysVerifyResult = dk.Verify(msg, mailer)
        Console.WriteLine(dkResult.ToString())
    End Sub
End Module
See Also

Reference

DomainKeys Class
Verify Overload
MailBee.Security Namespace


DomainKeys.Verify Method (MailMessage, Smtp, Header)

DomainKeysVerify Method (MailMessage, Smtp, Header)
Verifies the specified DomainKeys and/or DKIM signature of the mail message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DomainKeysVerifyResult Verify(
    MailMessage msg,
    Smtp dnsRequestor,
    Header dkHeader
)
Public Function Verify (
    msg As MailMessage,
    dnsRequestor As Smtp,
    dkHeader As Header
) As DomainKeysVerifyResult

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be verified.
dnsRequestor
Type: MailBee.SmtpMailSmtp
The instance of Smtp class to be used for making DNS queries.
dkHeader
Type: MailBee.MimeHeader
The source message's DomainKey-Signature or DKIM-Signature to be verified.

Return Value

Type: DomainKeysVerifyResult
The result of the verification.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or dnsRequestor or dkHeader is a null reference (Nothing in Visual Basic) or dnsRequestor.DnsServers collection is empty or FipsMode is enabled and DKIM verification is requested.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This overload is useful if the message has multiple DKIM signatures and you want to verify them all.

Note Note
If the current system is FIPS-compliant and runs .NET 2.0/3.5 and the message contains only DKIM signature created using SHA256 algorithm, the method will return Sha256NotSupported or throw an exception if ThrowExceptions is enabled. This can only occur with older .NET versions (before 4.0) because there was no FIPS-certified SHA256 implementation at that time. On a FIPS system, use MailBee.NET.dll for .NET 4.0+ to avoid these issues. All classic DK signatures and those DKIM signatures which use SHA1 algorithm are fully supported on all Windows platforms, including FIPS-compliant ones. You'll still need to enable FipsMode to use FIPS-compliant versions of security algorithms.
Examples
This sample loads an e-mail message from file, prepares Smtp object for making DNS queries and verifies all DKIM signatures in the message.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {

        // Load the message from file (we could also
        // get if from the mail server or elsewhere).
        MailMessage msg = new MailMessage();
        msg.LoadMessage(@"C:\Docs\msg.eml");

        // Prepare Smtp instance for making DNS queries.
        // We assume Smtp license key is already set in config file.
        Smtp mailer = new Smtp();
        mailer.DnsServers.Autodetect();

        DomainKeys dk = new DomainKeys();

        // Get the collection of DKIM-Signature headers.
        HeaderCollection dkimHeaders = msg.Headers.Items("DKIM-Signature");
        if (dkimHeaders == null)
        {
            Console.WriteLine("Message has no DKIM signatures");
        }
        else
        {
            foreach (Header h in dkimHeaders)
            {
                // Verify each DKIM signature.
                DomainKeysVerifyResult dkResult = dk.Verify(msg, mailer, h);
                Console.WriteLine(dkResult.ToString());
            }
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security
Imports MailBee.SmtpMail

Module Sample
    Sub Main(ByVal args As String())
        ' Load the message from file (we could also
        ' get if from the mail server or elsewhere).
        Dim msg As MailMessage = New MailMessage
        msg.LoadMessage("C:\Docs\msg.eml")

        ' Prepare Smtp instance for making DNS queries.
        ' We assume Smtp license key is already set in config file.
        Dim mailer As Smtp = New Smtp
        mailer.DnsServers.Autodetect()

        Dim dk As DomainKeys = New DomainKeys

        ' Get the collection of DKIM-Signature headers.
        Dim dkimHeaders As HeaderCollection = msg.Headers.Items("DKIM-Signature")
        If dkimHeaders Is Nothing Then
            Console.WriteLine("Message has no DKIM signatures")
        Else
            For Each h As Header In dkimHeaders
                ' Verify each DKIM signature.
                Dim dkResult As DomainKeysVerifyResult = dk.Verify(msg, mailer, h)
                Console.WriteLine(dkResult.ToString())
            Next
        End If
    End Sub
End Module
See Also

Reference

DomainKeys Class
Verify Overload
MailBee.Security Namespace


DomainKeys.Verify Method (MailMessage, Smtp, DomainKeysTypes)

DomainKeysVerify Method (MailMessage, Smtp, DomainKeysTypes)
Verifies the DomainKeys and/or DKIM signatures of the mail message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DomainKeysVerifyResult Verify(
    MailMessage msg,
    Smtp dnsRequestor,
    DomainKeysTypes dkTypes
)
Public Function Verify (
    msg As MailMessage,
    dnsRequestor As Smtp,
    dkTypes As DomainKeysTypes
) As DomainKeysVerifyResult

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be verified.
dnsRequestor
Type: MailBee.SmtpMailSmtp
The instance of Smtp class to be used for making DNS queries.
dkTypes
Type: MailBee.SecurityDomainKeysTypes
Specifies which signatures to verify (classic DK, newer DKIM, or both).

Return Value

Type: DomainKeysVerifyResult
The result of the verification.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or dnsRequestor is a null reference (Nothing in Visual Basic) or dnsRequestor.DnsServers collection is empty or FipsMode is enabled and DKIM verification is requested.
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This overload of Verify(MailMessage, Smtp) allows you to select which methods to use (classic DK, newer DKIM, or both).
Note Note
If the current system is FIPS-compliant and runs .NET 2.0/3.5 and the message contains only DKIM signature created using SHA256 algorithm, the method will return Sha256NotSupported or throw an exception if ThrowExceptions is enabled. This can only occur with older .NET versions (before 4.0) because there was no FIPS-certified SHA256 implementation at that time. On a FIPS system, use MailBee.NET.dll for >NET 4.0+ to avoid these issues. All classic DK signatures and those DKIM signatures which use SHA1 algorithm are fully supported on all Windows platforms, including FIPS-compliant ones. You'll still need to enable FipsMode to use FIPS-compliant versions of security algorithms.
See Also

Reference

DomainKeys Class
Verify Overload
MailBee.Security Namespace


DomainKeys.VerifyAsync Method

DomainKeysVerifyAsync Method
Overload List
 | Name | Description
Public method | VerifyAsync(MailMessage, Smtp) | async/await version of Verify(MailMessage, Smtp).
Public method | VerifyAsync(MailMessage, Smtp, Header) | async/await version of Verify(MailMessage, Smtp, Header).
Public method | VerifyAsync(MailMessage, Smtp, DomainKeysTypes) | async/await version of Verify(MailMessage, Smtp, DomainKeysTypes).
Top
See Also

Reference

DomainKeys Class
MailBee.Security Namespace


DomainKeys.VerifyAsync Method (MailMessage, Smtp)

DomainKeysVerifyAsync Method (MailMessage, Smtp)
async/await version of Verify(MailMessage, Smtp).

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<DomainKeysVerifyResult> VerifyAsync(
    MailMessage msg,
    Smtp dnsRequestor
)
Public Function VerifyAsync (
    msg As MailMessage,
    dnsRequestor As Smtp
) As Task(Of DomainKeysVerifyResult)

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be verified.
dnsRequestor
Type: MailBee.SmtpMailSmtp
The instance of Smtp class to be used for making DNS queries.

Return Value

Type: Task DomainKeysVerifyResult
A task that represents the asynchronous operation. The value of TResult parameter is the result of the verification.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or dnsRequestor is a null reference (Nothing in Visual Basic) or dnsRequestor.DnsServers collection is empty.
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

DomainKeys Class
VerifyAsync Overload
MailBee.Security Namespace


DomainKeys.VerifyAsync Method (MailMessage, Smtp, Header)

DomainKeysVerifyAsync Method (MailMessage, Smtp, Header)
async/await version of Verify(MailMessage, Smtp, Header).

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<DomainKeysVerifyResult> VerifyAsync(
    MailMessage msg,
    Smtp dnsRequestor,
    Header dkHeader
)
Public Function VerifyAsync (
    msg As MailMessage,
    dnsRequestor As Smtp,
    dkHeader As Header
) As Task(Of DomainKeysVerifyResult)

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be verified.
dnsRequestor
Type: MailBee.SmtpMailSmtp
The instance of Smtp class to be used for making DNS queries.
dkHeader
Type: MailBee.MimeHeader
The source message's DomainKey-Signature or DKIM-Signature to be verified.

Return Value

Type: Task DomainKeysVerifyResult
A task that represents the asynchronous operation. The value of TResult parameter is the result of the verification.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or dnsRequestor is a null reference (Nothing in Visual Basic) or dnsRequestor.DnsServers collection is empty or FipsMode is enabled and DKIM verification is requested.
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

DomainKeys Class
VerifyAsync Overload
MailBee.Security Namespace


DomainKeys.VerifyAsync Method (MailMessage, Smtp, DomainKeysTypes)

DomainKeysVerifyAsync Method (MailMessage, Smtp, DomainKeysTypes)
async/await version of Verify(MailMessage, Smtp, DomainKeysTypes).

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<DomainKeysVerifyResult> VerifyAsync(
    MailMessage msg,
    Smtp dnsRequestor,
    DomainKeysTypes dkTypes
)
Public Function VerifyAsync (
    msg As MailMessage,
    dnsRequestor As Smtp,
    dkTypes As DomainKeysTypes
) As Task(Of DomainKeysVerifyResult)

Parameters

msg
Type: MailBee.MimeMailMessage
The mail message to be verified.
dnsRequestor
Type: MailBee.SmtpMailSmtp
The instance of Smtp class to be used for making DNS queries.
dkTypes
Type: MailBee.SecurityDomainKeysTypes
Specifies which signatures to verify (classic DK, newer DKIM, or both).

Return Value

Type: Task DomainKeysVerifyResult
A task that represents the asynchronous operation. The value of TResult parameter is the result of the verification.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | msg or dnsRequestor is a null reference (Nothing in Visual Basic) or dnsRequestor.DnsServers collection is empty or FipsMode is enabled and DKIM verification is requested.
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

DomainKeys Class
VerifyAsync Overload
MailBee.Security Namespace


DomainKeys Properties

DomainKeys Properties

The DomainKeys type exposes the following members.

Properties
 | Name | Description
Public property | LastResult | Gets a numeric code of the last error.
 | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

DomainKeys Class
MailBee.Security Namespace


DomainKeys.LastResult Property

DomainKeysLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

DomainKeys Class
MailBee.Security Namespace
MailBeeErrorCodes
DomainKeysThrowExceptions


DomainKeys.ThrowExceptions Property

DomainKeysThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
true if the DomainKeys object will throw exceptions on errors; otherwise, false. The default value is true.
Remarks
If this property is set to true and an error occurs, an exception derived from MailBeeException is thrown. Otherwise, the exception will not occur but the method which caused will report error (returning false, null reference, etc). Anyway, the code of the last occurred error will be contained in the LastResult property. The list of all error codes is available in ErrorCodes class overview.
Examples
You can find examples of signing and verifying messages in Sign(MailMessage, String, String, Boolean, String) and Verify(MailMessage, Smtp) topics.
See Also

Reference

DomainKeys Class
MailBee.Security Namespace
DomainKeysLastResult


DomainKeysTypes Enumeration

DomainKeysTypes Enumeration
Defines the supported types of DomainKeys technology (classic DK and DKIM).

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum DomainKeysTypes
<FlagsAttribute>
Public Enumeration DomainKeysTypes
Members
Member name | Value | Description
DK | 1 | Classic DomainKeys technology. Always uses SHA1 algorithm for signing and verification.
DKIM | 2 | Newer DKIM technology. Can use SHA1 but SHA256 is preferred.
Both | 3 | Sign and verify using both DK and DKIM signatures. In case of verification, the message can have one or both signature, if any of them are incorrect, the overall result will be "incorrect". However, when there are both DK/DKIM signatures and DKIM signature cannot be checked because it's SHA256 while the current system has no support for it (e.g. FipsMode is enabled and .NET Framework is older than 4.0), MailBee will ignore DKIM signature and return the result based on DK signature only.
Remarks

MailBee can create and verify signatures of two types: classic DomainKeys and newer DKIM (or both of them). By default, both DomainKeys and DKIM are used. However, some overloads of Sign(MailMessage, String, Byte, String, DomainKeysTypes) and Verify(MailMessage, Smtp, DomainKeysTypes) methods allow you to specify the exact DomainKeys type to be used.

DK and DKIM use SHA algorithms for calculating hashes (for both signing and signature verification). DK always uses SHA1 algorithm while DKIM can use SHA1 but more secure SHA256 is preferred. MailBee by default creates DKIM signatures using SHA256. As for verification of DKIM signatures of existing messages, both SHA1 and SHA256 are supported.

Note Note
Checking or creating DKIM signatures may require the support of SHA256 algorithm from the system. If the current system is FIPS-compliant, you should enable FipsMode to make MailBee always use FIPS-compliant implementations of SHA1 and SHA256 (they are a bit slower than their managed code counterparts). However, FIPS-compliant SHA256 is still NOT available in .NET Framework 2.0/3.5. If FipsMode is enabled, MailBee for .NET 2.0/3.5 will use SHA1 for signing and can only verify SHA1 DKIM signatures.

.NET 4.0+ and MailBee.NET.dll builds for .NET 4.0+ are OK for FIPS and can always use SHA256 for both signing and encryption (but for performance reasons it's still recommended to enable FipsMode).

See Also

Reference

MailBee.Security Namespace


DomainKeysVerifyResult Enumeration

DomainKeysVerifyResult Enumeration
Defines the return values of Verify(MailMessage, Smtp) method.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum DomainKeysVerifyResult
Public Enumeration DomainKeysVerifyResult
Members
Member name | Value | Description
OK | 0 | The DomainKeys signature of the message is valid and up to date.
MessageNotSigned | 1 | The message is not signed with DomainKeys signature.
SignatureInvalidTag | 2 | The DomainKeys signature tag in the message headers is invalid.
SignatureExpired | 3 | The DomainKeys signature is expired.
DomainInvalid | 4 | The DomainKeys signature refers to a non-existent sender domain.
DnsQueryFailed | 5 | DNS query could not be performed. Perhaps, all DnsServers (supplied in dnsRequestor parameter of Verify(MailMessage, Smtp) method) are dead. By default, MailBee throws MailBeeDomainKeysException in case of this error.
DnsEntryInvalidTag | 6 | The DomainKeys DNS record of the sender domain is incorrect.
SignatureInvalid | 7 | The DomainKeys signature of the message is invalid.
PublicKeyBadFormat | 8 | The public key contained in DomainKeys DNS record of the sender domain has wrong format.
Sha256NotSupported | 9 | It's not possible to verify the given DKIM signature because it uses SHA256 while the current system does not support SHA256 algorithm (usually, in case of .NET Framework prior to 4.0 on a FIPS-enabled system). By default, MailBee throws MailBeeDomainKeysException in case of this error. With MailBee.NET.dll for .NET 4.0+ this error will never occur, regardless whether Windows operates in FIPS mode or not.
Remarks

Some errors are considered a problem with the system running MailBee and thus by default MailBee will throw MailBeeDomainKeysException in case of such errors. To suppress exceptions and get all errors as the method's return values, disable DomainKeys.ThrowExceptions (or MailMessage.ThrowExceptions if you using MailMessage.DomainKeysVerify method).

Note Note
In case of a FIPS-compliant system, enable FipsMode to make MailBee always use FIPS-compliant methods. If you don't do that, MailBee will fall back to a FIPS-compliant method only after the default method fails, and this degrades performance a bit. However, in .NET 2.0/3.5 the SHA256 method (which is used in DKIM) is available only as FIPS-noncompliant implementation. On a FIPS system, it's recommended to always use MailBee.NET.dll for .NET 4.0+ along with the corresponding .NET Framework.
See Also

Reference

MailBee.Security Namespace


Impersonation Class

Impersonation Class
Provides access to the impersonation functions.
Inheritance Hierarchy
SystemObject
MailBee.SecurityImpersonation

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Impersonation : IDisposable
Public Class Impersonation
    Implements IDisposable

The Impersonation type exposes the following members.

Constructors
 | Name | Description
Public method | Impersonation | Creates an instance of Impersonation class.
Public method | Impersonation(String) | Creates and unlocks an instance of Impersonation class.
Top
Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the Impersonation object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | Logoff | Terminates the impersonation mode initiated with LogonAs(String, String, String) call and reverts back to the user account the current thread was created on.
Public method | LogonAs | Makes the current thread impersonate the specified user account.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | IsImpersonated | Gets whether the impersonation mode is on and the current thread is being impersonating another user.
Public property | LastResult | Gets a numeric code of the last error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
Remarks

This class can be used to let the current thread programmatically impersonate another user. This can be useful if the application needs to access resources which belong to another user.

If you need to impersonate web application based on which user accessed it, refer to ASP.NET impersonation section of MSDN library.

To get the name of the user account being used by the current thread, call System.Security.Principal.WindowsIdentity.GetCurrent().Name.

Note Note
To use this class, make sure MailBee.NET Security is licensed (MailBee.NET Objects full bundle does include the license).
Examples
This sample displays the current user name, then impersontates the current thread and displays the current user name again (it's now different), then reverts back to the original user account and displays its name.
C#
VB
Copy
using System;
using System.Security.Principal;

using MailBee;
using MailBee.Security;

class Sample
{
    static void Main(string[] args)
    {
        // Display the current domain\user name (such as "OurCompany\JohnDoe").
        Console.WriteLine(WindowsIdentity.GetCurrent().Name);

        // Impersonate as Administrator user of the current computer.
        Impersonation imperson = new Impersonation();
        imperson.LogonAs("Administrator", null, "secret");

        // Display the current domain\user name (such as "JohnComputer\Administrator").
        Console.WriteLine(WindowsIdentity.GetCurrent().Name);

        // Revert back to the original user account.
        imperson.Logoff();

        // Display the current domain\user name (such as "OurCompany\JohnDoe").
        Console.WriteLine(WindowsIdentity.GetCurrent().Name);
    }
}
Imports System
Imports System.Security.Principal

Imports MailBee
Imports MailBee.Security

Class Sample
    Shared Sub Main(ByVal args() As String)
        ' Display the current domain\user name (such as "OurCompany\JohnDoe").
        Console.WriteLine(WindowsIdentity.GetCurrent().Name)

        ' Impersonate as Administrator user of the current computer.
        Dim imperson As Impersonation = New Impersonation
        imperson.LogonAs("Administrator", Nothing, "secret")

        ' Display the current domain\user name (such as "JohnComputer\Administrator").
        Console.WriteLine(WindowsIdentity.GetCurrent().Name)

        ' Revert back to the original user account.
        imperson.Logoff()

        ' Display the current domain\user name (such as "OurCompany\JohnDoe").
        Console.WriteLine(WindowsIdentity.GetCurrent().Name)
    End Sub
End Class
See Also

Reference

MailBee.Security Namespace


Impersonation Constructor

Impersonation Constructor
Creates an instance of Impersonation class.
Overload List
 | Name | Description
Public method | Impersonation | Creates an instance of Impersonation class.
Public method | Impersonation(String) | Creates and unlocks an instance of Impersonation class.
Top
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation Constructor

Impersonation Constructor
Creates an instance of Impersonation class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Impersonation()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Security Powerup not licensed.
Remarks

This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).

If your application is multi-threaded and you need to have multiple impersonated threads, each such thread must maintain its own instance of Impersonation class. Single-threaded applications need only a single instance of this class.

To get the name of the user account being used by the current thread, call System.Security.Principal.WindowsIdentity.GetCurrent().Name.

See Also

Reference

Impersonation Class
Impersonation Overload
MailBee.Security Namespace


Impersonation Constructor (String)

Impersonation Constructor (String)
Creates and unlocks an instance of Impersonation class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Impersonation(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Security Powerup not licensed and the supplied license key is invalid.
Remarks

If your application is multi-threaded and you need to have multiple impersonated threads, each such thread must maintain its own instance of Impersonation class. Single-threaded applications need only a single instance of this class.

To get the name of the user account being used by the current thread, call System.Security.Principal.WindowsIdentity.GetCurrent().Name.

See Also

Reference

Impersonation Class
Impersonation Overload
MailBee.Security Namespace


Impersonation Methods

Impersonation Methods

The Impersonation type exposes the following members.

Methods
 | Name | Description
Public method | Dispose | Releases the resources associated with the Impersonation object.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Public method | Logoff | Terminates the impersonation mode initiated with LogonAs(String, String, String) call and reverts back to the user account the current thread was created on.
Public method | LogonAs | Makes the current thread impersonate the specified user account.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation.Dispose Method

ImpersonationDispose Method
Releases the resources associated with the Impersonation object.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation.Logoff Method

ImpersonationLogoff Method
Terminates the impersonation mode initiated with LogonAs(String, String, String) call and reverts back to the user account the current thread was created on.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Logoff()
Public Function Logoff As Boolean

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidStateException | Not impersonated yet because LogonAs(String, String, String) method has not yet been called.
MailBeeImpersonationWin32Exception | Win32 returned an error on attempt to complete impersonation and ThrowExceptions is true.
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation.LogonAs Method

ImpersonationLogonAs Method
Makes the current thread impersonate the specified user account.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool LogonAs(
    string accountName,
    string domainName,
    string password
)
Public Function LogonAs (
    accountName As String,
    domainName As String,
    password As String
) As Boolean

Parameters

accountName
Type: SystemString
The name of the account being impersonated.
domainName
Type: SystemString
The name of the domain the specified account belongs to.
password
Type: SystemString
The password of the specified account.

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | accountName is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeImpersonationWin32Exception | Win32 returned an error on attempt to complete impersonation and ThrowExceptions is true.
Remarks
The impersonation lasts until the current thread exits or Logoff method gets called.
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation Properties

Impersonation Properties

The Impersonation type exposes the following members.

Properties
 | Name | Description
Public property | IsImpersonated | Gets whether the impersonation mode is on and the current thread is being impersonating another user.
Public property | LastResult | Gets a numeric code of the last error.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Top
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation.IsImpersonated Property

ImpersonationIsImpersonated Property
Gets whether the impersonation mode is on and the current thread is being impersonating another user.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsImpersonated { get; }
Public ReadOnly Property IsImpersonated As Boolean
    Get

Property Value

Type: Boolean
true if LogonAs(String, String, String) method has already been called on the current thread; otherwise, false.
See Also

Reference

Impersonation Class
MailBee.Security Namespace


Impersonation.LastResult Property

ImpersonationLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Impersonation Class
MailBee.Security Namespace
ImpersonationThrowExceptions


Impersonation.ThrowExceptions Property

ImpersonationThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the object will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the object methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee.NET usage will still be thrown.

Typical example of such errors is passing invalid arguments to methods. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

See Also

Reference

Impersonation Class
MailBee.Security Namespace


MessageVerificationFlags Enumeration

MessageVerificationFlags Enumeration
Defines criteria of verification of e-mail message signatures.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum MessageVerificationFlags
<FlagsAttribute>
Public Enumeration MessageVerificationFlags
Members
Member name | Value | Description
None | 0 | No criteria (the message signature successfully passed all the tests or the message was not signed and there were no tests to pass).
MessageTampered | 1 | The signature or content of the message was altered.
SignatureExpired | 2 | The signature of the message is expired.
SignerAndSenderDoNotMatch | 4 | The e-mail address of the sender (Email value of MailMessage.From object) does not match the EmailAddress of the certificate used to sign the message.
CertificateRevoked | 8 | The certificate used to sign the message is not valid anymore.
Untrusted | 16 | The certificate used to sign the message is not trusted. In other words, it was issued by an organization which is not trusted itself because its certificate was not found in the certification authorities stores such as IntermediateCA or RootCA.
All | 31 | All the criteria listed above.
Remarks

Verify(MailMessage, MessageVerificationFlags, CertificateStore) and DecryptAndVerify(MailMessage, MessageVerificationFlags) methods of Smime class can be used to verify message signatures accordingly MessageVerificationFlags criteria. These methods take MessageVerificationFlags value as one of the input parameters and return another MessageVerificationFlags value as one of the output parameters. The flags which have been set in the input value and remained in the output value indicate the verification tests which have not passed successfully.

Thus, if certain MessageVerificationFlags was set in the input parameter, the corresponding test will be made and the resulting value will have the same flag set if the corresponding test failed. This means each flag has two meanings: as input parameter "what to test" and as output parameter "whether the test failed or succeeded".

Note Note
Testing whether the signature is Untrusted actually checks if the signature certificate is issued by an organization (certification authority, CA) whose certificate is listed in the store of certification authorities. By default, they are IntermediateCA and RootCA. If the valid certificate of the CA is not there, the certificate of the signature is considered not trusted. You can use extraStore parameter of Verify(MailMessage, MessageVerificationFlags, CertificateStore) method to extend the list of CA stores if the CA certificate of the message signature resides in another location.
See Also

Reference

MailBee.Security Namespace
SmimeVerify(MailMessage, MessageVerificationFlags, CertificateStore)


Powerup Class

Powerup Class
Explains which features of MailBee.Security namespace require Security license.
Inheritance Hierarchy
SystemObject
MailBee.SecurityPowerup

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Powerup
Public Class Powerup

The Powerup type exposes the following members.

Constructors
 | Name | Description
Public method | Powerup | Creates an instance of Powerup class.
Public method | Powerup(String) | Creates and unlocks an instance of Powerup class.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
 | LicenseKey | Obsolete. Assigns the license key.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
Remarks
Some features of MailBee.Security namespace become available for use only if MailBee.NET Security is specifically licensed (the license key is set in MailBee.Global.LicenseKey property includes Security license). With Security fully unlocked, the developer can:
  • Assign client certificate when connecting to SSL-enabled mail server
  • Examine the certificate of the SSL-enabled mail server
  • Use S/MIME facilities, access certificates and certificate stores
  • Impersonate another user account
The only MailBee.Security feature which works even if Security license is not unlocked is the ability to connect to SSL-enabled mail servers. The application, however, will be unable to set or examine certificates involved in SSL handshake procedure.
See Also

Reference

MailBee.Security Namespace


Powerup Constructor

Powerup Constructor
Creates an instance of Powerup class.
Overload List
 | Name | Description
Public method | Powerup | Creates an instance of Powerup class.
Public method | Powerup(String) | Creates and unlocks an instance of Powerup class.
Top
See Also

Reference

Powerup Class
MailBee.Security Namespace


Powerup Constructor

Powerup Constructor
Creates an instance of Powerup class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Powerup()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Security Powerup not licensed.
Remarks

This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).

This class on its own does not have any useful features. It mainly supports the licensing infrastructure. For instance, it lets you check how many days you still have in trial mode.

Note Note
You can avoid using Powerup class and unlock Smime and Impersonationclasses in Security namespace directly, by supplying the license key right in their constructor. See Smime(String) and Impersonation(String) constructors.
See Also

Reference

Powerup Class
Powerup Overload
MailBee.Security Namespace


Powerup Constructor (String)

Powerup Constructor (String)
Creates and unlocks an instance of Powerup class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Powerup(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Security Powerup not licensed and the supplied license key is invalid.
Remarks
This class on its own does not have any useful features. It mainly supports the licensing infrastructure. For instance, it lets you check how many days you still have in trial mode.
Note Note
You can avoid using Powerup class and unlock Smime and Impersonationclasses in Security namespace directly, by supplying the license key right in their constructor. See Smime(String) and Impersonation(String) constructors.
See Also

Reference

Powerup Class
Powerup Overload
MailBee.Security Namespace


Powerup Methods

Powerup Methods

The Powerup type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

Powerup Class
MailBee.Security Namespace


Powerup Properties

Powerup Properties

The Powerup type exposes the following members.

Properties
 | Name | Description
 | LicenseKey | Obsolete. Assigns the license key.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Top
See Also

Reference

Powerup Class
MailBee.Security Namespace


Powerup.LicenseKey Property

PowerupLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks Security Powerup. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks

You can unlock Security Powerup by either setting this property to the valid permanent or trial license key or by adding MailBee.Security.Powerup.LicenseKey key in app.config, web.config, or machine.config file.

This property is static (Shared in Visual Basic). If not set in the config file, this property must be set before any method or property or constructor which may check it gets called.

Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

Powerup Class
MailBee.Security Namespace


Powerup.TrialDaysLeft Property

PowerupTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value indicating the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

Powerup Class
MailBee.Security Namespace


RegistryStoreLocation Enumeration

RegistryStoreLocation Enumeration
Defines branches of the Windows registry where the system certificate stores can reside.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum RegistryStoreLocation
Public Enumeration RegistryStoreLocation
Members
Member name | Value | Description
CurrentUser | 65536 | The store resides in "HKEY_CURRENT_USER\Software\Microsoft\SystemCertificates" branch.
LocalMachine | 131072 | The store resides in "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates" branch.
Users | 393216 | The store resides in "HKEY_USERS\.DEFAULT\Software\Microsoft\SystemCertificates" branch.
Remarks

By default, MailBee uses system stores which reside in CurrentUser branch.

To open an existing system certificate store which resides in another branch of the registry, create CertificateStore object using CertificateStore(String, CertStoreType, String, CryptoServiceProvider, RegistryStoreLocation) constructor. To create a store in the registry, use RegisterSystemStore(String, RegistryStoreLocation) method.

See Also

Reference

MailBee.Security Namespace
CertificateStoreRegisterSystemStore(String, RegistryStoreLocation)
CertificateStoreUnregisterSystemStore(String, RegistryStoreLocation)


SecurityProtocol Enumeration

SecurityProtocol Enumeration
Specifies the protocols to be used for performing TLS/SSL negotiation and data encryption.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum SecurityProtocol
<FlagsAttribute>
Public Enumeration SecurityProtocol
Members
Member name | Value | Description
Auto | 0 | The most secure protocol supported by the server will be used to authenticate the client and encrypt the data as specified by SecurityProtocol setting (if it's available and set). If it's not set or set to the value which permits the usage of a highly vulnerable SSL 3.0 protocol, TlsAuto will be tried instead. For better security, you can select Tls12 explicitly (provided that the server supports TLS 1.2 as well).
Ssl2 | 12 | SSL 2.0 will be used to authenticate the client and encrypt the data. Highly vulnerable!
Ssl3 | 48 | SSL 3.0 will be used to authenticate the client and encrypt the data. Highly vulnerable!
Tls1 | 192 | TLS 1.0 will be used to authenticate the client and encrypt the data. Somewhat vulnerable but there are still some mail servers around which don't support better options.
Tls11 | 768 | TLS 1.1 will be used to authenticate the client and encrypt the data.
Tls12 | 3072 | TLS 1.2 will be used to authenticate the client and encrypt the data. The highest level of security.
TlsAuto | 4032 | TLS 1.2 will be used if supported by the server. If not, falls back to TLS 1.1 and if it's not supported either, falls back to TLS 1.0. Highly vulnerable SSL 3.0 and its predecessors will NOT be tried anyway. This option is a decent trade-off between security and compatibility.
Remarks

The security protocol can be set via SslProtocol property of SmtpServer, Pop3, or Imap classes.

If the mail server does not support automatic protocol negotiation (this usually results in getting MailBeeSocketResetException thrown during TLS/SSL negotiation), the developer should manually specify the protocol to be used (for example Tls12).

Note Note
In case of UWP platform, MailBee always uses TlsAuto setting.
See Also

Reference

MailBee.Security Namespace


Smime Class

Smime Class
Provides properties and methods for encrypting, decrypting, signing and verifying e-mail messages.
Inheritance Hierarchy
SystemObject
MailBee.SecuritySmime

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Smime
Public Class Smime

The Smime type exposes the following members.

Constructors
 | Name | Description
Public method | Smime | Creates an instance of Smime class.
Public method | Smime(String) | Creates and unlocks an instance of Smime class.
Top
Methods
 | Name | Description
 | Decrypt(MailMessage) | Decrypts an e-mail message if it's encrypted.
 | Decrypt(MailMessage, CertificateStore) | Decrypts an e-mail message if it's encrypted.
 | DecryptAndVerify(MailMessage, MessageVerificationFlags) | Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.
 | DecryptAndVerify(MailMessage, MessageVerificationFlags, CertificateStore, CertificateStore) | Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.
 | Encrypt | Encrypts an e-mail message.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | ResetToDefaults | Resets S/MIME settings to default values.
 | Sign | Signs an e-mail message with a digital signature.
 | SignAndEncrypt | Signs and encrypts an e-mail message.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Verify | Verifies if the signature of the specified e-mail message is valid.
Top
Properties
 | Name | Description
 | EncryptionAlgorithm | Gets or sets the algorithm to use for encrypting messages.
 | HashAlgorithm | Gets or sets the hash algorithm to use for signing messages with a digital signature.
Public property | IncludeWholeChainOnSign | Gets or sets if Sign(MailMessage, Certificate) or SignAndEncrypt(MailMessage, Certificate, CertificateCollection) should include the whole certificate chain into the signature.
Public property | LastResult | Gets a numeric code of the last error.
 | Provider | Gets or sets the CSP to be used for cryptographic operations.
Public property | SetEnvelopedCmsOnDecrypt | Gets or sets if Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods should also populate EnvelopedCmsResult property.
Public property | SetSignedCmsOnVerify | Gets or sets if Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods should also populate SignedCmsResult property.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Public property | TimestampOnSign | Gets or sets if Sign(MailMessage, Certificate) or SignAndEncrypt(MailMessage, Certificate, CertificateCollection) should timestamp the signature.
Top
Remarks
Using this class, you can perform the following operations with e-mail messages:
  • Encrypt or decrypt e-mails
  • Sign e-mails with a digital signature
  • Verify signatures of e-mails

The class by default uses FIPS compliant algorithms: RSA DES for encryption and SHA1 for signing.

Note Note
To use this class, make sure MailBee.NET Security is licensed (MailBee.NET Objects full bundle does include the license).
Examples
This sample retrieves the last e-mail from the specified POP3 account, decrypts it if it's encrypted and verifies its signature if any. Then, it prints the plain-text version of the message to the console.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.Mime;
using MailBee.Security;

Smime objSmime = new Smime();
Pop3 pop = new Pop3();
pop.Connect("server", 110, true);
pop.Login("login", "password");
MailMessage msg = pop.DownloadEntireMessage(pop.InboxMessageCount);
pop.Disconnect();

try
{
    if (msg.IsEncrypted)
    {
        SmimeResult smResult = objSmime.DecryptAndVerify(msg, MessageVerificationFlags.All);
        if (smResult.VerificationResult > 0)
        {
            Console.WriteLine("Verification failed");
        }
        else if (smResult.DecryptedMessage != null)
        {
            Console.WriteLine(smResult.DecryptedMessage.BodyPlainText);
        }
    }
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import these namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.Mime
Imports MailBee.Security

Dim objSmime As Smime = New Smime
Dim pop As Pop3 = New Pop3
pop.Connect("server", 110, True)
pop.Login("login", "password")
Dim msg As MailMessage = pop.DownloadEntireMessage(pop.InboxMessageCount)
pop.Disconnect()

Try
    If (msg.IsEncrypted) Then
        Dim smResult As SmimeResult = objSmime.DecryptAndVerify(msg, MessageVerificationFlags.All)
        If (smResult.VerificationResult > 0) Then
            Console.WriteLine("Verification failed")
        ElseIf (Not IsNothing(smResult.DecryptedMessage)) Then
            Console.WriteLine(smResult.DecryptedMessage.BodyPlainText)
        End If
    End If
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

MailBee.Security Namespace


Smime Constructor

Smime Constructor
Creates an instance of Smime class.
Overload List
 | Name | Description
Public method | Smime | Creates an instance of Smime class.
Public method | Smime(String) | Creates and unlocks an instance of Smime class.
Top
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime Constructor

Smime Constructor
Creates an instance of Smime class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Smime()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Security Powerup not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

Smime Class
Smime Overload
MailBee.Security Namespace


Smime Constructor (String)

Smime Constructor (String)
Creates and unlocks an instance of Smime class.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Smime(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET Security Powerup not licensed and the supplied license key is invalid.
See Also

Reference

Smime Class
Smime Overload
MailBee.Security Namespace


Smime Methods

Smime Methods

The Smime type exposes the following members.

Methods
 | Name | Description
 | Decrypt(MailMessage) | Decrypts an e-mail message if it's encrypted.
 | Decrypt(MailMessage, CertificateStore) | Decrypts an e-mail message if it's encrypted.
 | DecryptAndVerify(MailMessage, MessageVerificationFlags) | Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.
 | DecryptAndVerify(MailMessage, MessageVerificationFlags, CertificateStore, CertificateStore) | Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.
 | Encrypt | Encrypts an e-mail message.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
 | ResetToDefaults | Resets S/MIME settings to default values.
 | Sign | Signs an e-mail message with a digital signature.
 | SignAndEncrypt | Signs and encrypts an e-mail message.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | Verify | Verifies if the signature of the specified e-mail message is valid.
Top
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.Decrypt Method

SmimeDecrypt Method
Overload List
Name | Description
Decrypt(MailMessage) | Decrypts an e-mail message if it's encrypted.
Decrypt(MailMessage, CertificateStore) | Decrypts an e-mail message if it's encrypted.
Top
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.Decrypt Method (MailMessage)

SmimeDecrypt Method (MailMessage)
Decrypts an e-mail message if it's encrypted.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmimeResult Decrypt(
    MailMessage message
)
Public Function Decrypt (
    message As MailMessage
) As SmimeResult

Parameters

message
Type: MailBee.MimeMailMessage
The original encrypted message to be decrypted.

Return Value

Type: SmimeResult
A reference to SmimeResult object containing either the decrypted message or the original message if it was not encrypted; a null reference (Nothing in Visual Basic) if the decryption process failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | A WinAPI error occurred during opening Personal certificate store and ThrowExceptions is true.
MailBeeSmimeWin32Exception | A WinAPI error occurred while performing S/MIME operation and ThrowExceptions is true.
Remarks

This method looks for the appropriate certificate for decryption in the standard system certificate store named "MY" (Personal). The certificate must contain a private key. In the case if the required certificate resides in another store, use Decrypt(MailMessage, CertificateStore) overload.

To access the decrypted message, use DecryptedMessage property of the returned SmimeResult object. To get the certificate used for decryption, use DecryptionCertificate property of the same object.

To check if the original message was encrypted, examine IsEncrypted property value of the original MailMessage object.

To decrypt and verify a message within a single method call, use DecryptAndVerify(MailMessage, MessageVerificationFlags) method or its overloads.

Examples
This sample loads the message from disk, decrypts it, and displays its content.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\encrypted.eml");

Smime objSmime = new Smime();

try
{
    // Decrypt the message.
    SmimeResult sResult = objSmime.Decrypt(msg);

    // Display the content of decrypted message.
    if (sResult.DecryptedMessage != null)
    {
        Console.WriteLine(sResult.DecryptedMessage.BodyPlainText);
    }
    if (sResult.DecryptionCertificate != null)
    {
        Console.WriteLine(sResult.DecryptionCertificate.Subject);
    }
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import these namespaces at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\encrypted.eml")

Dim objSmime As Smime = New Smime

Try
    ' Decrypt the message.
    Dim sResult As SmimeResult = objSmime.Decrypt(msg)

    ' Display the content of decrypted message.
    If (Not IsNothing(sResult.DecryptedMessage)) Then
        Console.WriteLine(sResult.DecryptedMessage.BodyPlainText)
    End If
    If (Not IsNothing(sResult.DecryptionCertificate)) Then
        Console.WriteLine(sResult.DecryptionCertificate.Subject)
    End If
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
Decrypt Overload
MailBee.Security Namespace
SmimeDecryptAndVerify(MailMessage, MessageVerificationFlags)


Smime.Decrypt Method (MailMessage, CertificateStore[])

SmimeDecrypt Method (MailMessage, CertificateStore)
Decrypts an e-mail message if it's encrypted.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmimeResult Decrypt(
    MailMessage message,
    CertificateStore[] stores
)
Public Function Decrypt (
    message As MailMessage,
    stores As CertificateStore()
) As SmimeResult

Parameters

message
Type: MailBee.MimeMailMessage
The original encrypted message to be decrypted.
stores
Type: MailBee.SecurityCertificateStore
The array of the certificate stores to be searched for the appropriate certificate for decrypting the message, or a null reference (Nothing in Visual Basic) if Personal system storage should be used.

Return Value

Type: SmimeResult
A reference to SmimeResult object containing either the decrypted message or the original message if it was not encrypted; a null reference (Nothing in Visual Basic) if the decryption process failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | A WinAPI error occurred during opening Personal certificate store and ThrowExceptions is true.
MailBeeSmimeWin32Exception | A WinAPI error occurred while performing S/MIME operation and ThrowExceptions is true.
Remarks

This method looks for the appropriate certificate for decryption in the specified certificate stores. The certificate must contain a private key.

To access the decrypted message, use DecryptedMessage property of the returned SmimeResult object. To get the certificate used for decryption, use DecryptionCertificate property of the same object.

To check if the original message was encrypted, examine IsEncrypted property value of the original MailMessage object.

To decrypt and verify a message within a single method call, use DecryptAndVerify(MailMessage, MessageVerificationFlags) method or its overloads.

Examples
This sample loads the message from the disk file, decrypts it, and displays its contents.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\encrypted_only.eml");

Smime objSmime = new Smime();

try
{
    CertificateStore[] stores = new CertificateStore[1];
    stores[0] = new CertificateStore(CertificateStore.Personal, CertStoreType.System, null);

    // Decrypt the message.
    SmimeResult sResult = objSmime.Decrypt(msg, stores);

    // Display the content of the message.
    if (sResult.DecryptedMessage != null)
    {
        Console.WriteLine(sResult.DecryptedMessage.BodyPlainText);
    }
    if (sResult.DecryptionCertificate != null)
    {
        Console.WriteLine(sResult.DecryptionCertificate.Subject);
    }
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import these namespaces at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\encrypted_only.eml")

Dim objSmime As Smime = New Smime

Try
    Dim stores(0) As CertificateStore
    stores(0) = New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)

    ' Decrypt the message.
    Dim sResult As SmimeResult = objSmime.Decrypt(msg, stores)

    ' Display the content of the message.
    If (Not IsNothing(sResult.DecryptedMessage)) Then
        Console.WriteLine(sResult.DecryptedMessage.BodyPlainText)
    End If
    If (Not IsNothing(sResult.DecryptionCertificate)) Then
        Console.WriteLine(sResult.DecryptionCertificate.Subject)
    End If
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
Decrypt Overload
MailBee.Security Namespace
SmimeDecryptAndVerify(MailMessage, MessageVerificationFlags)


Smime.DecryptAndVerify Method

SmimeDecryptAndVerify Method
Overload List
Name | Description
DecryptAndVerify(MailMessage, MessageVerificationFlags) | Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.
DecryptAndVerify(MailMessage, MessageVerificationFlags, CertificateStore, CertificateStore) | Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.
Top
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.DecryptAndVerify Method (MailMessage, MessageVerificationFlags)

SmimeDecryptAndVerify Method (MailMessage, MessageVerificationFlags)
Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmimeResult DecryptAndVerify(
    MailMessage message,
    MessageVerificationFlags flags
)
Public Function DecryptAndVerify (
    message As MailMessage,
    flags As MessageVerificationFlags
) As SmimeResult

Parameters

message
Type: MailBee.MimeMailMessage
The original message to be decrypted and verified.
flags
Type: MailBee.SecurityMessageVerificationFlags
A set of flags which specify the verification criteria.

Return Value

Type: SmimeResult
A reference to SmimeResult object containing either the decrypted message or the original message if it was not encrypted; a null reference (Nothing in Visual Basic) if the decryption process failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | A WinAPI error occurred during opening Personal certificate store and ThrowExceptions is true.
MailBeeSmimeWin32Exception | A WinAPI error occurred while performing S/MIME operation and ThrowExceptions is true.
Remarks

The returned SmimeResult object provides access to the return values of this method, including DecryptedMessage, DecryptionCertificate, VerificationResult, and SignatureCertificate.

Thus, to access the decrypted message, use DecryptedMessage property; to get the certificate used for decryption, use DecryptionCertificate property.

To check the result of the message signature verification, examine VerificationResult property value. To access the signature certificate, use SignatureCertificate property.

See Decrypt(MailMessage) and Verify(MailMessage, MessageVerificationFlags, CertificateStore) topics for more details on decryption and verification process.

Examples
The sample loads the message from the disk file, decrypts and verifies it.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\encrypted.eml");

Smime objSmime = new Smime();

try
{
    // Verify the message.
    SmimeResult smResult = objSmime.DecryptAndVerify(msg, MessageVerificationFlags.All);
    MessageVerificationFlags resultOptions = smResult.VerificationResult;
    // Check whether verification has been passed successfully.
    if (resultOptions != MessageVerificationFlags.None)
    {
        if ((resultOptions & MessageVerificationFlags.CertificateRevoked) == MessageVerificationFlags.CertificateRevoked)
        {
            Console.WriteLine("Error! Certificate revoked...");
        }
        if ((resultOptions & MessageVerificationFlags.MessageTampered) == MessageVerificationFlags.MessageTampered)
        {
            Console.WriteLine("Error! Message has been tampered...");
        }
        if ((resultOptions & MessageVerificationFlags.SignatureExpired) == MessageVerificationFlags.SignatureExpired)
        {
            Console.WriteLine("Error! Signature expired...");
        }
        if ((resultOptions & MessageVerificationFlags.SignerAndSenderDoNotMatch) == MessageVerificationFlags.SignerAndSenderDoNotMatch)
        {
            Console.WriteLine("Error! Signer and sender do not match...");
        }
        if ((resultOptions & MessageVerificationFlags.Untrusted) == MessageVerificationFlags.Untrusted)
        {
            Console.WriteLine("Error! Untrusted certificate...");
        }
    }
    if (smResult.SignatureCertificate != null)
    {
        Console.WriteLine(smResult.SignatureCertificate.Subject);
    }
    if (smResult.DecryptionCertificate != null)
    {
        Console.WriteLine(smResult.DecryptionCertificate.Subject);
    }
    if (smResult.DecryptedMessage != null)
    {
        Console.WriteLine(smResult.DecryptedMessage.BodyPlainText);
    }
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import these namespaces at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\encrypted.eml")

Dim objSmime As Smime = New Smime

Try
    ' Verify the message.
    Dim smResult As SmimeResult = objSmime.DecryptAndVerify(msg, MessageVerificationFlags.All)
    Dim resultOptions As MessageVerificationFlags = smResult.VerificationResult
    ' Check whether verification has been passed successfully.
    If (resultOptions <> MessageVerificationFlags.None) Then
        If ((resultOptions & MessageVerificationFlags.CertificateRevoked) = MessageVerificationFlags.CertificateRevoked) Then
            Console.WriteLine("Error! Certificate revoked...")
        End If
        If ((resultOptions & MessageVerificationFlags.MessageTampered) = MessageVerificationFlags.MessageTampered) Then
            Console.WriteLine("Error! Message has been tampered...")
        End If
        If ((resultOptions & MessageVerificationFlags.SignatureExpired) = MessageVerificationFlags.SignatureExpired) Then
            Console.WriteLine("Error! Signature expired...")
        End If
        If ((resultOptions & MessageVerificationFlags.SignerAndSenderDoNotMatch) = MessageVerificationFlags.SignerAndSenderDoNotMatch) Then
            Console.WriteLine("Error! Signer and sender do not match...")
        End If
        If ((resultOptions & MessageVerificationFlags.Untrusted) = MessageVerificationFlags.Untrusted) Then
            Console.WriteLine("Error! Untrusted certificate...")
        End If
    End If
    If (Not IsNothing(smResult.SignatureCertificate)) Then
        Console.WriteLine(smResult.SignatureCertificate.Subject)
    End If
    If (Not IsNothing(smResult.DecryptionCertificate)) Then
        Console.WriteLine(smResult.DecryptionCertificate.Subject)
    End If
    If (Not IsNothing(smResult.DecryptedMessage)) Then
        Console.WriteLine(smResult.DecryptedMessage.BodyPlainText)
    End If
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
DecryptAndVerify Overload
MailBee.Security Namespace
SmimeDecrypt(MailMessage)
SmimeVerify(MailMessage, MessageVerificationFlags, CertificateStore)


Smime.DecryptAndVerify Method (MailMessage, MessageVerificationFlags, CertificateStore[], CertificateStore)

SmimeDecryptAndVerify Method (MailMessage, MessageVerificationFlags, CertificateStore, CertificateStore)
Decrypts an e-mail message if it's encrypted and verifies its signature if it's signed.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmimeResult DecryptAndVerify(
    MailMessage message,
    MessageVerificationFlags flags,
    CertificateStore[] storesForDecrypt,
    CertificateStore extraStoreForVerify
)
Public Function DecryptAndVerify (
    message As MailMessage,
    flags As MessageVerificationFlags,
    storesForDecrypt As CertificateStore(),
    extraStoreForVerify As CertificateStore
) As SmimeResult

Parameters

message
Type: MailBee.MimeMailMessage
The original message to be decrypted and verified.
flags
Type: MailBee.SecurityMessageVerificationFlags
A set of flags which specify the verification criteria.
storesForDecrypt
Type: MailBee.SecurityCertificateStore
The array of the certificate stores to be searched for the appropriate certificate for decrypting the message, or a null reference (Nothing in Visual Basic) if Personal system storage should be used.
extraStoreForVerify
Type: MailBee.SecurityCertificateStore
A reference to the certificate store containing additional certificates of the certification authorities, or a null reference (Nothing in Visual Basic) if only the system default certification authorities should be used for validating the certificate of the message signature.

Return Value

Type: SmimeResult
A reference to SmimeResult object containing either the decrypted message or the original message if it was not encrypted; a null reference (Nothing in Visual Basic) if the decryption process failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
MailBeeCertificateStoreWin32Exception | A WinAPI error occurred during opening Personal certificate store and ThrowExceptions is true.
MailBeeSmimeWin32Exception | A WinAPI error occurred while performing S/MIME operation and ThrowExceptions is true.
Remarks

The returned SmimeResult object provides access to the return values of this method, including DecryptedMessage, DecryptionCertificate, VerificationResult, and SignatureCertificate.

Thus, to access the decrypted message, use DecryptedMessage property; to get the certificate used for decryption, use DecryptionCertificate property.

To check the result of the message signature verification, examine VerificationResult property value. To access the signature certificate, use SignatureCertificate property.

See Decrypt(MailMessage) and Verify(MailMessage, MessageVerificationFlags, CertificateStore) topics for more details on decryption and verification process.

Examples
This sample loads the message from the disk file, decrypts and verifies it.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\encrypted.eml");

Smime objSmime = new Smime();

try
{
    // Verify the message.
    SmimeResult smResult = objSmime.DecryptAndVerify(msg, MessageVerificationFlags.All,
        new CertificateStore[] {new CertificateStore(CertificateStore.Personal, CertStoreType.System, null)}, null);
    MessageVerificationFlags resultOptions = smResult.VerificationResult;
    // Check whether verification has been passed successfully.
    if (resultOptions != MessageVerificationFlags.None)
    {
        if ((resultOptions & MessageVerificationFlags.CertificateRevoked) == MessageVerificationFlags.CertificateRevoked)
        {
            Console.WriteLine("Error! Certificate revoked...");
        }
        if ((resultOptions & MessageVerificationFlags.MessageTampered) == MessageVerificationFlags.MessageTampered)
        {
            Console.WriteLine("Error! Message has been tampered...");
        }
        if ((resultOptions & MessageVerificationFlags.SignatureExpired) == MessageVerificationFlags.SignatureExpired)
        {
            Console.WriteLine("Error! Signature expired...");
        }
        if ((resultOptions & MessageVerificationFlags.SignerAndSenderDoNotMatch) == MessageVerificationFlags.SignerAndSenderDoNotMatch)
        {
            Console.WriteLine("Error! Signer and sender do not match...");
        }
        if ((resultOptions & MessageVerificationFlags.Untrusted) == MessageVerificationFlags.Untrusted)
        {
            Console.WriteLine("Error! Untrusted certificate...");
        }
    }
    if (smResult.SignatureCertificate != null)
    {
        Console.WriteLine(smResult.SignatureCertificate.Subject);
    }
    if (smResult.DecryptionCertificate != null)
    {
        Console.WriteLine(smResult.DecryptionCertificate.Subject);
    }
    if (smResult.DecryptedMessage != null)
    {
        Console.WriteLine(smResult.DecryptedMessage.BodyPlainText);
    }
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import these namespaces at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\encrypted.eml")

Dim objSmime As Smime = New Smime

Try
    ' Verify the message.
    Dim smResult As SmimeResult = objSmime.DecryptAndVerify(msg, MessageVerificationFlags.All, _
        New CertificateStore() {New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)}, Nothing)
    Dim resultOptions As MessageVerificationFlags = smResult.VerificationResult
    ' Check whether verification has been passed successfully.
    If (resultOptions <> MessageVerificationFlags.None) Then
        If ((resultOptions & MessageVerificationFlags.CertificateRevoked) = MessageVerificationFlags.CertificateRevoked) Then
            Console.WriteLine("Error! Certificate revoked...")
        End If
        If ((resultOptions & MessageVerificationFlags.MessageTampered) = MessageVerificationFlags.MessageTampered) Then
            Console.WriteLine("Error! Message has been tampered...")
        End If
        If ((resultOptions & MessageVerificationFlags.SignatureExpired) = MessageVerificationFlags.SignatureExpired) Then
            Console.WriteLine("Error! Signature expired...")
        End If
        If ((resultOptions & MessageVerificationFlags.SignerAndSenderDoNotMatch) = MessageVerificationFlags.SignerAndSenderDoNotMatch) Then
            Console.WriteLine("Error! Signer and sender do not match...")
        End If
        If ((resultOptions & MessageVerificationFlags.Untrusted) = MessageVerificationFlags.Untrusted) Then
            Console.WriteLine("Error! Untrusted certificate...")
        End If
    End If
    If (Not IsNothing(smResult.SignatureCertificate)) Then
        Console.WriteLine(smResult.SignatureCertificate.Subject)
    End If
    If (Not IsNothing(smResult.DecryptionCertificate)) Then
        Console.WriteLine(smResult.DecryptionCertificate.Subject)
    End If
    If (Not IsNothing(smResult.DecryptedMessage)) Then
        Console.WriteLine(smResult.DecryptedMessage.BodyPlainText)
    End If
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
DecryptAndVerify Overload
MailBee.Security Namespace
SmimeDecrypt(MailMessage)
SmimeVerify(MailMessage, MessageVerificationFlags, CertificateStore)


Smime.Encrypt Method

SmimeEncrypt Method
Encrypts an e-mail message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Encrypt(
    MailMessage message,
    CertificateCollection encryptionCerts
)
Public Function Encrypt (
    message As MailMessage,
    encryptionCerts As CertificateCollection
) As MailMessage

Parameters

message
Type: MailBee.MimeMailMessage
The original message which should be encrypted.
encryptionCerts
Type: MailBee.SecurityCertificateCollection
The collection of public certificates of all the recipients of the message.

Return Value

Type: MailMessage
A reference to the encrypted message if the encryption went successfully; a reference to the original message if it was already encrypted; a null reference (Nothing in Visual Basic) if the encryption failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic) or encryptionCerts is a null reference or an empty collection.
MailBeeSmimeWin32Exception | An error occurred and ThrowExceptions is true.
Remarks

This method encrypts the specified message using EncryptionAlgorithm and public keys of all the certificates in encryptionCerts collection. If the e-mail message contains multiple recipients, this collection should contain all their certificates. Otherwise, those recipients which have no their certificates listed in encryptionCerts will not be able to decrypt the message on their end.

Thus, to encrypt a message, you need to have public certificates of its recipients. They can be stored in a file, in Windows registry, etc. You can check S/MIME Demo projects shipped with MailBee on how to open certificate stores and find out recipient certificates based on the recipient list of the message (which can be obtained with GetAllRecipients method).

The developer can also use SignAndEncrypt(MailMessage, Certificate, CertificateCollection) method to encrypt a message and sign it with a digital signature in a single method call.

Examples
The following sample loads the message from disk, encrypts it with the recipient's certificate, and then saves it back to disk.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\original.eml");

Smime objSmime = new Smime();

try
{
    // Open the system certificate store which contains the recipients certificates.
    CertificateStore store = new CertificateStore(CertificateStore.OtherPeople, CertStoreType.System, null);
    // Search the recipient by e-mail.
    CertificateCollection encryptionCerts = store.FindCertificates("user1@domain.com", CertificateFields.EmailAddress);
    // Encrypt the message.
    MailMessage encMsg = objSmime.Encrypt(msg, encryptionCerts);
    // Save the encrypted message to the disk file.
    encMsg.SaveMessage(@"C:\Temp\encrypted.eml");
    Console.WriteLine("Done.");
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import these namespaces at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\original.eml")

Dim objSmime As Smime = New Smime

Try
    ' Open the system certificate store which contains the recipients certificates.
    Dim store As CertificateStore = New CertificateStore(CertificateStore.OtherPeople, CertStoreType.System, Nothing)
    ' Search the recipient by e-mail.
    Dim encryptionCerts As CertificateCollection = store.FindCertificates("user1@domain.com", CertificateFields.EmailAddress)
    ' Encrypt the message.
    Dim encMsg As MailMessage = objSmime.Encrypt(msg, encryptionCerts)
    ' Save the encrypted message to disk.
    encMsg.SaveMessage("C:\Temp\encrypted.eml")
    Console.WriteLine("Done.")
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeSignAndEncrypt(MailMessage, Certificate, CertificateCollection)


Smime.ResetToDefaults Method

SmimeResetToDefaults Method
Resets S/MIME settings to default values.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ResetToDefaults()
Public Function ResetToDefaults As Boolean

Return Value

Type: Boolean
true if succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeCryptoProviderWin32Exception | Failed to create an instance of CryptoServiceProvider representing the default CSP and ThrowExceptions is true.
Remarks

This method reverts Provider property value back to the default CSP (Base).

The algorithm to use for encryption (EncryptionAlgorithm property) is set to RSA DES (szOID_RSA_DES_EDE3_CBC).

The algorithm to use for signing messages (HashAlgorithm property) is set to SHA1 (szOID_OIWSEC_sha1).

Examples
The example is available in CryptoServiceProvider topic.
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.Sign Method

SmimeSign Method
Signs an e-mail message with a digital signature.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Sign(
    MailMessage message,
    Certificate signingCert
)
Public Function Sign (
    message As MailMessage,
    signingCert As Certificate
) As MailMessage

Parameters

message
Type: MailBee.MimeMailMessage
The original e-mail message to be signed.
signingCert
Type: MailBee.SecurityCertificate
The certificate to be used for signing the message. This certificate must contain a private key.

Return Value

Type: MailMessage
A reference to the signed message if the signing went successfully; a reference to the original message if it was already signed; a null reference (Nothing in Visual Basic) if the signing process failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message or signingCert is a null reference (Nothing in Visual Basic).
MailBeeSmimeWin32Exception | An error occurred and ThrowExceptions is true.
Remarks

Make sure the Certificate used for signing has the same EmailAddress as Email value of MailMessage.From of the message being signed. Otherwise, the message will still be signed successfully but it might not be trusted by its recipients when it gets delivered.

To create a signature, MailBee uses HashAlgorithm and the private key of signingCert to calculate a hash of the message data.

The developer can also use the SignAndEncrypt(MailMessage, Certificate, CertificateCollection) method to sign and encrypt a message within a single method call.

If you're getting "System.Security.Cryptography.CryptographicException: the buffer supplied to a function was too small" on signing, you will have to set IncludeWholeChainOnSign to false.

Examples
The following sample loads the message from disk, signs it with the sender's certificate, and saves it back to disk.
C#
VB
Copy
// To use the code below, import these namespace at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Docs\original.eml");

Smime objSmime = new Smime();

try
{
    // Load certificate from the specified file.
    Certificate signingCert = new Certificate(@"C:\Docs\cert.pfx", CertFileType.Pfx, "secret");
    // Sign the message.
    MailMessage signMsg = objSmime.Sign(msg, signingCert);
    // Save the signed message to disk.
    signMsg.SaveMessage(@"C:\Docs\signed.eml");
    Console.WriteLine("Done.");
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Docs\original.eml")

Dim objSmime As Smime = New Smime

Try
    ' Load certificate from the specified file.
    Dim signingCert As Certificate = New Certificate("C:\Docs\cert.pfx", CertFileType.Pfx, "secret")
    ' Sign the message.
    Dim signMsg As MailMessage = objSmime.Sign(msg, signingCert)
    ' Save the signed message to disk.
    signMsg.SaveMessage("C:\Docs\signed.eml")
    Console.WriteLine("Done.")
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeSignAndEncrypt(MailMessage, Certificate, CertificateCollection)


Smime.SignAndEncrypt Method

SmimeSignAndEncrypt Method
Signs and encrypts an e-mail message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage SignAndEncrypt(
    MailMessage message,
    Certificate signingCert,
    CertificateCollection encryptionCerts
)
Public Function SignAndEncrypt (
    message As MailMessage,
    signingCert As Certificate,
    encryptionCerts As CertificateCollection
) As MailMessage

Parameters

message
Type: MailBee.MimeMailMessage
The original e-mail message to be signed and encrypted.
signingCert
Type: MailBee.SecurityCertificate
The certificate to be used for signing the message. This certificate must contain a private key.
encryptionCerts
Type: MailBee.SecurityCertificateCollection
The collection of public certificates of all the recipients of the message.

Return Value

Type: MailMessage
A reference to the signed and encrypted message if the signing and encryption went successfully; a reference to the original message if it was already signed and encrypted; a null reference (Nothing in Visual Basic) if the signing or encryption failed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message or signingCert is a null reference (Nothing in Visual Basic) or encryptionCerts is a null reference or an empty collection.
MailBeeSmimeWin32Exception | An error occurred and ThrowExceptions is true.
Remarks
See Sign(MailMessage, Certificate) and Encrypt(MailMessage, CertificateCollection) topics for details on signing and encryption process.
Examples
This sample signs and encrypts a message.
C#
VB
Copy
// To use the code below, import these namespace at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\original.eml");

Smime objSmime = new Smime();

try
{
    // Search for the sender certificate in the system certificate store.
    CertificateStore myStore = new CertificateStore(CertificateStore.Personal, CertStoreType.System, null);
    CertificateCollection signingCerts = myStore.FindCertificates("user@afterlogic.com", CertificateFields.EmailAddress);
    Certificate signingCert = null;
    if (signingCerts.Count > 0) signingCert = signingCerts[0];
    // Get the recipients certificates from the the system certificate store.
    CertificateCollection encryptionCerts = new CertificateStore(CertificateStore.OtherPeople, CertStoreType.System, null).GetAllCertificates();
    // Sign and encrypt the message.
    MailMessage signEncMsg = objSmime.SignAndEncrypt(msg, signingCert, encryptionCerts);
    // Save the resulting message.
    signEncMsg.SaveMessage(@"C:\Temp\result.eml");
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\original.eml")

Dim objSmime As Smime = New Smime

Try
    ' Search for the sender certificate in the system certificate store.
    Dim myStore As CertificateStore = New CertificateStore(CertificateStore.Personal, CertStoreType.System, Nothing)
    Dim signingCerts As CertificateCollection = myStore.FindCertificates("user@afterlogic.com", CertificateFields.EmailAddress)
    Dim signingCert As Certificate = Nothing
    If (signingCerts.Count > 0) Then
        signingCert = signingCerts(0)
    End If
    ' Get the recipients certificates from the the system certificate store.
    Dim encryptionCerts As CertificateCollection = New CertificateStore(CertificateStore.OtherPeople, CertStoreType.System, Nothing).GetAllCertificates()
    ' Sign and encrypt the message.
    Dim signEncMsg As MailMessage = objSmime.SignAndEncrypt(msg, signingCert, encryptionCerts)
    ' Save the resulting message.
    signEncMsg.SaveMessage("C:\Temp\result.eml")
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeSign(MailMessage, Certificate)
SmimeEncrypt(MailMessage, CertificateCollection)


Smime.Verify Method

SmimeVerify Method
Verifies if the signature of the specified e-mail message is valid.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmimeResult Verify(
    MailMessage message,
    MessageVerificationFlags flags,
    CertificateStore extraStore
)
Public Function Verify (
    message As MailMessage,
    flags As MessageVerificationFlags,
    extraStore As CertificateStore
) As SmimeResult

Parameters

message
Type: MailBee.MimeMailMessage
The message to be verified.
flags
Type: MailBee.SecurityMessageVerificationFlags
A set of flags which specify the verification criteria.
extraStore
Type: MailBee.SecurityCertificateStore
A reference to the certificate store containing additional certificates of the certification authorities, or a null reference (Nothing in Visual Basic) if only the system default certification authorities should be used for validating the certificate of the message signature.

Return Value

Type: SmimeResult
A reference to SmimeResult object containing either a bitwise combination of MessageVerificationFlags indicating which conditions of flags criteria have not been passed the verification or None if the verification completed successfully or the message was not signed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | message is a null reference (Nothing in Visual Basic).
Remarks

If the message has so-called "attached" signature, you'll need to check DecryptedMessage of the returned value of this method in order to get access to the original (unsigned) message. This is because messages with attached signatures look like encrypted messages so it's required to decode such a message (like in decryption procedure) to get access to the original message. Therefore checking the signature may also extract the original message from it. If DecryptedMessage is not set (null reference) in the returned value of this method, this means the message has so-called "detached" signature which is not encapsulated into the original message contents but simply added as attachment. In this case, message input parameter already refers to the original message and there is no need to extract anything.

extraStore usually needs to be set if the system default store lacks a certification authority which issued the certificate the message is signed with. This is common case for ASP.NET web applications because ASP.NET user has fewer certification authorities in its system default store than regular Windows users. See ASP.NET S/MIME Demo sample project shipped with MailBee for details.

To check the message verification result, examine VerificationResult property of the returned SmimeResult object. To access the signature certificate, use SignatureCertificate property of the same object.

To check if the original message had a digital signature, examine IsSigned property value of the original MailMessage object.

To decrypt and verify a message within a single method call, use DecryptAndVerify(MailMessage, MessageVerificationFlags) method or its overloads.

Note Note
This method can be slow in case if the certificate refers to a non-existing domain name (or local domain name while the current machine is not in that network).
Examples
This sample verifies the message signature using all the available criteria.
C#
VB
Copy
// To use the code below, import these namespace at the top of your code
using System;
using MailBee;
using MailBee.Mime;
using MailBee.Security;

// The actual code (put it into a method of your class)

// Load the message from file.
MailMessage msg = new MailMessage();
msg.LoadMessage(@"C:\Temp\signed_only.eml");

Smime objSmime = new Smime();

try
{
    // Verify the message.
    SmimeResult smResult = objSmime.Verify(msg, MessageVerificationFlags.All, null);
    MessageVerificationFlags resultOptions = smResult.VerificationResult;
    // Check for the errors.
    if (resultOptions != MessageVerificationFlags.None)
    {
        if ((resultOptions & MessageVerificationFlags.CertificateRevoked) == MessageVerificationFlags.CertificateRevoked)
        {
            Console.WriteLine("Error! Certificate revoked...");
        }
        if ((resultOptions & MessageVerificationFlags.MessageTampered) == MessageVerificationFlags.MessageTampered)
        {
            Console.WriteLine("Error! Message has been tampered...");
        }
        if ((resultOptions & MessageVerificationFlags.SignatureExpired) == MessageVerificationFlags.SignatureExpired)
        {
            Console.WriteLine("Error! Signature expired...");
        }
        if ((resultOptions & MessageVerificationFlags.SignerAndSenderDoNotMatch) == MessageVerificationFlags.SignerAndSenderDoNotMatch)
        {
            Console.WriteLine("Error! Signer and sender do not match...");
        }
        if ((resultOptions & MessageVerificationFlags.Untrusted) == MessageVerificationFlags.Untrusted)
        {
            Console.WriteLine("Error! Untrusted certificate...");
        }
    }
    if (smResult.SignatureCertificate != null)
    {
        Console.WriteLine(smResult.SignatureCertificate.Subject);
    }
}
catch (MailBeeException ex)
{
    Console.WriteLine(ex.Message);
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee
Imports MailBee.Mime
Imports MailBee.Security

' The actual code (put it into a method of your class)

' Load the message from file.
Dim msg As MailMessage = New MailMessage
msg.LoadMessage("C:\Temp\signed_only.eml")

Dim objSmime As Smime = New Smime

Try
    ' Verify the message.
    Dim smResult As SmimeResult = objSmime.Verify(msg, MessageVerificationFlags.All, Nothing)
    Dim resultOptions As MessageVerificationFlags = smResult.VerificationResult
    ' Check for the errors.
    If (resultOptions <> MessageVerificationFlags.None) Then
        If ((resultOptions & MessageVerificationFlags.CertificateRevoked) = MessageVerificationFlags.CertificateRevoked) Then
            Console.WriteLine("Error! Certificate revoked...")
        End If
        If ((resultOptions & MessageVerificationFlags.MessageTampered) = MessageVerificationFlags.MessageTampered) Then
            Console.WriteLine("Error! Message has been tampered...")
        End If
        If ((resultOptions & MessageVerificationFlags.SignatureExpired) = MessageVerificationFlags.SignatureExpired) Then
            Console.WriteLine("Error! Signature expired...")
        End If
        If ((resultOptions & MessageVerificationFlags.SignerAndSenderDoNotMatch) = MessageVerificationFlags.SignerAndSenderDoNotMatch) Then
            Console.WriteLine("Error! Signer and sender do not match...")
        End If
        If ((resultOptions & MessageVerificationFlags.Untrusted) = MessageVerificationFlags.Untrusted) Then
            Console.WriteLine("Error! Untrusted certificate...")
        End If
    End If
    If (Not IsNothing(smResult.SignatureCertificate)) Then
        Console.WriteLine(smResult.SignatureCertificate.Subject)
    End If
Catch ex As MailBeeException
    Console.WriteLine(ex.Message)
End Try
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeDecryptAndVerify(MailMessage, MessageVerificationFlags)


Smime Properties

Smime Properties

The Smime type exposes the following members.

Properties
 | Name | Description
 | EncryptionAlgorithm | Gets or sets the algorithm to use for encrypting messages.
 | HashAlgorithm | Gets or sets the hash algorithm to use for signing messages with a digital signature.
Public property | IncludeWholeChainOnSign | Gets or sets if Sign(MailMessage, Certificate) or SignAndEncrypt(MailMessage, Certificate, CertificateCollection) should include the whole certificate chain into the signature.
Public property | LastResult | Gets a numeric code of the last error.
 | Provider | Gets or sets the CSP to be used for cryptographic operations.
Public property | SetEnvelopedCmsOnDecrypt | Gets or sets if Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods should also populate EnvelopedCmsResult property.
Public property | SetSignedCmsOnVerify | Gets or sets if Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods should also populate SignedCmsResult property.
Public property | ThrowExceptions | Gets or sets whether the object will throw exceptions on errors.
Public property | TimestampOnSign | Gets or sets if Sign(MailMessage, Certificate) or SignAndEncrypt(MailMessage, Certificate, CertificateCollection) should timestamp the signature.
Top
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.EncryptionAlgorithm Property

SmimeEncryptionAlgorithm Property
Gets or sets the algorithm to use for encrypting messages.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Algorithm EncryptionAlgorithm { get; set; }
Public Property EncryptionAlgorithm As Algorithm
    Get
    Set

Property Value

Type: Algorithm
A reference to Algorithm object representing the algorithm to be used for encrypting messages. The default algorithm is RSA DES (szOID_RSA_DES_EDE3_CBC).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

Usually, there is no need to change the default value of this property.

In order to set this property, the developer can get Algorithm instance using CreateInstanceByOid(String) or CreateInstanceById(Int32) methods.

Examples
This sample sets DES encryption algorithm if it's supported by the operating system.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class)

Smime objSmime = new Smime();
Algorithm[] algs = objSmime.Provider.GetSupportedAlgorithms();
Algorithm algDes = null;

// Iterate through all encryption algorithms supported by CSP
foreach (Algorithm alg in algs)
{
    if (alg.Name.ToLower() == "des")
    {
        algDes = alg;
        break;
    }
}
if (algDes != null)
{
    objSmime.EncryptionAlgorithm = algDes;
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class)

Dim objSmime As Smime = New Smime
Dim algs() As Algorithm = objSmime.Provider.GetSupportedAlgorithms()
Dim algDes As Algorithm = Nothing

' Iterate through all encryption algorithms supported by CSP
For Each alg As Algorithm In algs
    If (alg.Name.ToLower() = "des") Then
        algDes = alg
        Exit For
    End If
Next
If (Not IsNothing(algDes)) Then
    objSmime.EncryptionAlgorithm = algDes
End If
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeHashAlgorithm
SmimeEncrypt(MailMessage, CertificateCollection)


Smime.HashAlgorithm Property

SmimeHashAlgorithm Property
Gets or sets the hash algorithm to use for signing messages with a digital signature.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Algorithm HashAlgorithm { get; set; }
Public Property HashAlgorithm As Algorithm
    Get
    Set

Property Value

Type: Algorithm
A reference to Algorithm object representing the hash algorithm to be used for signing messages. The default algorithm is SHA1.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

Usually, there is no need to change the default value of this property.

In order to set this property, the developer can get Algorithm instance using CreateInstanceByOid(String) or CreateInstanceById(Int32) methods.

Examples
This sample sets MD5 hash algorithm if it's supported by the operating system.
C#
VB
Copy
// To use the code below, import MailBee namespace at the top of your code
using MailBee.Security;

// The actual code (put it into a method of your class)

Smime objSmime = new Smime();
Algorithm[] algs = objSmime.Provider.GetSupportedAlgorithms();
Algorithm algHash = null;

// Iterate through all hash algorithms supported by OS
foreach (Algorithm alg in algs)
{
    if (alg.Name.ToLower() == "md5")
    {
        algHash = alg;
        break;
    }
}
if (algHash != null)
{
    objSmime.HashAlgorithm = algHash;
}
' To use the code below, import MailBee namespace at the top of your code
Imports MailBee.Security

' The actual code (put it into a method of your class)

Dim objSmime As Smime = New Smime
Dim algs() As Algorithm = objSmime.Provider.GetSupportedAlgorithms()
Dim algHash As Algorithm = Nothing

' Iterate through all hash algorithms supported by OS
For Each alg As Algorithm In algs
    If (alg.Name.ToLower() = "md5") Then
        algHash = alg
        Exit For
    End If
Next
If (Not IsNothing(algHash)) Then
    objSmime.HashAlgorithm = algHash
End If
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeSign(MailMessage, Certificate)


Smime.IncludeWholeChainOnSign Property

SmimeIncludeWholeChainOnSign Property
Gets or sets if Sign(MailMessage, Certificate) or SignAndEncrypt(MailMessage, Certificate, CertificateCollection) should include the whole certificate chain into the signature.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IncludeWholeChainOnSign { get; set; }
Public Property IncludeWholeChainOnSign As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will export the full certificate chain into the signature; otherwise, only the signer's certificate itself. The default value is true.
Remarks

With the whole chain, the signature size will be larger. However, if you set this value to false, it might not be possible for the recipient to check the signature in case if the CA of this certificate is not known for them.

Note Note
If you're getting "System.Security.Cryptography.CryptographicException: the buffer supplied to a function was too small" on signing, you will have to set this property to false. Some combinations of Windows (Windows Server 2012) and .NET Framework have a bug in an underlying implementation of security certificates which cannot be worked around unless you upgrade to a more recent Windows (e.g. 2016) or disable including the whole certificate chain. Issue on github.com.
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.LastResult Property

SmimeLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Smime Class
MailBee.Security Namespace
SmimeThrowExceptions


Smime.Provider Property

SmimeProvider Property
Gets or sets the CSP to be used for cryptographic operations.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public CryptoServiceProvider Provider { get; set; }
Public Property Provider As CryptoServiceProvider
    Get
    Set

Property Value

Type: CryptoServiceProvider
A reference to CryptoServiceProvider object representing the CSP to be used for cryptographic operations. The default CSP is Base.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks
This property is for advanced use. Most applications do not need to change the default CSP.
Examples
The example is available in CryptoServiceProvider topic.
See Also

Reference

Smime Class
MailBee.Security Namespace
MailBee.SecurityCryptoServiceProvider
SmimeResetToDefaults


Smime.SetEnvelopedCmsOnDecrypt Property

SmimeSetEnvelopedCmsOnDecrypt Property
Gets or sets if Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods should also populate EnvelopedCmsResult property.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetEnvelopedCmsOnDecrypt { get; set; }
Public Property SetEnvelopedCmsOnDecrypt As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will populate EnvelopedCmsResult property with EnvelopedCms object in SmimeResult object returned by methods capable of message signature verification in case if the message is encrypted. If false, EnvelopedCmsResult property will always remain a null reference (Nothing in Visual Basic). The default value is false.
Remarks
Instantiating EnvelopedCms object is an expensive operation so you should set this property to true only if you need the S/MIME message info which is not otherwise returned by other properties of SmimeResult class.
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.SetSignedCmsOnVerify Property

SmimeSetSignedCmsOnVerify Property
Gets or sets if Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods should also populate SignedCmsResult property.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SetSignedCmsOnVerify { get; set; }
Public Property SetSignedCmsOnVerify As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will populate SignedCmsResult property with SignedCms object in SmimeResult object returned by methods capable of message signature verification in case if the message does have signature. If false, SignedCmsResult property will always remain a null reference (Nothing in Visual Basic). The default value is false.
Remarks
Instantiating SignedCms object is an expensive operation so you should set this property to true only if you need the S/MIME message info which is not otherwise returned by other properties of SmimeResult class.
See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.ThrowExceptions Property

SmimeThrowExceptions Property
Gets or sets whether the object will throw exceptions on errors.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the object will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the object methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee.NET usage will still be thrown.

Typical example of such errors is passing invalid arguments to methods. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

See Also

Reference

Smime Class
MailBee.Security Namespace


Smime.TimestampOnSign Property

SmimeTimestampOnSign Property
Gets or sets if Sign(MailMessage, Certificate) or SignAndEncrypt(MailMessage, Certificate, CertificateCollection) should timestamp the signature.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool TimestampOnSign { get; set; }
Public Property TimestampOnSign As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will timestamp the signature; otherwise, there will be no timestamp. The default value is true.
Remarks
Timestamping requires a network query to the timestamp server.
See Also

Reference

Smime Class
MailBee.Security Namespace


SmimeResult Class

SmimeResult Class
Provides access to the decrypted message, signature verification status and other values returned by the methods of Smime class.
Inheritance Hierarchy
SystemObject
MailBee.SecuritySmimeResult

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmimeResult
Public Class SmimeResult

The SmimeResult type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
Name Description
Public property DecryptedMessage
Gets a reference to the decrypted message.
Public property DecryptionCertificate
Gets a reference to the certificate which was used to decrypt the message.
Public property EnvelopedCmsResult
Gets EnvelopedCms reference produced by Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods if SetEnvelopedCmsOnDecrypt was true.

Field Value

Type:
A reference to EnvelopedCms object if SetEnvelopedCmsOnDecrypt was true and message decryption occurred, or a null reference (Nothing in Visual Basic) otherwise.
Public property SignatureCertificate
Gets a reference to the certificate extracted from the message signature.
Public property SignedCmsResult
Gets SignedCms reference produced by Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods if SetSignedCmsOnVerify was true.

Field Value

Type:
A reference to SignedCms object if SetSignedCmsOnVerify was true and signature verification occurred, or a null reference (Nothing in Visual Basic) otherwise.
Public property VerificationResult
Gets a set of flags which indicate reasons to treat the message signature as invalid.
Top
Remarks
The following methods of Smime class return SmimeResult objects: Decrypt(MailMessage), Verify(MailMessage, MessageVerificationFlags, CertificateStore), DecryptAndVerify(MailMessage, MessageVerificationFlags).
Examples
The examples are available in Decrypt(MailMessage), Verify(MailMessage, MessageVerificationFlags, CertificateStore), DecryptAndVerify(MailMessage, MessageVerificationFlags) topics.
See Also

Reference

MailBee.Security Namespace
MailBee.SecuritySmime


SmimeResult Methods

SmimeResult Methods

The SmimeResult type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult Properties

SmimeResult Properties

The SmimeResult type exposes the following members.

Properties
Name Description
Public property DecryptedMessage
Gets a reference to the decrypted message.
Public property DecryptionCertificate
Gets a reference to the certificate which was used to decrypt the message.
Public property EnvelopedCmsResult
Gets EnvelopedCms reference produced by Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods if SetEnvelopedCmsOnDecrypt was true.

Field Value

Type:
A reference to EnvelopedCms object if SetEnvelopedCmsOnDecrypt was true and message decryption occurred, or a null reference (Nothing in Visual Basic) otherwise.
Public property SignatureCertificate
Gets a reference to the certificate extracted from the message signature.
Public property SignedCmsResult
Gets SignedCms reference produced by Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods if SetSignedCmsOnVerify was true.

Field Value

Type:
A reference to SignedCms object if SetSignedCmsOnVerify was true and signature verification occurred, or a null reference (Nothing in Visual Basic) otherwise.
Public property VerificationResult
Gets a set of flags which indicate reasons to treat the message signature as invalid.
Top
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult.DecryptedMessage Property

SmimeResultDecryptedMessage Property
Gets a reference to the decrypted message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage DecryptedMessage { get; }
Public ReadOnly Property DecryptedMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the decrypted message (or to the source message if it was not encrypted), or a null reference (Nothing in Visual Basic) if the current SmimeResult object was returned by Verify(MailMessage, MessageVerificationFlags, CertificateStore) method call.
Remarks
You should use Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods to get SmimeResult object with DecryptedMessage property set.
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult.DecryptionCertificate Property

SmimeResultDecryptionCertificate Property
Gets a reference to the certificate which was used to decrypt the message.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate DecryptionCertificate { get; }
Public ReadOnly Property DecryptionCertificate As Certificate
    Get

Property Value

Type: Certificate
A reference to the certificate used to decrypt the message, or a null reference (Nothing in Visual Basic) if the source message was not encrypted or if the current SmimeResult object was returned by Verify(MailMessage, MessageVerificationFlags, CertificateStore) method call.
Remarks
You should use Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods to get SmimeResult object with DecryptionCertificate property set.
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult.EnvelopedCmsResult Property

SmimeResultEnvelopedCmsResult Property
Gets EnvelopedCms reference produced by Decrypt(MailMessage) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods if SetEnvelopedCmsOnDecrypt was true.

Property Value

Type: EnvelopedCms
A reference to EnvelopedCms object if SetEnvelopedCmsOnDecrypt was true and message decryption occurred, or a null reference (Nothing in Visual Basic) otherwise.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EnvelopedCms EnvelopedCmsResult { get; }
Public ReadOnly Property EnvelopedCmsResult As EnvelopedCms
    Get

Property Value

Type: EnvelopedCms
Remarks
EnvelopedCms object lets you examine many properties of an S/MIME encrypted message. For instance, smimeResult.EnvelopedCmsResult.ContentEncryptionAlgorithm (C# syntax) gives you the algorithm the message was encrypted with.
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult.SignatureCertificate Property

SmimeResultSignatureCertificate Property
Gets a reference to the certificate extracted from the message signature.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Certificate SignatureCertificate { get; }
Public ReadOnly Property SignatureCertificate As Certificate
    Get

Property Value

Type: Certificate
A reference to the certificate extracted from the message signature, or a null reference (Nothing in Visual Basic) if the source message was not signed or if the current SmimeResult object was returned by Encrypt(MailMessage, CertificateCollection) method call.
Remarks
You should use Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods to get SmimeResult object with SignatureCertificate property set.
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult.SignedCmsResult Property

SmimeResultSignedCmsResult Property
Gets SignedCms reference produced by Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods if SetSignedCmsOnVerify was true.

Property Value

Type: SignedCms
A reference to SignedCms object if SetSignedCmsOnVerify was true and signature verification occurred, or a null reference (Nothing in Visual Basic) otherwise.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SignedCms SignedCmsResult { get; }
Public ReadOnly Property SignedCmsResult As SignedCms
    Get

Property Value

Type: SignedCms
Remarks
SignedCms object lets you examine many properties of an S/MIME signature. For instance, smimeResult.SignedCmsResult.SignerInfos[0].DigestAlgorithm (C# syntax) gives you the algorithm the message was signed with.
See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SmimeResult.VerificationResult Property

SmimeResultVerificationResult Property
Gets a set of flags which indicate reasons to treat the message signature as invalid.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MessageVerificationFlags VerificationResult { get; }
Public ReadOnly Property VerificationResult As MessageVerificationFlags
    Get

Property Value

Type: MessageVerificationFlags
A set of flags which indicate reasons to treat the message signature as invalid, or None if the source message passed all the tests or was not signed or if the current SmimeResult object was returned by Encrypt(MailMessage, CertificateCollection) (rather than by Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags)) method call.
Remarks

You should use Verify(MailMessage, MessageVerificationFlags, CertificateStore) or DecryptAndVerify(MailMessage, MessageVerificationFlags) methods to get SmimeResult object with VerificationResult property set.

If you get None status, you can distinguish between "not-signed" and "signature passed all the tests" statuses by checking SignatureCertificate property. It's a null reference (Nothing in Visual Basic) if the message was not signed.

See Also

Reference

SmimeResult Class
MailBee.Security Namespace


SslStartupMode Enumeration

SslStartupMode Enumeration
Specifies in which way the mailer component should switch the connection into TLS/SSL mode.

Namespace: MailBee.Security
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum SslStartupMode
Public Enumeration SslStartupMode
Members
Member name | Value | Description
Manual | 0 | The developer must manually call StartTls method of the mailer component to switch the connection into TLS/SSL mode. However, AutodetectPortAndSslMode property may cause MailBee to automatically enable TLS/SSL for some well-known hosts or ports even if Manual mode is selected.
OnConnect | 1 | The entire conversation with the mail server will take place under TLS/SSL layer. To use this mode, the developer should connect to the mail server on dedicated TLS/SSL port (usually, 465 for SMTP, 995 for POP3, and 993 for IMAP4).
UseStartTls | 2 | The mailer component will automatically call StartTls method when appropriate (prior to login for POP3/IMAP4, prior to hello for SMTP). No dedicated SSL/TLS port is required (the connection should be made to the regular SMTP, POP3, or IMAP4 port). Also, some SMTP servers use the special port 587 for StartTLS - the client MUST switch the connection into secure mode using StartTLS after establishing the connection to port 587. This is different from connecting to port 25 where the client MAY switch the connection into secure mode (it's up to the client to decide). StartTLS approach provides the same security level as OnConnect. However, the mail server must support STARTTLS (STLS for POP3) extension.
UseStartTlsIfSupported | 3 | Similar to UseStartTls but does not require the server support STARTTLS. If the server supports STARTTLS, MailBee will use it. If STARTTLS is not supported, MailBee will not issue this command and the entire session will not be SSL-encrypted.
Remarks
SslMode property of SmtpServer, Pop3, or Imap classes can be used to set any of the values provided by this enumeration.
See Also

Reference

MailBee.Security Namespace


MailBee.SmtpMail Namespace

MailBee.SmtpMail Namespace

MailBee.SmtpMail namespace contains classes, interfaces and enumerations which can be used by your applications to send mail messages using SMTP protocol. Mail messages can be sent to SMTP relay server, directly to end recipients servers (via DNS MX lookup), or to both. Backup servers can be specified for increased reliability of send mail operations. Another supported operations are submitting messages to MailBee Message Queue or IIS SMTP pickup folder, sending custom commands to the server, authenticating using secure methods, and more.

MailBee supports many popular ESMTP extensions (including PIPELINING), which greatly increases performance of sending messages.

SmtpMail.Smtp (main class of this namespace) is declared as a component, which means you can also just drop it onto your application form instead of creating an instance in the code.

"Quick" methods are also supported, which allows you to send mail in a single line of code.

Powerful mail merge (bulk mailing) capabilities with database support allow sending large volumes of e-mails. Concept of jobs allows the developer to assign a job (which consists of processing a single mail or mail merge), process it, analyze the results, and optionally retry processing failed e-mails again.

The component has built-in support for secure connections (TLS/SSL) and proxy servers (SOCKS4/SOCKS5/HTTP).

Some features (mostly, mail merge over database) are not supported in .NET Core and UWP. Also, UWP apps must use async methods whenever possible.

Classes
 | Class | Description
 | DeliveryNotificationOptions | Provides properties and methods which control how and when ESMTP Delivery Status Notifications (DSN) are sent.
Public class | DirectSendServerConfig | Provides properties which specify SMTP server settings to be used by Smtp component for SMTP servers found through MX lookup.
Public class | MailBeeDnsRecordsDisabledException | The exception that is thrown when there was an attempt to request DNS records for a non-existent domain or a domain which is dead.
Public class | MailBeeMXRecordsDisabledException | The exception that is thrown when there was an attempt to request DNS MX records for a non-existent domain or a domain whose SMTP MX servers are not responsive.
Public class | MailBeeSmtp8bitDataNotSupportedException | The exception that is thrown when the message contains 8bit data while the SMTP server is capable of transmitting 7bit data only.
Public class | MailBeeSmtpLoginBadCredentialsException | The exception that is thrown when the SMTP server reports the given user account name and/or password is incorrect.
Public class | MailBeeSmtpLoginBadMethodException | The exception that is thrown when the SMTP server reports the given ESMTP SASL authentication method is not supported and use of another authentication methods is not allowed by the application.
Public class | MailBeeSmtpLoginNegativeResponseException | An abstract parent for all exceptions which indicate the SMTP server replied with a negative response during authentication of the user.
Public class | MailBeeSmtpMessageNotAllowedException | An abstract parent for all exceptions that are thrown when the component determines the message could not be submitted to the SMTP server even before starting the actual submission.
Public class | MailBeeSmtpMessageSizeOutOfRangeException | The exception that is thrown when the component determines the size of the message data exceeds the maximum size allowed by the SMTP server.
Public class | MailBeeSmtpNegativeResponseException | The exception that is thrown when the SMTP server responds with a negative reply (4xx or 5xx, such as 501).
Public class | MailBeeSmtpNoAcceptedRecipientsException | The exception that is thrown when the SMTP server refuses all the recipients submitted during the send mail operation.
Public class | MailBeeSmtpOptionalCommandNotSupportedException | The exception that is thrown when the SMTP server responds with a negative reply to an optional SMTP command.
Public class | MailBeeSmtpRefusedDataException | The exception that is thrown when the SMTP server refuses the message data submitted by the client or even refuses to start receiving the message data from the client.
Public class | MailBeeSmtpRefusedRecipientException | The exception that is thrown when the SMTP server refuses to deliver the mail message to the specified recipient.
Public class | MailBeeSmtpRefusedSenderException | The exception that is thrown when the SMTP server refuses to deliver the mail message from the specified sender.
Public class | MailBeeSmtpSendNegativeResponseException | The exception that is thrown when the SMTP server responds with a negative reply (4xx or 5xx, such as 501) during send mail operation.
Public class | SendMailJob | Represents a task to send (or submit to the pickup folder) a single e-mail message or a series of e-mail messages created as a mail merge of a data table and an e-mail template.
Public class | SendMailJobCollection | Represents a collection of assigned tasks of sending e-mails.
 | Smtp | Provides properties and methods for sending messages using the SMTP protocol.
Public class | SmtpFinishingJobEventArgs | Contains the event data for FinishingJob event.
Public class | SmtpMergingMessageEventArgs | Contains the event data for MergingMessage event.
Public class | SmtpMessageDataChunkSentEventArgs | Contains the event data for MessageDataChunkSent event.
Public class | SmtpMessageDirectSendDoneEventArgs | Contains the event data for MessageDirectSendDone event.
Public class | SmtpMessageMXLookupDoneEventArgs | Contains the event data for MessageMXLookupDone event.
Public class | SmtpMessageNotSentEventArgs | Contains the event data for MessageNotSent event.
Public class | SmtpMessageRecipientSubmittedEventArgs | Contains the event data for MessageRecipientSubmitted event.
Public class | SmtpMessageSenderSubmittedEventArgs | Contains the event data for MessageSenderSubmitted event.
Public class | SmtpMessageSentEventArgs | Contains the event data for MessageSent event.
Public class | SmtpMessageSubmittedToPickupFolderEventArgs | Contains the event data for MessageSubmittedToPickupFolder event.
Public class | SmtpMessageSubmittedToServerEventArgs | Contains the event data for MessageSubmittedToServer event.
Public class | SmtpSendingMessageEventArgs | Contains the event data for SendingMessage event.
 | SmtpServer | Represents an SMTP relay server to which the mail messages will be sent.
Public class | SmtpServerCollection | Represents a sorted collection of SmtpServer objects.
Public class | SmtpSubmittingMessageToPickupFolderEventArgs | Contains the event data for SubmittingMessageToPickupFolder event.
Public class | SmtpTransientErrorOccurredEventArgs | Contains the event data for TransientErrorOccurred event.
Interfaces
 | Interface | Description
Public interface | IMailBeeNegativeSmtpResponseException | When implemented by an exception class, indicates the SMTP server returned negative response. The response data is available in text (i.e. string) form, and SMTP response status code is also available.
Public interface | IMailBeeSendException | When implemented by an exception class, indicates the exception is related to send mail operation. The list of the recipients, the sender e-mail address, and the mail message itself is available.
Public interface | IMailBeeSmtpSendException | When implemented by an exception class, indicates the exception is related to send mail to an SMTP server.
Public interface | IMailBeeSmtpSendNeedsResetException | When implemented by an exception class, indicates RSET command was issued to the SMTP server to reset SMTP session and prepare it for sending another message.
Delegates
 | Delegate | Description
Public delegate | SmtpFinishingJobEventHandler | Represents the method that will handle FinishingJob event.
Public delegate | SmtpMergingMessageEventHandler | Represents the method that will handle MergingMessage event.
Public delegate | SmtpMessageDataChunkSentEventHandler | Represents the method that will handle MessageDataChunkSent event.
Public delegate | SmtpMessageDirectSendDoneEventHandler | Represents the method that will handle MessageDirectSendDone event.
Public delegate | SmtpMessageMXLookupDoneEventHandler | Represents the method that will handle MessageMXLookupDone event.
Public delegate | SmtpMessageNotSentEventHandler | Represents the method that will handle MessageNotSent event.
Public delegate | SmtpMessageRecipientSubmittedEventHandler | Represents the method that will handle MessageRecipientSubmitted event.
Public delegate | SmtpMessageSenderSubmittedEventHandler | Represents the method that will handle MessageSenderSubmitted event.
Public delegate | SmtpMessageSentEventHandler | Represents the method that will handle MessageSent event.
Public delegate | SmtpMessageSubmittedToPickupFolderEventHandler | Represents the method that will handle MessageSubmittedToPickupFolder event.
Public delegate | SmtpMessageSubmittedToServerEventHandler | Represents the method that will handle MessageSubmittedToServer event.
Public delegate | SmtpSendingMessageEventHandler | Represents the method that will handle SendingMessage event.
Public delegate | SmtpSubmittingMessageToPickupFolderEventHandler | Represents the method that will handle SubmittingMessageToPickupFolder event.
Public delegate | SmtpTransientErrorOccurredEventHandler | Represents the method that will handle TransientErrorOccurred event.
Enumerations
 | Enumeration | Description
Public enumeration | DsnNotifyCondition | Specifies events that trigger ESMTP server to send delivery status notification back to the sender of the message.
Public enumeration | DsnReturnPortion | Specifies how much of the original message is returned with the delivery status notification when the message delivery fails.
Public enumeration | ExtendedSmtpOptions | Provides flags specifying which ESMTP extensions will be enabled during SMTP session.
Public enumeration | SendFailureThreshold | Specifies whether TestSend(SendFailureThreshold) method should report error if sending failed to at least one recipient, or to all recipients.
Public enumeration | Smtp8bitDataConversion | Defines the available actions to perform when the message contains 8bit data when the SMTP server does not support transmission of 8bit data.
Public enumeration | TestSendResult | Provides values returned by TestSend(SendFailureThreshold) method as the result of test send operation.


SmtpFinishingJobEventArgs Class

SmtpFinishingJobEventArgs Class
Contains the event data for FinishingJob event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpFinishingJobEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpFinishingJobEventArgs : CommonEventArgs
Public Class SmtpFinishingJobEventArgs
    Inherits CommonEventArgs

The SmtpFinishingJobEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | IsSuccessful | Gets if the job was completed successfully.
Public property | Job | Gets the job which is about to be finished.
Public property | KeepIt | Gets or sets whether to put this job in the collections of finished jobs.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpFinishingJobEventArgs Methods

SmtpFinishingJobEventArgs Methods

The SmtpFinishingJobEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpFinishingJobEventArgs Class
MailBee.SmtpMail Namespace


SmtpFinishingJobEventArgs Properties

SmtpFinishingJobEventArgs Properties

The SmtpFinishingJobEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | IsSuccessful | Gets if the job was completed successfully.
Public property | Job | Gets the job which is about to be finished.
Public property | KeepIt | Gets or sets whether to put this job in the collections of finished jobs.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

SmtpFinishingJobEventArgs Class
MailBee.SmtpMail Namespace


SmtpFinishingJobEventArgs.IsSuccessful Property

SmtpFinishingJobEventArgsIsSuccessful Property
Gets if the job was completed successfully.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSuccessful { get; }
Public ReadOnly Property IsSuccessful As Boolean
    Get

Property Value

Type: Boolean
true if the job succeeded; otherwise, false.
Remarks

This property just returns true when ErrorReason of the Job object is not set.

You can use this property to decide whether to destroy the job after this event completes. For instance, keep failed jobs for later reuse with RetryFailedJobs method and remove successful jobs so that they wouldn't occupy memory. See KeepIt property for details.

See Also

Reference

SmtpFinishingJobEventArgs Class
MailBee.SmtpMail Namespace


SmtpFinishingJobEventArgs.Job Property

SmtpFinishingJobEventArgsJob Property
Gets the job which is about to be finished.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SendMailJob Job { get; }
Public ReadOnly Property Job As SendMailJob
    Get

Property Value

Type: SendMailJob
A reference to the SendMailJob object representing the finished job of sending an individual e-mail or mail merge series.
Remarks

The finished job may be successful or failed. Use IsSuccessful property to check this.

At the moment of this event, Job object has not yet been moved into JobsSuccessful or JobsFailed collections and retains in JobsRunning. Use KeepIt property to let MailBee know what to do with this job upon completion.

See Also

Reference

SmtpFinishingJobEventArgs Class
MailBee.SmtpMail Namespace


SmtpFinishingJobEventArgs.KeepIt Property

SmtpFinishingJobEventArgsKeepIt Property
Gets or sets whether to put this job in the collections of finished jobs.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool KeepIt { get; set; }
Public Property KeepIt As Boolean
    Get
    Set

Property Value

Type: Boolean
Set to true to add the Job object to JobsSuccessful or JobsFailed collections (depending on whether it's successful or failed job). Set to false to destroy the Job object instead of adding it to any of these collections after this event handler completes.
Remarks

This property is mainly for jobs of sending individual e-mails rather than for mail merge jobs. With a mail merge job, you can control what happens with the sub-jobs produced during the mail merge process, using AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) method and its keepProducedJobs parameter.

Still, this property can be used with mail merge too although it's not as required. By default, MailBee retains all the sub-jobs in the mail merge series but you will still not end up with 1000 e-mail messages in memory because for 999 sub-jobs only their index in mail merge table will be preserved. The generated e-mail will be retained only for the last sub-job in the series.

However, if you send millions of e-mails, even that small footprint of a single sub-job (which contains only the index in mail merge table and a few other small fields) may become too large when multiplied by millions. Although you could set keepProducedJobs to false, you won't get any results in JobsFailed and JobsSuccessful collections until the entire mail merge operation finishes. To overcome this, you can selective set KeepIt to true for every, let's say, 100-th data row

to decrease the number of data in JobsFailed and JobsSuccessful collections by 100 times but still get the picture how the sending goes on.

Or, you can simply use false value for keepProducedJobs, do not use JobsFailed and JobsSuccessful collections at all and monitor the progress only with events (like FinishingJob, MessageSent or MessageNotSent).

See Also

Reference

SmtpFinishingJobEventArgs Class
MailBee.SmtpMail Namespace


SmtpFinishingJobEventHandler Delegate

SmtpFinishingJobEventHandler Delegate
Represents the method that will handle FinishingJob event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpFinishingJobEventHandler(
    Object sender,
    SmtpFinishingJobEventArgs e
)
Public Delegate Sub SmtpFinishingJobEventHandler (
    sender As Object,
    e As SmtpFinishingJobEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpFinishingJobEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs Class

SmtpMergingMessageEventArgs Class
Contains the event data for MergingMessage event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMergingMessageEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMergingMessageEventArgs : CommonEventArgs
Public Class SmtpMergingMessageEventArgs
    Inherits CommonEventArgs

The SmtpMergingMessageEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeIt | Gets or sets whether the current data row will be merged with the mail template.
Public property | MergeRowIndex | Gets the index of the data table row which is about to be merged with the mail message template.
Public property | MergeTable | Gets the data table whose row is about to be merged with the mail message template.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Public property | TemplateDeliveryNotification | Gets the delivery status notification template which is about to be merged with the data from a database table row.
Public property | TemplateMessage | Gets the mail message template which is about to be merged with the data from a database table row.
Public property | TemplateRecipients | Gets the actual recipients template which is about to be merged with the data from a database table row.
Public property | TemplateSenderEmail | Gets the actual sender's e-mail address template which is about to be merged with the data from a database table row.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs Methods

SmtpMergingMessageEventArgs Methods

The SmtpMergingMessageEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs Properties

SmtpMergingMessageEventArgs Properties

The SmtpMergingMessageEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeIt | Gets or sets whether the current data row will be merged with the mail template.
Public property | MergeRowIndex | Gets the index of the data table row which is about to be merged with the mail message template.
Public property | MergeTable | Gets the data table whose row is about to be merged with the mail message template.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Public property | TemplateDeliveryNotification | Gets the delivery status notification template which is about to be merged with the data from a database table row.
Public property | TemplateMessage | Gets the mail message template which is about to be merged with the data from a database table row.
Public property | TemplateRecipients | Gets the actual recipients template which is about to be merged with the data from a database table row.
Public property | TemplateSenderEmail | Gets the actual sender's e-mail address template which is about to be merged with the data from a database table row.
Top
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.MergeDataReader Property

SmtpMergingMessageEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
Remarks
See MergeDataReader for explanations.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.MergeDataReaderColumnNames Property

SmtpMergingMessageEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
Remarks
See MergeDataReaderColumnNames for explanations.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.MergeDataReaderRowValues Property

SmtpMergingMessageEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
Remarks
See MergeDataReaderRowValues for explanations.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.MergeIt Property

SmtpMergingMessageEventArgsMergeIt Property
Gets or sets whether the current data row will be merged with the mail template.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool MergeIt { get; set; }
Public Property MergeIt As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the data row designated by MergeRowIndex will be merged with the mail template and the resulting message will be sent out or submitted to the pickup folder; otherwise, this data row will be skipped so that no e-mail message for this data row will be sent or submitted to the pickup folder. The default value is true.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.MergeRowIndex Property

SmtpMergingMessageEventArgsMergeRowIndex Property
Gets the index of the data table row which is about to be merged with the mail message template.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
An integer value representing an index of the row in MergeTable object to be used for mail merge, or 0 if the input was IDataReader rather than DataTable.
Remarks
The developer can obtain a reference to the DataRow object as follows (in C# syntax): e.MergeTable.Rows[e.MergeRowIndex] where e is an SmtpMergingMessageEventArgs object instance.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.MergeTable Property

SmtpMergingMessageEventArgsMergeTable Property
Gets the data table whose row is about to be merged with the mail message template.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the DataTable object representing the data table for mail merge in case if this is a "mail merge over DataTable" job, or a null reference (Nothing in Visual Basic) for "mail merge over IDataReader" jobs
Remarks
For "mail merge over IDataReader" jobs, see MergeDataReader property.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.Tag Property

SmtpMergingMessageEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.TemplateDeliveryNotification Property

SmtpMergingMessageEventArgsTemplateDeliveryNotification Property
Gets the delivery status notification template which is about to be merged with the data from a database table row.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryNotificationOptions TemplateDeliveryNotification { get; }
Public ReadOnly Property TemplateDeliveryNotification As DeliveryNotificationOptions
    Get

Property Value

Type: DeliveryNotificationOptions
A reference to the DeliveryNotificationOptions object representing the DSN settings specified for the message.
Remarks
If the message is submitted to the pickup folder rather than sent out, DSN settings are ignored.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.TemplateMessage Property

SmtpMergingMessageEventArgsTemplateMessage Property
Gets the mail message template which is about to be merged with the data from a database table row.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage TemplateMessage { get; }
Public ReadOnly Property TemplateMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the mail message template.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.TemplateRecipients Property

SmtpMergingMessageEventArgsTemplateRecipients Property
Gets the actual recipients template which is about to be merged with the data from a database table row.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection TemplateRecipients { get; }
Public ReadOnly Property TemplateRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object representing the actual recipients template.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventArgs.TemplateSenderEmail Property

SmtpMergingMessageEventArgsTemplateSenderEmail Property
Gets the actual sender's e-mail address template which is about to be merged with the data from a database table row.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TemplateSenderEmail { get; }
Public ReadOnly Property TemplateSenderEmail As String
    Get

Property Value

Type: String
The string representing the template of the actual sender's e-mail address.
See Also

Reference

SmtpMergingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpMergingMessageEventHandler Delegate

SmtpMergingMessageEventHandler Delegate
Represents the method that will handle MergingMessage event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMergingMessageEventHandler(
    Object sender,
    SmtpMergingMessageEventArgs e
)
Public Delegate Sub SmtpMergingMessageEventHandler (
    sender As Object,
    e As SmtpMergingMessageEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMergingMessageEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs Class

SmtpMessageDataChunkSentEventArgs Class
Contains the event data for MessageDataChunkSent event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageDataChunkSentEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageDataChunkSentEventArgs : CommonEventArgs
Public Class SmtpMessageDataChunkSentEventArgs
    Inherits CommonEventArgs

The SmtpMessageDataChunkSentEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | BytesJustSent | Gets the number of bytes sent to the server during the operation which raised the current event.
Public property | DataTotalLength | Gets the length (in bytes) of the message data being sent.
Public property | MailMessage | Gets the mail message which is being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | TotalBytesSent | Gets the total length (in bytes) of the already sent data of the message currently being sent.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs Methods

SmtpMessageDataChunkSentEventArgs Methods

The SmtpMessageDataChunkSentEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageDataChunkSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs Properties

SmtpMessageDataChunkSentEventArgs Properties

The SmtpMessageDataChunkSentEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | BytesJustSent | Gets the number of bytes sent to the server during the operation which raised the current event.
Public property | DataTotalLength | Gets the length (in bytes) of the message data being sent.
Public property | MailMessage | Gets the mail message which is being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | TotalBytesSent | Gets the total length (in bytes) of the already sent data of the message currently being sent.
Top
See Also

Reference

SmtpMessageDataChunkSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs.BytesJustSent Property

SmtpMessageDataChunkSentEventArgsBytesJustSent Property
Gets the number of bytes sent to the server during the operation which raised the current event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int BytesJustSent { get; }
Public ReadOnly Property BytesJustSent As Integer
    Get

Property Value

Type: Int32
The number of bytes sent to the server during the operation which raised the current event.
See Also

Reference

SmtpMessageDataChunkSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs.DataTotalLength Property

SmtpMessageDataChunkSentEventArgsDataTotalLength Property
Gets the length (in bytes) of the message data being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int DataTotalLength { get; }
Public ReadOnly Property DataTotalLength As Integer
    Get

Property Value

Type: Int32
The length (in bytes) of the message data to be sent.
Remarks

The following formula can be used to determine percentage of sending the message data to the SMTP server:

sendProgress = (DataTotalLength * 100) / TotalBytesSent.

See Also

Reference

SmtpMessageDataChunkSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs.MailMessage Property

SmtpMessageDataChunkSentEventArgsMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.
See Also

Reference

SmtpMessageDataChunkSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventArgs.TotalBytesSent Property

SmtpMessageDataChunkSentEventArgsTotalBytesSent Property
Gets the total length (in bytes) of the already sent data of the message currently being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TotalBytesSent { get; }
Public ReadOnly Property TotalBytesSent As Integer
    Get

Property Value

Type: Int32
The total length (in bytes) of the already received data of the message currently being sent, including the bytes just sent.
Remarks
If the message is being sent in multiple SMTP sessions (such as to many SMTP MX servers in direct send mode), this value applies to the current SMTP session only. Message data traffic produced during previous SMTP sessions is not counted.
See Also

Reference

SmtpMessageDataChunkSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDataChunkSentEventHandler Delegate

SmtpMessageDataChunkSentEventHandler Delegate
Represents the method that will handle MessageDataChunkSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageDataChunkSentEventHandler(
    Object sender,
    SmtpMessageDataChunkSentEventArgs e
)
Public Delegate Sub SmtpMessageDataChunkSentEventHandler (
    sender As Object,
    e As SmtpMessageDataChunkSentEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageDataChunkSentEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs Class

SmtpMessageDirectSendDoneEventArgs Class
Contains the event data for MessageDirectSendDone event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageDirectSendDoneEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageDirectSendDoneEventArgs : CommonEventArgs
Public Class SmtpMessageDirectSendDoneEventArgs
    Inherits CommonEventArgs

The SmtpMessageDirectSendDoneEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the actual sender of the message.
Public property | FailedRecipients | Gets the list of recipients the message was not delivered to.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which was sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SuccessfulRecipients | Gets the list of recipients the message was successfully delivered to.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs Methods

SmtpMessageDirectSendDoneEventArgs Methods

The SmtpMessageDirectSendDoneEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs Properties

SmtpMessageDirectSendDoneEventArgs Properties

The SmtpMessageDirectSendDoneEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the actual sender of the message.
Public property | FailedRecipients | Gets the list of recipients the message was not delivered to.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which was sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SuccessfulRecipients | Gets the list of recipients the message was successfully delivered to.
Top
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs.ActualSenderEmail Property

SmtpMessageDirectSendDoneEventArgsActualSenderEmail Property
Gets the e-mail address of the actual sender of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
A string value containing the e-mail address of the actual sender of the message.
Remarks
Since Send method can be used to send messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message was sent from.
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs.FailedRecipients Property

SmtpMessageDirectSendDoneEventArgsFailedRecipients Property
Gets the list of recipients the message was not delivered to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection FailedRecipients { get; }
Public ReadOnly Property FailedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients which did not receive the message.
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs.IntendedRecipients Property

SmtpMessageDirectSendDoneEventArgsIntendedRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection IntendedRecipients { get; }
Public ReadOnly Property IntendedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs.MailMessage Property

SmtpMessageDirectSendDoneEventArgsMailMessage Property
Gets the mail message which was sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which was sent.
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventArgs.SuccessfulRecipients Property

SmtpMessageDirectSendDoneEventArgsSuccessfulRecipients Property
Gets the list of recipients the message was successfully delivered to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection SuccessfulRecipients { get; }
Public ReadOnly Property SuccessfulRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients which received the message.
Remarks
The list of recipients returned by this property indicates which recipients have been accepted by SMTP servers the message was submitted to.
Note Note
Although a particular domain's SMTP server may successfully accept the message for delivery (and the recipients of this domain will be added into SuccessfulRecipients) list), it still does not guarantee the server itself will deliver the message to the recipients. Many servers accept non-existent recipient e-mail addresses when the message is being submitted, and then send bounced message back to the sender if certain e-mail address is invalid.
See Also

Reference

SmtpMessageDirectSendDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageDirectSendDoneEventHandler Delegate

SmtpMessageDirectSendDoneEventHandler Delegate
Represents the method that will handle MessageDirectSendDone event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageDirectSendDoneEventHandler(
    Object sender,
    SmtpMessageDirectSendDoneEventArgs e
)
Public Delegate Sub SmtpMessageDirectSendDoneEventHandler (
    sender As Object,
    e As SmtpMessageDirectSendDoneEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageDirectSendDoneEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs Class

SmtpMessageMXLookupDoneEventArgs Class
Contains the event data for MessageMXLookupDone event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageMXLookupDoneEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageMXLookupDoneEventArgs : CommonEventArgs
Public Class SmtpMessageMXLookupDoneEventArgs
    Inherits CommonEventArgs

The SmtpMessageMXLookupDoneEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | FailedDomains | Gets the list of domains MX lookup failed for.
Public property | IntendedDomains | Gets the list of domains of the message recipients.
Public property | MailMessage | Gets the mail message which is being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SuccessfulDomains | Gets the list of domains MX lookup succeeded for.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs Methods

SmtpMessageMXLookupDoneEventArgs Methods

The SmtpMessageMXLookupDoneEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageMXLookupDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs Properties

SmtpMessageMXLookupDoneEventArgs Properties

The SmtpMessageMXLookupDoneEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | FailedDomains | Gets the list of domains MX lookup failed for.
Public property | IntendedDomains | Gets the list of domains of the message recipients.
Public property | MailMessage | Gets the mail message which is being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SuccessfulDomains | Gets the list of domains MX lookup succeeded for.
Top
See Also

Reference

SmtpMessageMXLookupDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs.FailedDomains Property

SmtpMessageMXLookupDoneEventArgsFailedDomains Property
Gets the list of domains MX lookup failed for.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringCollection FailedDomains { get; }
Public ReadOnly Property FailedDomains As StringCollection
    Get

Property Value

Type: StringCollection
A reference to the StringCollection object which contains the list of all recipients domains, for which SMTP servers have been found.
Remarks
If no MX or A records have been reported by the DNS server for the given domain, it means this domain cannot accept mail for delivery. Such domain will be placed into FailedDomains list.
See Also

Reference

SmtpMessageMXLookupDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs.IntendedDomains Property

SmtpMessageMXLookupDoneEventArgsIntendedDomains Property
Gets the list of domains of the message recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringCollection IntendedDomains { get; }
Public ReadOnly Property IntendedDomains As StringCollection
    Get

Property Value

Type: StringCollection
A reference to the StringCollection object which contains the list of all domains the message recipients e-mail addresses belong to.
Remarks
For instance, if the message is addressed to jdoe@domain1.com, bill@domain2.com, kathy@domain2.com, sales@domain2.com, joe@subdomain.domain2.com, the list of domains would be domain1.com, domain2.com, subdomain.domain2.com.
See Also

Reference

SmtpMessageMXLookupDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs.MailMessage Property

SmtpMessageMXLookupDoneEventArgsMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.
See Also

Reference

SmtpMessageMXLookupDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventArgs.SuccessfulDomains Property

SmtpMessageMXLookupDoneEventArgsSuccessfulDomains Property
Gets the list of domains MX lookup succeeded for.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringCollection SuccessfulDomains { get; }
Public ReadOnly Property SuccessfulDomains As StringCollection
    Get

Property Value

Type: StringCollection
A reference to the StringCollection object which contains the list of all recipients domains, for which MX or A records have been found.
Remarks
If at least one MX or A record has been reported by the DNS server for the given domain, it means this domain probably has SMTP service running on the host specified by MX/A record, and can accept mail for delivery. Such domain will be placed into SuccessfulDomains list.
See Also

Reference

SmtpMessageMXLookupDoneEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageMXLookupDoneEventHandler Delegate

SmtpMessageMXLookupDoneEventHandler Delegate
Represents the method that will handle MessageMXLookupDone event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageMXLookupDoneEventHandler(
    Object sender,
    SmtpMessageMXLookupDoneEventArgs e
)
Public Delegate Sub SmtpMessageMXLookupDoneEventHandler (
    sender As Object,
    e As SmtpMessageMXLookupDoneEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageMXLookupDoneEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs Class

SmtpMessageNotSentEventArgs Class
Contains the event data for MessageNotSent event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageNotSentEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageNotSentEventArgs : CommonEventArgs
Public Class SmtpMessageNotSentEventArgs
    Inherits CommonEventArgs

The SmtpMessageNotSentEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which could not be sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | Reason | Gets the exception describing the error which prevented the message from being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs Methods

SmtpMessageNotSentEventArgs Methods

The SmtpMessageNotSentEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs Properties

SmtpMessageNotSentEventArgs Properties

The SmtpMessageNotSentEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which could not be sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | Reason | Gets the exception describing the error which prevented the message from being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.ActualSenderEmail Property

SmtpMessageNotSentEventArgsActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.
Remarks
Since Send method can be used to send messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message was sent from.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.IntendedRecipients Property

SmtpMessageNotSentEventArgsIntendedRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection IntendedRecipients { get; }
Public ReadOnly Property IntendedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.MailMessage Property

SmtpMessageNotSentEventArgsMailMessage Property
Gets the mail message which could not be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which could not be sent.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.MergeDataReader Property

SmtpMessageNotSentEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
Remarks
See MergeDataReader for explanations.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.MergeDataReaderColumnNames Property

SmtpMessageNotSentEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
Remarks
See MergeDataReaderColumnNames for explanations.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.MergeDataReaderRowValues Property

SmtpMessageNotSentEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
Remarks
See MergeDataReaderRowValues for explanations.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.MergeRowIndex Property

SmtpMessageNotSentEventArgsMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageNotSentEventArgs class) returns DataRow used for mail merge of the message which could not be sent.

This property returns zero for mail merge over IDataReader jobs.

See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.MergeTable Property

SmtpMessageNotSentEventArgsMergeTable Property
Gets the reference to the data table used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table used for mail merge of this message, or a null reference (Nothing in Visual Basic) if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge over DataTable operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageNotSentEventArgs class) returns DataRow used for mail merge of the message which could not be sent.

For mail merge over IDataReader jobs, see MergeDataReader property.

See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.Reason Property

SmtpMessageNotSentEventArgsReason Property
Gets the exception describing the error which prevented the message from being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailBeeException Reason { get; }
Public ReadOnly Property Reason As MailBeeException
    Get

Property Value

Type: MailBeeException
A reference to the exception.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventArgs.Tag Property

SmtpMessageNotSentEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpMessageNotSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageNotSentEventHandler Delegate

SmtpMessageNotSentEventHandler Delegate
Represents the method that will handle MessageNotSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageNotSentEventHandler(
    Object sender,
    SmtpMessageNotSentEventArgs e
)
Public Delegate Sub SmtpMessageNotSentEventHandler (
    sender As Object,
    e As SmtpMessageNotSentEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageNotSentEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs Class

SmtpMessageRecipientSubmittedEventArgs Class
Contains the event data for MessageRecipientSubmitted event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageRecipientSubmittedEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageRecipientSubmittedEventArgs : CommonEventArgs
Public Class SmtpMessageRecipientSubmittedEventArgs
    Inherits CommonEventArgs

The SmtpMessageRecipientSubmittedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AllowRefusedRecipient | Gets or sets whether to proceed with sending this message if the server rejected the given recipient.
Public property | MailMessage | Gets the mail message which is being sent.
Public property | RecipientEmail | Gets the e-mail address of the recipient of the mail message.
Public property | Result | Gets the status of submission of the recipient e-mail address to the SMTP server.
Public property | ServerStatusMessage | Gets the string containing the status line of the SMTP server response.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs Methods

SmtpMessageRecipientSubmittedEventArgs Methods

The SmtpMessageRecipientSubmittedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs Properties

SmtpMessageRecipientSubmittedEventArgs Properties

The SmtpMessageRecipientSubmittedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | AllowRefusedRecipient | Gets or sets whether to proceed with sending this message if the server rejected the given recipient.
Public property | MailMessage | Gets the mail message which is being sent.
Public property | RecipientEmail | Gets the e-mail address of the recipient of the mail message.
Public property | Result | Gets the status of submission of the recipient e-mail address to the SMTP server.
Public property | ServerStatusMessage | Gets the string containing the status line of the SMTP server response.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs.AllowRefusedRecipient Property

SmtpMessageRecipientSubmittedEventArgsAllowRefusedRecipient Property
Gets or sets whether to proceed with sending this message if the server rejected the given recipient.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AllowRefusedRecipient { get; set; }
Public Property AllowRefusedRecipient As Boolean
    Get
    Set

Property Value

Type: Boolean
If true or Result is true, will proceed with sending the message; if false and Result is also false, MailBee throw MailBeeSmtpRefusedRecipientException. The default value is SmtpServer.AllowRefusedRecipients.
Remarks

You can set this property value to false in case if you encounter that an important recipient was rejected by the server (this requires you to allow failed recipients first by setting SmtpServer.AllowRefusedRecipients to true.

Or, you can leave SmtpServer.AllowRefusedRecipients in its default state false (so that failed recipients would generally not be allowed) but set AllowRefusedRecipient to true for some particular recipients which you find not important.

See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs.MailMessage Property

SmtpMessageRecipientSubmittedEventArgsMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.
See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs.RecipientEmail Property

SmtpMessageRecipientSubmittedEventArgsRecipientEmail Property
Gets the e-mail address of the recipient of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RecipientEmail { get; }
Public ReadOnly Property RecipientEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) of the mail message recipient which was accepted or refused by the SMTP server.
See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs.Result Property

SmtpMessageRecipientSubmittedEventArgsResult Property
Gets the status of submission of the recipient e-mail address to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Result { get; }
Public ReadOnly Property Result As Boolean
    Get

Property Value

Type: Boolean
true if the recipient e-mail address was accepted by the SMTP server; false is the SMTP server rejected this address.
See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventArgs.ServerStatusMessage Property

SmtpMessageRecipientSubmittedEventArgsServerStatusMessage Property
Gets the string containing the status line of the SMTP server response.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ServerStatusMessage { get; }
Public ReadOnly Property ServerStatusMessage As String
    Get

Property Value

Type: String
The status string of the SMTP server response to the recipient submission attempt.
Remarks

This value can be used to determine why the server refused a certain recipient.

Examples of the values returned by this property:

  • 250 good@address.com accepted (positive)
  • 501 bad@@@address.com syntax error (negative)

See Also

Reference

SmtpMessageRecipientSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageRecipientSubmittedEventHandler Delegate

SmtpMessageRecipientSubmittedEventHandler Delegate
Represents the method that will handle MessageRecipientSubmitted event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageRecipientSubmittedEventHandler(
    Object sender,
    SmtpMessageRecipientSubmittedEventArgs e
)
Public Delegate Sub SmtpMessageRecipientSubmittedEventHandler (
    sender As Object,
    e As SmtpMessageRecipientSubmittedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageRecipientSubmittedEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSenderSubmittedEventArgs Class

SmtpMessageSenderSubmittedEventArgs Class
Contains the event data for MessageSenderSubmitted event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageSenderSubmittedEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageSenderSubmittedEventArgs : CommonEventArgs
Public Class SmtpMessageSenderSubmittedEventArgs
    Inherits CommonEventArgs

The SmtpMessageSenderSubmittedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | MailMessage | Gets the mail message which is being sent.
Public property | SenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSenderSubmittedEventArgs Methods

SmtpMessageSenderSubmittedEventArgs Methods

The SmtpMessageSenderSubmittedEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageSenderSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSenderSubmittedEventArgs Properties

SmtpMessageSenderSubmittedEventArgs Properties

The SmtpMessageSenderSubmittedEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | MailMessage | Gets the mail message which is being sent.
Public property | SenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

SmtpMessageSenderSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSenderSubmittedEventArgs.MailMessage Property

SmtpMessageSenderSubmittedEventArgsMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.
See Also

Reference

SmtpMessageSenderSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSenderSubmittedEventArgs.SenderEmail Property

SmtpMessageSenderSubmittedEventArgsSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SenderEmail { get; }
Public ReadOnly Property SenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) of the mail message sender which was accepted by the SMTP server.
See Also

Reference

SmtpMessageSenderSubmittedEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSenderSubmittedEventHandler Delegate

SmtpMessageSenderSubmittedEventHandler Delegate
Represents the method that will handle MessageSenderSubmitted event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageSenderSubmittedEventHandler(
    Object sender,
    SmtpMessageSenderSubmittedEventArgs e
)
Public Delegate Sub SmtpMessageSenderSubmittedEventHandler (
    sender As Object,
    e As SmtpMessageSenderSubmittedEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageSenderSubmittedEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs Class

SmtpMessageSentEventArgs Class
Contains the event data for MessageSent event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageSentEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageSentEventArgs : CommonEventArgs
Public Class SmtpMessageSentEventArgs
    Inherits CommonEventArgs

The SmtpMessageSentEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | FailedRecipients | Gets the list of recipients the message was not delivered to.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which was sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SuccessfulRecipients | Gets the list of recipients the message was successfully delivered to.
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs Methods

SmtpMessageSentEventArgs Methods

The SmtpMessageSentEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs Properties

SmtpMessageSentEventArgs Properties

The SmtpMessageSentEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | FailedRecipients | Gets the list of recipients the message was not delivered to.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which was sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SuccessfulRecipients | Gets the list of recipients the message was successfully delivered to.
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.ActualSenderEmail Property

SmtpMessageSentEventArgsActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.
Remarks
Since Send method can be used to send messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message was sent from.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.FailedRecipients Property

SmtpMessageSentEventArgsFailedRecipients Property
Gets the list of recipients the message was not delivered to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection FailedRecipients { get; }
Public ReadOnly Property FailedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients which did not receive the message.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.IntendedRecipients Property

SmtpMessageSentEventArgsIntendedRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection IntendedRecipients { get; }
Public ReadOnly Property IntendedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.MailMessage Property

SmtpMessageSentEventArgsMailMessage Property
Gets the mail message which was sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which was sent.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.MergeDataReader Property

SmtpMessageSentEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
Remarks
See MergeDataReader for explanations.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.MergeDataReaderColumnNames Property

SmtpMessageSentEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
Remarks
See MergeDataReaderColumnNames for explanations.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.MergeDataReaderRowValues Property

SmtpMessageSentEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
Remarks
See MergeDataReaderRowValues for explanations.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.MergeRowIndex Property

SmtpMessageSentEventArgsMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageSentEventArgs class) returns DataRow used for mail merge of the message sent.

This property returns zero for mail merge over IDataReader jobs.

See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.MergeTable Property

SmtpMessageSentEventArgsMergeTable Property
Gets the reference to the data table used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table used for mail merge of this message, or a null reference (Nothing in Visual Basic) if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge over DataTable operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageSentEventArgs class) returns DataRow used for mail merge of the message sent.

For mail merge over IDataReader jobs, see MergeDataReader property.

See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.SuccessfulRecipients Property

SmtpMessageSentEventArgsSuccessfulRecipients Property
Gets the list of recipients the message was successfully delivered to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection SuccessfulRecipients { get; }
Public ReadOnly Property SuccessfulRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients which received the message.
Remarks
The list of recipients returned by this property indicates which recipients have been accepted by SMTP servers the message was submitted to.
Note Note
Although a particular domain's SMTP server may successfully accept the message for delivery (and the recipients of this domain will be added into SuccessfulRecipients) list), it still does not guarantee the server itself will deliver the message to the recipients. Many servers accept non-existent recipient e-mail addresses when the message is being submitted, and then send bounced message back to the sender if certain e-mail address is invalid.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventArgs.Tag Property

SmtpMessageSentEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpMessageSentEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSentEventHandler Delegate

SmtpMessageSentEventHandler Delegate
Represents the method that will handle MessageSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageSentEventHandler(
    Object sender,
    SmtpMessageSentEventArgs e
)
Public Delegate Sub SmtpMessageSentEventHandler (
    sender As Object,
    e As SmtpMessageSentEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageSentEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs Class

SmtpMessageSubmittedToPickupFolderEventArgs Class
Contains the event data for MessageSubmittedToPickupFolder event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageSubmittedToPickupFolderEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageSubmittedToPickupFolderEventArgs : CommonEventArgs
Public Class SmtpMessageSubmittedToPickupFolderEventArgs
    Inherits CommonEventArgs

The SmtpMessageSubmittedToPickupFolderEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Filename | Gets the filename of the saved message file.
Public property | MailMessage | Gets the mail message which was submitted to IIS SMTP queue (pickup folder).
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | PickupFolderName | Gets the full physical path to the folder the message file was saved in.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs Methods

SmtpMessageSubmittedToPickupFolderEventArgs Methods

The SmtpMessageSubmittedToPickupFolderEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs Properties

SmtpMessageSubmittedToPickupFolderEventArgs Properties

The SmtpMessageSubmittedToPickupFolderEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Filename | Gets the filename of the saved message file.
Public property | MailMessage | Gets the mail message which was submitted to IIS SMTP queue (pickup folder).
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | PickupFolderName | Gets the full physical path to the folder the message file was saved in.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.ActualRecipients Property

SmtpMessageSubmittedToPickupFolderEventArgsActualRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; }
Public ReadOnly Property ActualRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.ActualSenderEmail Property

SmtpMessageSubmittedToPickupFolderEventArgsActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) of the message sender.
Remarks
Since MailBee allows sending messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message was sent from.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.Filename Property

SmtpMessageSubmittedToPickupFolderEventArgsFilename Property
Gets the filename of the saved message file.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; }
Public ReadOnly Property Filename As String
    Get

Property Value

Type: String
The filename (without folder path) under which the queued message file was saved in the queue folder.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.MailMessage Property

SmtpMessageSubmittedToPickupFolderEventArgsMailMessage Property
Gets the mail message which was submitted to IIS SMTP queue (pickup folder).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the mail message just queued.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.MergeDataReader Property

SmtpMessageSubmittedToPickupFolderEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
Remarks
See MergeDataReader for explanations.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.MergeDataReaderColumnNames Property

SmtpMessageSubmittedToPickupFolderEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
Remarks
See MergeDataReaderColumnNames for explanations.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.MergeDataReaderRowValues Property

SmtpMessageSubmittedToPickupFolderEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
Remarks
See MergeDataReaderRowValues for explanations.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.MergeRowIndex Property

SmtpMessageSubmittedToPickupFolderEventArgsMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageSubmittedToPickupFolderEventArgs class) returns DataRow used for mail merge of the message just enqueued.

This property returns zero for mail merge over IDataReader jobs.

See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.MergeTable Property

SmtpMessageSubmittedToPickupFolderEventArgsMergeTable Property
Gets the reference to the data table used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table used for mail merge of this message, or a null reference (Nothing in Visual Basic) if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge over DataTable operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageSubmittedToPickupFolderEventArgs class) returns DataRow used for mail merge of the message just enqueued.

For mail merge over IDataReader jobs, see MergeDataReader property.

See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.PickupFolderName Property

SmtpMessageSubmittedToPickupFolderEventArgsPickupFolderName Property
Gets the full physical path to the folder the message file was saved in.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string PickupFolderName { get; }
Public ReadOnly Property PickupFolderName As String
    Get

Property Value

Type: String
The full physical path to the folder in which the message file was saved.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventArgs.Tag Property

SmtpMessageSubmittedToPickupFolderEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpMessageSubmittedToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToPickupFolderEventHandler Delegate

SmtpMessageSubmittedToPickupFolderEventHandler Delegate
Represents the method that will handle MessageSubmittedToPickupFolder event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageSubmittedToPickupFolderEventHandler(
    Object sender,
    SmtpMessageSubmittedToPickupFolderEventArgs e
)
Public Delegate Sub SmtpMessageSubmittedToPickupFolderEventHandler (
    sender As Object,
    e As SmtpMessageSubmittedToPickupFolderEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageSubmittedToPickupFolderEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs Class

SmtpMessageSubmittedToServerEventArgs Class
Contains the event data for MessageSubmittedToServer event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpMessageSubmittedToServerEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpMessageSubmittedToServerEventArgs : CommonEventArgs
Public Class SmtpMessageSubmittedToServerEventArgs
    Inherits CommonEventArgs

The SmtpMessageSubmittedToServerEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AcceptedRecipients | Gets the list of all recipients which were accepted by the SMTP server.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which was successfully submitted to the SMTP server.
Public property | RefusedRecipients | Gets the list of all recipients which were refused by the SMTP server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs Methods

SmtpMessageSubmittedToServerEventArgs Methods

The SmtpMessageSubmittedToServerEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs Properties

SmtpMessageSubmittedToServerEventArgs Properties

The SmtpMessageSubmittedToServerEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | AcceptedRecipients | Gets the list of all recipients which were accepted by the SMTP server.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which was successfully submitted to the SMTP server.
Public property | RefusedRecipients | Gets the list of all recipients which were refused by the SMTP server.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Top
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs.AcceptedRecipients Property

SmtpMessageSubmittedToServerEventArgsAcceptedRecipients Property
Gets the list of all recipients which were accepted by the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection AcceptedRecipients { get; }
Public ReadOnly Property AcceptedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients which were accepted by the SMTP server.
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs.ActualSenderEmail Property

SmtpMessageSubmittedToServerEventArgsActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.
Remarks
Since Send method can be used to send messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message was sent from.
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs.IntendedRecipients Property

SmtpMessageSubmittedToServerEventArgsIntendedRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection IntendedRecipients { get; }
Public ReadOnly Property IntendedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs.MailMessage Property

SmtpMessageSubmittedToServerEventArgsMailMessage Property
Gets the mail message which was successfully submitted to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the mail message which was successfully submitted to the SMTP server.
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventArgs.RefusedRecipients Property

SmtpMessageSubmittedToServerEventArgsRefusedRecipients Property
Gets the list of all recipients which were refused by the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection RefusedRecipients { get; }
Public ReadOnly Property RefusedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients which were refused by the SMTP server.
See Also

Reference

SmtpMessageSubmittedToServerEventArgs Class
MailBee.SmtpMail Namespace


SmtpMessageSubmittedToServerEventHandler Delegate

SmtpMessageSubmittedToServerEventHandler Delegate
Represents the method that will handle MessageSubmittedToServer event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpMessageSubmittedToServerEventHandler(
    Object sender,
    SmtpMessageSubmittedToServerEventArgs e
)
Public Delegate Sub SmtpMessageSubmittedToServerEventHandler (
    sender As Object,
    e As SmtpMessageSubmittedToServerEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpMessageSubmittedToServerEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs Class

SmtpSendingMessageEventArgs Class
Contains the event data for SendingMessage event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpSendingMessageEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpSendingMessageEventArgs : CommonEventArgs
Public Class SmtpSendingMessageEventArgs
    Inherits CommonEventArgs

The SmtpSendingMessageEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets or sets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets or sets the e-mail address of the sender of the mail message.
Public property | DeliveryNotification | Gets the delivery status notification settings of the mail message to be sent.
Public property | MailMessage | Gets the mail message which is about to be sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | SendIt | Gets or sets whether this message will be sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs Methods

SmtpSendingMessageEventArgs Methods

The SmtpSendingMessageEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs Properties

SmtpSendingMessageEventArgs Properties

The SmtpSendingMessageEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets or sets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets or sets the e-mail address of the sender of the mail message.
Public property | DeliveryNotification | Gets the delivery status notification settings of the mail message to be sent.
Public property | MailMessage | Gets the mail message which is about to be sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | SendIt | Gets or sets whether this message will be sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.ActualRecipients Property

SmtpSendingMessageEventArgsActualRecipients Property
Gets or sets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; set; }
Public Property ActualRecipients As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
Remarks

Since MailBee allows sending messages to e-mail addresses different from the addresses specified by To, Cc, and Bcc properties, the developer can use ActualRecipients property to obtain the actual addresses the message is sent to.

The developer may also set this property to change the recipients of the mail message. Passing a null reference (Nothing in Visual Basic) will make the message be sent to the recipients returned by GetAllRecipients method.

See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.ActualSenderEmail Property

SmtpSendingMessageEventArgsActualSenderEmail Property
Gets or sets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; set; }
Public Property ActualSenderEmail As String
    Get
    Set

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) of the message sender.
Remarks

Since MailBee allows sending messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message is sent from.

The developer may also set this address to change the sender of the mail message. Passing a null reference (Nothing in Visual Basic) will make the message be sent from From address.

See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.DeliveryNotification Property

SmtpSendingMessageEventArgsDeliveryNotification Property
Gets the delivery status notification settings of the mail message to be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryNotificationOptions DeliveryNotification { get; }
Public ReadOnly Property DeliveryNotification As DeliveryNotificationOptions
    Get

Property Value

Type: DeliveryNotificationOptions
A reference to the DeliveryNotificationOptions object representing the DSN settings specified for the message.
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.MailMessage Property

SmtpSendingMessageEventArgsMailMessage Property
Gets the mail message which is about to be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the mail message to be sent.
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.MergeDataReader Property

SmtpSendingMessageEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
A reference to the data reader if it was passed as an input, or a null reference (Nothing in Visual Basic) if the input wasn't a data reader.
Remarks
Note that you must not advance the position of data reader (such as with Read method). MailBee will do this itself. Also, if the mail merge process is multi-threaded, you cannot use this property to access the current row. Another thread may already use the reader to read the next data row. Use MergeDataReaderRowValues and MergeDataReaderColumnNames propeties to read the field values corresponding to the current row.
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.MergeDataReaderColumnNames Property

SmtpSendingMessageEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
A reference to the string array where each item is the result of GetName(Int32) call for each column, made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks

Can be used in conjunction with MergeDataReaderRowValues property to access elements by their names, such as with e.MergeDataReaderRowValues[Array.IndexOf(e.MergeDataReaderColumnNames, "id")] call (in C# syntax, assuming e is SmtpSendingMessageEventArgs instance).

If you know the index of the field you need to access, you can use it directly, such as e.MergeDataReaderRowValues[0].

See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.MergeDataReaderRowValues Property

SmtpSendingMessageEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
A reference to the result of GetValues(Object) call made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks
This property is useful in case of multi-threaded mail merge when the IDataReader could have already advance to next records to the moment when this event occurs. It guarantees that the data in this array will correspond to that e-mail address for which this event was raised.
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.MergeRowIndex Property

SmtpSendingMessageEventArgsMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpSendingMessageEventArgs class) returns DataRow used for mail merge of the message being sent.

This property returns zero for mail merge over IDataReader jobs.

See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.MergeTable Property

SmtpSendingMessageEventArgsMergeTable Property
Gets the reference to the data table used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table used for mail merge of this message, or a null reference (Nothing in Visual Basic) if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge over DataTable operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpSendingMessageEventArgs class) returns DataRow used for mail merge of the message being sent.

For mail merge over IDataReader jobs, see MergeDataReader property.

See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.SendIt Property

SmtpSendingMessageEventArgsSendIt Property
Gets or sets whether this message will be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SendIt { get; set; }
Public Property SendIt As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the message will be sent; otherwise, it will be ignored. The default value is true.
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventArgs.Tag Property

SmtpSendingMessageEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpSendingMessageEventArgs Class
MailBee.SmtpMail Namespace


SmtpSendingMessageEventHandler Delegate

SmtpSendingMessageEventHandler Delegate
Represents the method that will handle SendingMessage event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpSendingMessageEventHandler(
    Object sender,
    SmtpSendingMessageEventArgs e
)
Public Delegate Sub SmtpSendingMessageEventHandler (
    sender As Object,
    e As SmtpSendingMessageEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpSendingMessageEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs Class

SmtpSubmittingMessageToPickupFolderEventArgs Class
Contains the event data for SubmittingMessageToPickupFolder event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpSubmittingMessageToPickupFolderEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpSubmittingMessageToPickupFolderEventArgs : CommonEventArgs
Public Class SmtpSubmittingMessageToPickupFolderEventArgs
    Inherits CommonEventArgs

The SmtpSubmittingMessageToPickupFolderEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets or sets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets or sets the e-mail address of the sender of the mail message.
Public property | Filename | Gets or sets the filename of the message file to be saved in the pickup folder.
Public property | MailMessage | Gets the mail message which is about to be submitted to MailBee.NET Queue or IIS SMTP pickup folder.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | PickupFolderName | Gets or sets the full physical path to MailBee.NET Queue or IIS SMTP pickup folder.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SubmitIt | Gets or sets whether this message will be submitted to MailBee.NET Queue or IIS SMTP pickup folder.
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs Methods

SmtpSubmittingMessageToPickupFolderEventArgs Methods

The SmtpSubmittingMessageToPickupFolderEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs Properties

SmtpSubmittingMessageToPickupFolderEventArgs Properties

The SmtpSubmittingMessageToPickupFolderEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets or sets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets or sets the e-mail address of the sender of the mail message.
Public property | Filename | Gets or sets the filename of the message file to be saved in the pickup folder.
Public property | MailMessage | Gets the mail message which is about to be submitted to MailBee.NET Queue or IIS SMTP pickup folder.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | PickupFolderName | Gets or sets the full physical path to MailBee.NET Queue or IIS SMTP pickup folder.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | SubmitIt | Gets or sets whether this message will be submitted to MailBee.NET Queue or IIS SMTP pickup folder.
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.ActualRecipients Property

SmtpSubmittingMessageToPickupFolderEventArgsActualRecipients Property
Gets or sets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; set; }
Public Property ActualRecipients As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
Remarks

Since MailBee allows sending messages to e-mail addresses different from the addresses specified by To, Cc, and Bcc properties, the developer can use ActualRecipients property to obtain the actual addresses the message is sent to.

The developer may also set this property to change the recipients of the mail message. Passing a null reference (Nothing in Visual Basic) will make the message be sent to the recipients returned by GetAllRecipients method.

See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.ActualSenderEmail Property

SmtpSubmittingMessageToPickupFolderEventArgsActualSenderEmail Property
Gets or sets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; set; }
Public Property ActualSenderEmail As String
    Get
    Set

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) of the message sender.
Remarks

Since MailBee allows sending messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message is sent from.

The developer may also set this address to change the sender of the mail message. Passing a null reference (Nothing in Visual Basic) will make the message be sent from From address.

See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.Filename Property

SmtpSubmittingMessageToPickupFolderEventArgsFilename Property
Gets or sets the filename of the message file to be saved in the pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Filename { get; set; }
Public Property Filename As String
    Get
    Set

Property Value

Type: String
The filename (without folder path) under which the message file will be saved in MailBee.NET Queue or IIS SMTP pickup folder (for instance, "app18_10469.eml"). The default value is a null reference (Nothing in Visual Basic).
Remarks
By default, this value is a null reference. In this case, MailBee will automatically generate a unique filename for the queued message file. The developer can change the value of this property to employ a special naming schema for message files. Filenames auto-generated by MailBee look like "0ac5356fb20417188a04f4ec3f219ce5.eml".
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.MailMessage Property

SmtpSubmittingMessageToPickupFolderEventArgsMailMessage Property
Gets the mail message which is about to be submitted to MailBee.NET Queue or IIS SMTP pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the mail message to be submitted to the pickup folder.
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.MergeDataReader Property

SmtpSubmittingMessageToPickupFolderEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
Remarks
See MergeDataReader for explanations.
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.MergeDataReaderColumnNames Property

SmtpSubmittingMessageToPickupFolderEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
Remarks
See MergeDataReaderColumnNames for explanations.
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.MergeDataReaderRowValues Property

SmtpSubmittingMessageToPickupFolderEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
Remarks
See MergeDataReaderRowValues for explanations.
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.MergeRowIndex Property

SmtpSubmittingMessageToPickupFolderEventArgsMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpSubmittingMessageToPickupFolderEventArgs class) returns DataRow used for mail merge of the message being submitted to the pickup folder.

This property returns zero for mail merge over IDataReader jobs.

See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.MergeTable Property

SmtpSubmittingMessageToPickupFolderEventArgsMergeTable Property
Gets the reference to the data table used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table used for mail merge of this message, or a null reference (Nothing in Visual Basic) if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge over DataTable operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpSubmittingMessageToPickupFolderEventArgs class) returns DataRow used for mail merge of the message being submitted to the pickup folder.

For mail merge over IDataReader jobs, see MergeDataReader property.

See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.PickupFolderName Property

SmtpSubmittingMessageToPickupFolderEventArgsPickupFolderName Property
Gets or sets the full physical path to MailBee.NET Queue or IIS SMTP pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string PickupFolderName { get; set; }
Public Property PickupFolderName As String
    Get
    Set

Property Value

Type: String
The full physical path to MailBee.NET or IIS SMTP pickup folder where the mail message should be saved (such as "C:\Inetpub\mailroot\Pickup").
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is an empty string or a null reference (Nothing in Visual Basic).
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.SubmitIt Property

SmtpSubmittingMessageToPickupFolderEventArgsSubmitIt Property
Gets or sets whether this message will be submitted to MailBee.NET Queue or IIS SMTP pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SubmitIt { get; set; }
Public Property SubmitIt As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, the message will be submitted to the pickup folder; otherwise, it will be ignored. The default value is true.
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventArgs.Tag Property

SmtpSubmittingMessageToPickupFolderEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpSubmittingMessageToPickupFolderEventArgs Class
MailBee.SmtpMail Namespace


SmtpSubmittingMessageToPickupFolderEventHandler Delegate

SmtpSubmittingMessageToPickupFolderEventHandler Delegate
Represents the method that will handle SubmittingMessageToPickupFolder event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpSubmittingMessageToPickupFolderEventHandler(
    Object sender,
    SmtpSubmittingMessageToPickupFolderEventArgs e
)
Public Delegate Sub SmtpSubmittingMessageToPickupFolderEventHandler (
    sender As Object,
    e As SmtpSubmittingMessageToPickupFolderEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpSubmittingMessageToPickupFolderEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs Class

SmtpTransientErrorOccurredEventArgs Class
Contains the event data for TransientErrorOccurred event.
Inheritance Hierarchy
SystemObject
SystemEventArgs
MailBeeCommonEventArgs
MailBee.SmtpMailSmtpTransientErrorOccurredEventArgs

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SmtpTransientErrorOccurredEventArgs : CommonEventArgs
Public Class SmtpTransientErrorOccurredEventArgs
    Inherits CommonEventArgs

The SmtpTransientErrorOccurredEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Continue | Gets or sets if MailBee must continue sending attempts with another SMTP server at its disposal.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which could not be sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | Reason | Gets the exception describing the error which prevented the message from being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs Methods

SmtpTransientErrorOccurredEventArgs Methods

The SmtpTransientErrorOccurredEventArgs type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs Properties

SmtpTransientErrorOccurredEventArgs Properties

The SmtpTransientErrorOccurredEventArgs type exposes the following members.

Properties
 | Name | Description
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Continue | Gets or sets if MailBee must continue sending attempts with another SMTP server at its disposal.
Public property | IntendedRecipients | Gets the list of recipients the message is addressed to.
Public property | MailMessage | Gets the mail message which could not be sent.
Public property | MergeDataReader | Gets the reference to the data reader used for mail merge of this message.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the reference to the data table used for mail merge of this message.
Public property | Reason | Gets the exception describing the error which prevented the message from being sent.
Public property | State | Gets a reference to the object which was supplied by the developer in state parameter of asynchronous methods of the mailer components. (Inherited from CommonEventArgs.)
Public property | Tag | Gets the tag assigned by the developer to SendMailJob of processing the given message.
Top
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.ActualSenderEmail Property

SmtpTransientErrorOccurredEventArgsActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.
Remarks
Since Send method can be used to send messages from an e-mail address different from the address specified by From property, the developer can use ActualSenderEmail property to obtain the actual address the message was sent from.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.Continue Property

SmtpTransientErrorOccurredEventArgsContinue Property
Gets or sets if MailBee must continue sending attempts with another SMTP server at its disposal.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Continue { get; set; }
Public Property Continue As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, another server will be retried. If false, no more sending attempts with other servers will be made. The default value is true for sends via SMTP relay and false for direct sends via DNS MX lookup.
Remarks
You can analyze Reason in more detail to decide whether to keep trying or not.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.IntendedRecipients Property

SmtpTransientErrorOccurredEventArgsIntendedRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection IntendedRecipients { get; }
Public ReadOnly Property IntendedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.MailMessage Property

SmtpTransientErrorOccurredEventArgsMailMessage Property
Gets the mail message which could not be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which could not be sent.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.MergeDataReader Property

SmtpTransientErrorOccurredEventArgsMergeDataReader Property
Gets the reference to the data reader used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
Remarks
See MergeDataReader for explanations.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.MergeDataReaderColumnNames Property

SmtpTransientErrorOccurredEventArgsMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
Remarks
See MergeDataReaderColumnNames for explanations.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.MergeDataReaderRowValues Property

SmtpTransientErrorOccurredEventArgsMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
Remarks
See MergeDataReaderRowValues for explanations.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.MergeRowIndex Property

SmtpTransientErrorOccurredEventArgsMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageNotSentEventArgs class) returns DataRow used for mail merge of the message which could not be sent.

This property returns zero for mail merge over IDataReader jobs.

See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.MergeTable Property

SmtpTransientErrorOccurredEventArgsMergeTable Property
Gets the reference to the data table used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the data table used for mail merge of this message, or a null reference (Nothing in Visual Basic) if this mail message was not composed as a merge of DataTable data with mail template.
Remarks

For mail merge over DataTable operations, e.MergeTable[e.MergeRowIndex] (in C# syntax, assuming e is an instance of SmtpMessageNotSentEventArgs class) returns DataRow used for mail merge of the message which could not be sent.

For mail merge over IDataReader jobs, see MergeDataReader property.

See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.Reason Property

SmtpTransientErrorOccurredEventArgsReason Property
Gets the exception describing the error which prevented the message from being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailBeeSmtpNegativeResponseException Reason { get; }
Public ReadOnly Property Reason As MailBeeSmtpNegativeResponseException
    Get

Property Value

Type: MailBeeSmtpNegativeResponseException
A reference to the exception.
Remarks
The error reason of TransientErrorOccurred events if always negative response from an SMTP server (it's pretty specific type of errors). Other errors like connection failures, network issues, etc won't case this event occur. So you can be sure that you have SMTP error code, human-readable description returned by the SMTP server, etc.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventArgs.Tag Property

SmtpTransientErrorOccurredEventArgsTag Property
Gets the tag assigned by the developer to SendMailJob of processing the given message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned by the developer to SendMailJob object associated with the given message, or empty string if tag was not assigned.
See Also

Reference

SmtpTransientErrorOccurredEventArgs Class
MailBee.SmtpMail Namespace


SmtpTransientErrorOccurredEventHandler Delegate

SmtpTransientErrorOccurredEventHandler Delegate
Represents the method that will handle TransientErrorOccurred event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public delegate void SmtpTransientErrorOccurredEventHandler(
    Object sender,
    SmtpTransientErrorOccurredEventArgs e
)
Public Delegate Sub SmtpTransientErrorOccurredEventHandler (
    sender As Object,
    e As SmtpTransientErrorOccurredEventArgs
)

Parameters

sender
Type: SystemObject
e
Type: MailBee.SmtpMailSmtpTransientErrorOccurredEventArgs
See Also

Reference

MailBee.SmtpMail Namespace


IMailBeeNegativeSmtpResponseException Interface

IMailBeeNegativeSmtpResponseException Interface
When implemented by an exception class, indicates the SMTP server returned negative response. The response data is available in text (i.e. string) form, and SMTP response status code is also available.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeNegativeSmtpResponseException : IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException
Public Interface IMailBeeNegativeSmtpResponseException
    Inherits IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The IMailBeeNegativeSmtpResponseException type exposes the following members.

Properties
 | Name | Description
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later).
Public property | ResponseCode | Gets a 3-digit SMTP response status code.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


IMailBeeNegativeSmtpResponseException Properties

IMailBeeNegativeSmtpResponseException Properties

The IMailBeeNegativeSmtpResponseException type exposes the following members.

Properties
 | Name | Description
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later).
Public property | ResponseCode | Gets a 3-digit SMTP response status code.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from IMailBeeNegativeTextResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from IMailBeeNegativeTextResponseException.)
Top
See Also

Reference

IMailBeeNegativeSmtpResponseException Interface
MailBee.SmtpMail Namespace


IMailBeeNegativeSmtpResponseException.IsTransientError Property

IMailBeeNegativeSmtpResponseExceptionIsTransientError Property
Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
bool IsTransientError { get; }
ReadOnly Property IsTransientError As Boolean
    Get

Property Value

Type: Boolean
true if the failure is transient, and the client may try again at a later time; false if the client should not try to send the same command with the same parameters later.
Remarks

Transient errors correspond to 4xx status code, while permanent errors - to 5xx.

Typical case of a transient error is "Server is busy, try later". "Account does not exist" is a typical example of a permanent error. "Account is over quota" can be both permanent or transient error, depending on the mail server implementation.

See Also

Reference

IMailBeeNegativeSmtpResponseException Interface
MailBee.SmtpMail Namespace


IMailBeeNegativeSmtpResponseException.ResponseCode Property

IMailBeeNegativeSmtpResponseExceptionResponseCode Property
Gets a 3-digit SMTP response status code.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
int ResponseCode { get; }
ReadOnly Property ResponseCode As Integer
    Get

Property Value

Type: Int32
An integer value in the range 400 to 599 returned by the SMTP server to indicate failure of the requested operation.
See Also

Reference

IMailBeeNegativeSmtpResponseException Interface
MailBee.SmtpMail Namespace


IMailBeeSendException Interface

IMailBeeSendException Interface
When implemented by an exception class, indicates the exception is related to send mail operation. The list of the recipients, the sender e-mail address, and the mail message itself is available.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeSendException
Public Interface IMailBeeSendException

The IMailBeeSendException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | MailMessage | Gets the mail message which is being sent.
Top
See Also

Reference

MailBee.SmtpMail Namespace


IMailBeeSendException Properties

IMailBeeSendException Properties

The IMailBeeSendException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | MailMessage | Gets the mail message which is being sent.
Top
See Also

Reference

IMailBeeSendException Interface
MailBee.SmtpMail Namespace


IMailBeeSendException.ActualRecipients Property

IMailBeeSendExceptionActualRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
EmailAddressCollection ActualRecipients { get; }
ReadOnly Property ActualRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.
See Also

Reference

IMailBeeSendException Interface
MailBee.SmtpMail Namespace


IMailBeeSendException.ActualSenderEmail Property

IMailBeeSendExceptionActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
string ActualSenderEmail { get; }
ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.
See Also

Reference

IMailBeeSendException Interface
MailBee.SmtpMail Namespace


IMailBeeSendException.MailMessage Property

IMailBeeSendExceptionMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
MailMessage MailMessage { get; }
ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.
See Also

Reference

IMailBeeSendException Interface
MailBee.SmtpMail Namespace


IMailBeeSmtpSendException Interface

IMailBeeSmtpSendException Interface
When implemented by an exception class, indicates the exception is related to send mail to an SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeSmtpSendException : IMailBeeSendException
Public Interface IMailBeeSmtpSendException
    Inherits IMailBeeSendException

The IMailBeeSmtpSendException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from IMailBeeSendException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from IMailBeeSendException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from IMailBeeSendException.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


IMailBeeSmtpSendException Properties

IMailBeeSmtpSendException Properties

The IMailBeeSmtpSendException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from IMailBeeSendException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from IMailBeeSendException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from IMailBeeSendException.)
Top
See Also

Reference

IMailBeeSmtpSendException Interface
MailBee.SmtpMail Namespace


IMailBeeSmtpSendNeedsResetException Interface

IMailBeeSmtpSendNeedsResetException Interface
When implemented by an exception class, indicates RSET command was issued to the SMTP server to reset SMTP session and prepare it for sending another message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public interface IMailBeeSmtpSendNeedsResetException : IMailBeeSmtpSendException,
    IMailBeeSendException
Public Interface IMailBeeSmtpSendNeedsResetException
    Inherits IMailBeeSmtpSendException, IMailBeeSendException

The IMailBeeSmtpSendNeedsResetException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from IMailBeeSendException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from IMailBeeSendException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from IMailBeeSendException.)
Top
Remarks
If the SMTP server returned a negative response during send mail operation and the connection was not closed, MailBee sends RSET command to the SMTP server in order to prepare the session for subsequent commands.
See Also

Reference

MailBee.SmtpMail Namespace


IMailBeeSmtpSendNeedsResetException Properties

IMailBeeSmtpSendNeedsResetException Properties

The IMailBeeSmtpSendNeedsResetException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from IMailBeeSendException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from IMailBeeSendException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from IMailBeeSendException.)
Top
See Also

Reference

IMailBeeSmtpSendNeedsResetException Interface
MailBee.SmtpMail Namespace


MailBeeDnsRecordsDisabledException Class

MailBeeDnsRecordsDisabledException Class
The exception that is thrown when there was an attempt to request DNS records for a non-existent domain or a domain which is dead.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBee.SmtpMailMailBeeDnsRecordsDisabledException
MailBee.SmtpMailMailBeeMXRecordsDisabledException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeDnsRecordsDisabledException : MailBeeNetworkException
<SerializableAttribute>
Public Class MailBeeDnsRecordsDisabledException
    Inherits MailBeeNetworkException

The MailBeeDnsRecordsDisabledException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeDnsRecordsDisabledException | Initializes a new instance of the MailBeeDnsRecordsDisabledException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | Domain | Gets the name of the non-existent or dead host.
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeDnsRecordsDisabledException Constructor

MailBeeDnsRecordsDisabledException Constructor
Initializes a new instance of the MailBeeDnsRecordsDisabledException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeDnsRecordsDisabledException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeDnsRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeDnsRecordsDisabledException Methods

MailBeeDnsRecordsDisabledException Methods

The MailBeeDnsRecordsDisabledException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeDnsRecordsDisabledException Properties

MailBeeDnsRecordsDisabledException Properties

The MailBeeDnsRecordsDisabledException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | Domain | Gets the name of the non-existent or dead host.
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeDnsRecordsDisabledException.Domain Property

MailBeeDnsRecordsDisabledExceptionDomain Property
Gets the name of the non-existent or dead host.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Domain { get; }
Public ReadOnly Property Domain As String
    Get

Property Value

Type: String
The name of the host for which the DNS server reports "No such domain" or other problem (accordingly the DNS cache data).
See Also

Reference

MailBeeDnsRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeDnsRecordsDisabledException Events

MailBeeDnsRecordsDisabledException Events

The MailBeeDnsRecordsDisabledException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeDnsRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeMXRecordsDisabledException Class

MailBeeMXRecordsDisabledException Class
The exception that is thrown when there was an attempt to request DNS MX records for a non-existent domain or a domain whose SMTP MX servers are not responsive.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBee.SmtpMailMailBeeDnsRecordsDisabledException
MailBee.SmtpMailMailBeeMXRecordsDisabledException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeMXRecordsDisabledException : MailBeeDnsRecordsDisabledException
<SerializableAttribute>
Public Class MailBeeMXRecordsDisabledException
    Inherits MailBeeDnsRecordsDisabledException

The MailBeeMXRecordsDisabledException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeMXRecordsDisabledException | Initializes a new instance of the MailBeeMXRecordsDisabledException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | Domain | Gets the name of the non-existent or dead host. (Inherited from MailBeeDnsRecordsDisabledException.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception can be thrown only if DNS caching is enabled (Enabled is true). In this case, MailBee keeps track of all DNS MX lookup requests made and the following attempts to connect to SMTP MX servers designated by the DNS records retrieved during DNS MX lookup. If, for certain domain, all DNS MX records failed (all SMTP MX servers did not respond), MailBee remembers in its DNS cache that this domain is dead and marks the corresponding DNS records in the cache as disabled. All subsequent attempts to connect to this domain will immediately throw this exception without wasting time on waiting for a response from the dead server. The same optimization is performed when non-existent domain is encountered (i.e. the DNS server returned an error).

However, when Timeout interval (by default, 90 minutes since the moment of adding a record into the cache) elapses, MailBee removes such DNS MX records from the cache. It's assumed the failed server may be back during this time, or DNS records may change, etc, so it's worth trying to check the availability of the host in question again.

Note Note
This exception does not refer to the error which occurred just now. It rather occurs to due to past knowledge (acquired during previous send attempts and saved in the cache) that SMTP MX server (which was determined via DNS MX query) could not be contacted or the domain does not exist.
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeMXRecordsDisabledException Constructor

MailBeeMXRecordsDisabledException Constructor
Initializes a new instance of the MailBeeMXRecordsDisabledException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeMXRecordsDisabledException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeMXRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeMXRecordsDisabledException Methods

MailBeeMXRecordsDisabledException Methods

The MailBeeMXRecordsDisabledException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeMXRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeMXRecordsDisabledException Properties

MailBeeMXRecordsDisabledException Properties

The MailBeeMXRecordsDisabledException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | Domain | Gets the name of the non-existent or dead host. (Inherited from MailBeeDnsRecordsDisabledException.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeMXRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeMXRecordsDisabledException Events

MailBeeMXRecordsDisabledException Events

The MailBeeMXRecordsDisabledException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeMXRecordsDisabledException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException Class

MailBeeSmtp8bitDataNotSupportedException Class
The exception that is thrown when the message contains 8bit data while the SMTP server is capable of transmitting 7bit data only.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.SmtpMailMailBeeSmtp8bitDataNotSupportedException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtp8bitDataNotSupportedException : MailBeeEmailProtocolException,
    IMailBeeSmtpSendNeedsResetException, IMailBeeSmtpSendException, IMailBeeSendException
<SerializableAttribute>
Public Class MailBeeSmtp8bitDataNotSupportedException
    Inherits MailBeeEmailProtocolException
    Implements IMailBeeSmtpSendNeedsResetException, IMailBeeSmtpSendException, IMailBeeSendException

The MailBeeSmtp8bitDataNotSupportedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtp8bitDataNotSupportedException | Initializes a new instance of the MailBeeSmtp8bitDataNotSupportedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
See Conversion8BitTo7bit property documentation for more information.
See Also

Reference

MailBee.SmtpMail Namespace
MailBee.SmtpMailSmtp8bitDataConversion


MailBeeSmtp8bitDataNotSupportedException Constructor

MailBeeSmtp8bitDataNotSupportedException Constructor
Initializes a new instance of the MailBeeSmtp8bitDataNotSupportedException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtp8bitDataNotSupportedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException Methods

MailBeeSmtp8bitDataNotSupportedException Methods

The MailBeeSmtp8bitDataNotSupportedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException Properties

MailBeeSmtp8bitDataNotSupportedException Properties

The MailBeeSmtp8bitDataNotSupportedException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException.ActualRecipients Property

MailBeeSmtp8bitDataNotSupportedExceptionActualRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; }
Public ReadOnly Property ActualRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.

Implements

IMailBeeSendExceptionActualRecipients
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException.ActualSenderEmail Property

MailBeeSmtp8bitDataNotSupportedExceptionActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.

Implements

IMailBeeSendExceptionActualSenderEmail
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException.MailMessage Property

MailBeeSmtp8bitDataNotSupportedExceptionMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.

Implements

IMailBeeSendExceptionMailMessage
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtp8bitDataNotSupportedException Events

MailBeeSmtp8bitDataNotSupportedException Events

The MailBeeSmtp8bitDataNotSupportedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtp8bitDataNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException Class

MailBeeSmtpLoginBadCredentialsException Class
The exception that is thrown when the SMTP server reports the given user account name and/or password is incorrect.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginBadCredentialsException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpLoginBadCredentialsException : MailBeeSmtpLoginNegativeResponseException,
    IMailBeeLoginBadCredentialsException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpLoginBadCredentialsException
    Inherits MailBeeSmtpLoginNegativeResponseException
    Implements IMailBeeLoginBadCredentialsException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException

The MailBeeSmtpLoginBadCredentialsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpLoginBadCredentialsException | Initializes a new instance of the MailBeeSmtpLoginBadCredentialsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used during the authentication.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Password | Gets the account password which was used during the authentication.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException Constructor

MailBeeSmtpLoginBadCredentialsException Constructor
Initializes a new instance of the MailBeeSmtpLoginBadCredentialsException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpLoginBadCredentialsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpLoginBadCredentialsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException Methods

MailBeeSmtpLoginBadCredentialsException Methods

The MailBeeSmtpLoginBadCredentialsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpLoginBadCredentialsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException Properties

MailBeeSmtpLoginBadCredentialsException Properties

The MailBeeSmtpLoginBadCredentialsException type exposes the following members.

Properties
 | Name | Description
Public property | AccountName | Gets the account name which was used during the authentication.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Password | Gets the account password which was used during the authentication.
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpLoginBadCredentialsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException.AccountName Property

MailBeeSmtpLoginBadCredentialsExceptionAccountName Property
Gets the account name which was used during the authentication.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; }
Public ReadOnly Property AccountName As String
    Get

Property Value

Type: String
The account name which was used during the authentication.

Implements

IMailBeeLoginBadCredentialsExceptionAccountName
See Also

Reference

MailBeeSmtpLoginBadCredentialsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException.Password Property

MailBeeSmtpLoginBadCredentialsExceptionPassword Property
Gets the account password which was used during the authentication.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; }
Public ReadOnly Property Password As String
    Get

Property Value

Type: String
The account password which was used during the authentication.

Implements

IMailBeeLoginBadCredentialsExceptionPassword
See Also

Reference

MailBeeSmtpLoginBadCredentialsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadCredentialsException Events

MailBeeSmtpLoginBadCredentialsException Events

The MailBeeSmtpLoginBadCredentialsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpLoginBadCredentialsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadMethodException Class

MailBeeSmtpLoginBadMethodException Class
The exception that is thrown when the SMTP server reports the given ESMTP SASL authentication method is not supported and use of another authentication methods is not allowed by the application.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginBadMethodException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpLoginBadMethodException : MailBeeSmtpLoginNegativeResponseException,
    IMailBeeLoginBadMethodException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpLoginBadMethodException
    Inherits MailBeeSmtpLoginNegativeResponseException
    Implements IMailBeeLoginBadMethodException, IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException,
    IMailBeeNegativeResponseException

The MailBeeSmtpLoginBadMethodException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpLoginBadMethodException | Initializes a new instance of the MailBeeSmtpLoginBadMethodException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
By default, if a particular ESMTP SASL authentication method is not supported by the server, MailBee switches to the previous method listed in AuthMethods property value. If no more methods left, MailBeeLoginNoSupportedMethodsException is thrown. However, if UseSingleMethodOnly flag is set in AuthOptions property value, MailBee will not try other methods. Instead, if will immediately throw MailBeeSmtpLoginBadMethodException.
Note Note
This exception does not indicate that authentication using the given method failed. Instead, it indicates the method itself is not supported by the server. When the method is supported but the authentication using this method fails (invalid account name/password), MailBee does not try another methods (there would be no sense if it did), and throws MailBeeSmtpLoginBadCredentialsException.
This exception may also occur if FipsMode is enabled and the given authentication method is not FIPS-compliant.
See Also

Reference

MailBee.SmtpMail Namespace
MailBeeAuthenticationMethods
MailBeeAuthenticationOptions
MailBee.SmtpMailMailBeeSmtpLoginBadCredentialsException


MailBeeSmtpLoginBadMethodException Constructor

MailBeeSmtpLoginBadMethodException Constructor
Initializes a new instance of the MailBeeSmtpLoginBadMethodException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpLoginBadMethodException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpLoginBadMethodException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadMethodException Methods

MailBeeSmtpLoginBadMethodException Methods

The MailBeeSmtpLoginBadMethodException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpLoginBadMethodException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadMethodException Properties

MailBeeSmtpLoginBadMethodException Properties

The MailBeeSmtpLoginBadMethodException type exposes the following members.

Properties
 | Name | Description
Public property | BadMethod | Gets the authentication method which was rejected by the server.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpLoginBadMethodException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadMethodException.BadMethod Property

MailBeeSmtpLoginBadMethodExceptionBadMethod Property
Gets the authentication method which was rejected by the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods BadMethod { get; }
Public ReadOnly Property BadMethod As AuthenticationMethods
    Get

Property Value

Type: AuthenticationMethods
A AuthenticationMethods value having only a single bit set, which indicates the method which is requested by the application but not supported by the server.

Implements

IMailBeeLoginBadMethodExceptionBadMethod
Remarks
Although AuthenticationMethods allows bitwise combination of its member values, the result returned by this property always contains a single member value indicating the specific method which was rejected.
See Also

Reference

MailBeeSmtpLoginBadMethodException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginBadMethodException Events

MailBeeSmtpLoginBadMethodException Events

The MailBeeSmtpLoginBadMethodException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpLoginBadMethodException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginNegativeResponseException Class

MailBeeSmtpLoginNegativeResponseException Class
An abstract parent for all exceptions which indicate the SMTP server replied with a negative response during authentication of the user.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginBadCredentialsException
MailBee.SmtpMailMailBeeSmtpLoginBadMethodException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeSmtpLoginNegativeResponseException : MailBeeSmtpNegativeResponseException,
    IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
Public MustInherit Class MailBeeSmtpLoginNegativeResponseException
    Inherits MailBeeSmtpNegativeResponseException
    Implements IMailBeeLoginNegativeResponseException, IMailBeeLoginException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The MailBeeSmtpLoginNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpLoginNegativeResponseException | Initializes a new instance of the MailBeeSmtpLoginNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpLoginNegativeResponseException Constructor

MailBeeSmtpLoginNegativeResponseException Constructor
Initializes a new instance of the MailBeeSmtpLoginNegativeResponseException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpLoginNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpLoginNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginNegativeResponseException Methods

MailBeeSmtpLoginNegativeResponseException Methods

The MailBeeSmtpLoginNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpLoginNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginNegativeResponseException Properties

MailBeeSmtpLoginNegativeResponseException Properties

The MailBeeSmtpLoginNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpLoginNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpLoginNegativeResponseException Events

MailBeeSmtpLoginNegativeResponseException Events

The MailBeeSmtpLoginNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpLoginNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException Class

MailBeeSmtpMessageNotAllowedException Class
An abstract parent for all exceptions that are thrown when the component determines the message could not be submitted to the SMTP server even before starting the actual submission.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.SmtpMailMailBeeSmtpMessageNotAllowedException
MailBee.SmtpMailMailBeeSmtpMessageSizeOutOfRangeException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeSmtpMessageNotAllowedException : MailBeeEmailProtocolException,
    IMailBeeSmtpSendException, IMailBeeSendException
Public MustInherit Class MailBeeSmtpMessageNotAllowedException
    Inherits MailBeeEmailProtocolException
    Implements IMailBeeSmtpSendException, IMailBeeSendException

The MailBeeSmtpMessageNotAllowedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpMessageNotAllowedException | Initializes a new instance of the MailBeeSmtpMessageNotAllowedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
For instance, if the message source data size exceeds the maximum size of the message allowed by the SMTP server for submission, it makes no sense to start the actual submission. The server would reject the message anyway.
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException Constructor

MailBeeSmtpMessageNotAllowedException Constructor
Initializes a new instance of the MailBeeSmtpMessageNotAllowedException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpMessageNotAllowedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException Methods

MailBeeSmtpMessageNotAllowedException Methods

The MailBeeSmtpMessageNotAllowedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException Properties

MailBeeSmtpMessageNotAllowedException Properties

The MailBeeSmtpMessageNotAllowedException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException.ActualRecipients Property

MailBeeSmtpMessageNotAllowedExceptionActualRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; }
Public ReadOnly Property ActualRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.

Implements

IMailBeeSendExceptionActualRecipients
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException.ActualSenderEmail Property

MailBeeSmtpMessageNotAllowedExceptionActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.

Implements

IMailBeeSendExceptionActualSenderEmail
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException.MailMessage Property

MailBeeSmtpMessageNotAllowedExceptionMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.

Implements

IMailBeeSendExceptionMailMessage
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageNotAllowedException Events

MailBeeSmtpMessageNotAllowedException Events

The MailBeeSmtpMessageNotAllowedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpMessageNotAllowedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageSizeOutOfRangeException Class

MailBeeSmtpMessageSizeOutOfRangeException Class
The exception that is thrown when the component determines the size of the message data exceeds the maximum size allowed by the SMTP server.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.SmtpMailMailBeeSmtpMessageNotAllowedException
MailBee.SmtpMailMailBeeSmtpMessageSizeOutOfRangeException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpMessageSizeOutOfRangeException : MailBeeSmtpMessageNotAllowedException
<SerializableAttribute>
Public Class MailBeeSmtpMessageSizeOutOfRangeException
    Inherits MailBeeSmtpMessageNotAllowedException

The MailBeeSmtpMessageSizeOutOfRangeException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpMessageSizeOutOfRangeException | Initializes a new instance of the MailBeeSmtpMessageSizeOutOfRangeException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpMessageNotAllowedException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpMessageNotAllowedException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpMessageNotAllowedException.)
Public property | MaxAllowedMessageSize | Gets the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

MailBee uses ESMTP SIZE extension to determine the maximum allowed message size on the server. If ESMTP SIZE extension is not supported or disabled, MailBee will not check the message size prior to sending, and this exception will not be thrown.

The message size can be determined from Size property value of MailMessage object.

See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpMessageSizeOutOfRangeException Constructor

MailBeeSmtpMessageSizeOutOfRangeException Constructor
Initializes a new instance of the MailBeeSmtpMessageSizeOutOfRangeException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpMessageSizeOutOfRangeException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpMessageSizeOutOfRangeException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageSizeOutOfRangeException Methods

MailBeeSmtpMessageSizeOutOfRangeException Methods

The MailBeeSmtpMessageSizeOutOfRangeException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpMessageSizeOutOfRangeException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageSizeOutOfRangeException Properties

MailBeeSmtpMessageSizeOutOfRangeException Properties

The MailBeeSmtpMessageSizeOutOfRangeException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpMessageNotAllowedException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpMessageNotAllowedException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpMessageNotAllowedException.)
Public property | MaxAllowedMessageSize | Gets the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpMessageSizeOutOfRangeException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageSizeOutOfRangeException.MaxAllowedMessageSize Property

MailBeeSmtpMessageSizeOutOfRangeExceptionMaxAllowedMessageSize Property
Gets the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxAllowedMessageSize { get; }
Public ReadOnly Property MaxAllowedMessageSize As Integer
    Get

Property Value

Type: Int32
An integer value specifying the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.
See Also

Reference

MailBeeSmtpMessageSizeOutOfRangeException Class
MailBee.SmtpMail Namespace


MailBeeSmtpMessageSizeOutOfRangeException Events

MailBeeSmtpMessageSizeOutOfRangeException Events

The MailBeeSmtpMessageSizeOutOfRangeException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpMessageSizeOutOfRangeException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException Class

MailBeeSmtpNegativeResponseException Class
The exception that is thrown when the SMTP server responds with a negative reply (4xx or 5xx, such as 501).
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpLoginNegativeResponseException
MailBee.SmtpMailMailBeeSmtpOptionalCommandNotSupportedException
MailBee.SmtpMailMailBeeSmtpSendNegativeResponseException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpNegativeResponseException : MailBeeEmailProtocolNegativeResponseException,
    IMailBeeNegativeSmtpResponseException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpNegativeResponseException
    Inherits MailBeeEmailProtocolNegativeResponseException
    Implements IMailBeeNegativeSmtpResponseException, IMailBeeNegativeTextResponseException, IMailBeeNegativeResponseException

The MailBeeSmtpNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpNegativeResponseException | Initializes a new instance of the MailBeeSmtpNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later).
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException Constructor

MailBeeSmtpNegativeResponseException Constructor
Initializes a new instance of the MailBeeSmtpNegativeResponseException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException Methods

MailBeeSmtpNegativeResponseException Methods

The MailBeeSmtpNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException Properties

MailBeeSmtpNegativeResponseException Properties

The MailBeeSmtpNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later).
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code.
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException.IsTransientError Property

MailBeeSmtpNegativeResponseExceptionIsTransientError Property
Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsTransientError { get; }
Public ReadOnly Property IsTransientError As Boolean
    Get

Property Value

Type: Boolean
true if the failure is transient, and the client may try again at a later time; false if the client should not try to send the same command with the same parameters later.

Implements

IMailBeeNegativeSmtpResponseExceptionIsTransientError
Remarks

Transient errors correspond to 4xx status code, while permanent errors - to 5xx.

Typical case of a transient error is "Server is busy, try later". "Account does not exist" is a typical example of a permanent error. "Account is over quota" can be both permanent or transient error, depending on the mail server implementation.

See Also

Reference

MailBeeSmtpNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException.ResponseCode Property

MailBeeSmtpNegativeResponseExceptionResponseCode Property
Gets a 3-digit SMTP response status code.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int ResponseCode { get; }
Public ReadOnly Property ResponseCode As Integer
    Get

Property Value

Type: Int32
An integer value in the range 400 to 599 returned by the SMTP server to indicate failure of the requested operation.

Implements

IMailBeeNegativeSmtpResponseExceptionResponseCode
See Also

Reference

MailBeeSmtpNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNegativeResponseException Events

MailBeeSmtpNegativeResponseException Events

The MailBeeSmtpNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException Class

MailBeeSmtpNoAcceptedRecipientsException Class
The exception that is thrown when the SMTP server refuses all the recipients submitted during the send mail operation.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBee.SmtpMailMailBeeSmtpNoAcceptedRecipientsException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpNoAcceptedRecipientsException : MailBeeEmailProtocolException,
    IMailBeeSmtpSendNeedsResetException, IMailBeeSmtpSendException, IMailBeeSendException
<SerializableAttribute>
Public Class MailBeeSmtpNoAcceptedRecipientsException
    Inherits MailBeeEmailProtocolException
    Implements IMailBeeSmtpSendNeedsResetException, IMailBeeSmtpSendException, IMailBeeSendException

The MailBeeSmtpNoAcceptedRecipientsException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpNoAcceptedRecipientsException | Initializes a new instance of the MailBeeSmtpNoAcceptedRecipientsException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
This exception can be thrown only when refused recipients are allowed. When refused recipients are not allowed, the component does not wait until all recipients get refused, and throws MailBeeSmtpRefusedRecipientException if at least one recipient fails.
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException Constructor

MailBeeSmtpNoAcceptedRecipientsException Constructor
Initializes a new instance of the MailBeeSmtpNoAcceptedRecipientsException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpNoAcceptedRecipientsException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException Methods

MailBeeSmtpNoAcceptedRecipientsException Methods

The MailBeeSmtpNoAcceptedRecipientsException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException Properties

MailBeeSmtpNoAcceptedRecipientsException Properties

The MailBeeSmtpNoAcceptedRecipientsException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException.ActualRecipients Property

MailBeeSmtpNoAcceptedRecipientsExceptionActualRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; }
Public ReadOnly Property ActualRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.

Implements

IMailBeeSendExceptionActualRecipients
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException.ActualSenderEmail Property

MailBeeSmtpNoAcceptedRecipientsExceptionActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.

Implements

IMailBeeSendExceptionActualSenderEmail
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException.MailMessage Property

MailBeeSmtpNoAcceptedRecipientsExceptionMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.

Implements

IMailBeeSendExceptionMailMessage
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpNoAcceptedRecipientsException Events

MailBeeSmtpNoAcceptedRecipientsException Events

The MailBeeSmtpNoAcceptedRecipientsException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpNoAcceptedRecipientsException Class
MailBee.SmtpMail Namespace


MailBeeSmtpOptionalCommandNotSupportedException Class

MailBeeSmtpOptionalCommandNotSupportedException Class
The exception that is thrown when the SMTP server responds with a negative reply to an optional SMTP command.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpOptionalCommandNotSupportedException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpOptionalCommandNotSupportedException : MailBeeSmtpNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpOptionalCommandNotSupportedException
    Inherits MailBeeSmtpNegativeResponseException

The MailBeeSmtpOptionalCommandNotSupportedException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpOptionalCommandNotSupportedException | Initializes a new instance of the MailBeeSmtpOptionalCommandNotSupportedException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks

This exception is never thrown in the application code. Instead, MailBee catches it, and raises ErrorOccurred event passing the exception instance as the Reason parameter value.

This exception indicates the SMTP server does not support an optional SMTP command which was sent to the server by MailBee. For instance, MailBee may try to send EHLO command in order to to initiate SMTP session and learn the server capabilities. The SMTP server, however, may not support it. In this case, MailBee continues normal execution and tries regular HELO command to initiate SMTP session (although ESMTP extensions, which could be supported if the failed command succeeded, will now be disabled). However, ErrorOccurred event is still raised to let the application code know that some features will be disabled.

See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpOptionalCommandNotSupportedException Constructor

MailBeeSmtpOptionalCommandNotSupportedException Constructor
Initializes a new instance of the MailBeeSmtpOptionalCommandNotSupportedException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpOptionalCommandNotSupportedException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpOptionalCommandNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpOptionalCommandNotSupportedException Methods

MailBeeSmtpOptionalCommandNotSupportedException Methods

The MailBeeSmtpOptionalCommandNotSupportedException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpOptionalCommandNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpOptionalCommandNotSupportedException Properties

MailBeeSmtpOptionalCommandNotSupportedException Properties

The MailBeeSmtpOptionalCommandNotSupportedException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpOptionalCommandNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpOptionalCommandNotSupportedException Events

MailBeeSmtpOptionalCommandNotSupportedException Events

The MailBeeSmtpOptionalCommandNotSupportedException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpOptionalCommandNotSupportedException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedDataException Class

MailBeeSmtpRefusedDataException Class
The exception that is thrown when the SMTP server refuses the message data submitted by the client or even refuses to start receiving the message data from the client.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpSendNegativeResponseException
MailBee.SmtpMailMailBeeSmtpRefusedDataException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpRefusedDataException : MailBeeSmtpSendNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpRefusedDataException
    Inherits MailBeeSmtpSendNegativeResponseException

The MailBeeSmtpRefusedDataException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpRefusedDataException | Initializes a new instance of the MailBeeSmtpRefusedDataException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
Remarks
The developer can use ResponseString and ErrorCode property values to obtain more detailed information about the error.
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpRefusedDataException Constructor

MailBeeSmtpRefusedDataException Constructor
Initializes a new instance of the MailBeeSmtpRefusedDataException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpRefusedDataException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpRefusedDataException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedDataException Methods

MailBeeSmtpRefusedDataException Methods

The MailBeeSmtpRefusedDataException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpRefusedDataException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedDataException Properties

MailBeeSmtpRefusedDataException Properties

The MailBeeSmtpRefusedDataException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpRefusedDataException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedDataException Events

MailBeeSmtpRefusedDataException Events

The MailBeeSmtpRefusedDataException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpRefusedDataException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException Class

MailBeeSmtpRefusedRecipientException Class
The exception that is thrown when the SMTP server refuses to deliver the mail message to the specified recipient.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpSendNegativeResponseException
MailBee.SmtpMailMailBeeSmtpRefusedRecipientException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpRefusedRecipientException : MailBeeSmtpSendNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpRefusedRecipientException
    Inherits MailBeeSmtpSendNegativeResponseException

The MailBeeSmtpRefusedRecipientException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpRefusedRecipientException | Initializes a new instance of the MailBeeSmtpRefusedRecipientException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RefusedRecipientEmail | Gets the e-mail address of the refused recipient.
Public property | RefusedRecipientIndex | Gets the index of the refused recipient in ActualRecipients collection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException Constructor

MailBeeSmtpRefusedRecipientException Constructor
Initializes a new instance of the MailBeeSmtpRefusedRecipientException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpRefusedRecipientException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpRefusedRecipientException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException Methods

MailBeeSmtpRefusedRecipientException Methods

The MailBeeSmtpRefusedRecipientException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpRefusedRecipientException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException Properties

MailBeeSmtpRefusedRecipientException Properties

The MailBeeSmtpRefusedRecipientException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RefusedRecipientEmail | Gets the e-mail address of the refused recipient.
Public property | RefusedRecipientIndex | Gets the index of the refused recipient in ActualRecipients collection.
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpRefusedRecipientException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException.RefusedRecipientEmail Property

MailBeeSmtpRefusedRecipientExceptionRefusedRecipientEmail Property
Gets the e-mail address of the refused recipient.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string RefusedRecipientEmail { get; }
Public ReadOnly Property RefusedRecipientEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the recipient's address.
See Also

Reference

MailBeeSmtpRefusedRecipientException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException.RefusedRecipientIndex Property

MailBeeSmtpRefusedRecipientExceptionRefusedRecipientIndex Property
Gets the index of the refused recipient in ActualRecipients collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int RefusedRecipientIndex { get; }
Public ReadOnly Property RefusedRecipientIndex As Integer
    Get

Property Value

Type: Int32
An integer value containing zero-based index of the refused recipient in ActualRecipients collection.
See Also

Reference

MailBeeSmtpRefusedRecipientException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedRecipientException Events

MailBeeSmtpRefusedRecipientException Events

The MailBeeSmtpRefusedRecipientException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpRefusedRecipientException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedSenderException Class

MailBeeSmtpRefusedSenderException Class
The exception that is thrown when the SMTP server refuses to deliver the mail message from the specified sender.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpSendNegativeResponseException
MailBee.SmtpMailMailBeeSmtpRefusedSenderException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeSmtpRefusedSenderException : MailBeeSmtpSendNegativeResponseException
<SerializableAttribute>
Public Class MailBeeSmtpRefusedSenderException
    Inherits MailBeeSmtpSendNegativeResponseException

The MailBeeSmtpRefusedSenderException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpRefusedSenderException | Initializes a new instance of the MailBeeSmtpRefusedSenderException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpRefusedSenderException Constructor

MailBeeSmtpRefusedSenderException Constructor
Initializes a new instance of the MailBeeSmtpRefusedSenderException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpRefusedSenderException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpRefusedSenderException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedSenderException Methods

MailBeeSmtpRefusedSenderException Methods

The MailBeeSmtpRefusedSenderException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpRefusedSenderException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedSenderException Properties

MailBeeSmtpRefusedSenderException Properties

The MailBeeSmtpRefusedSenderException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent. (Inherited from MailBeeSmtpSendNegativeResponseException.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpRefusedSenderException Class
MailBee.SmtpMail Namespace


MailBeeSmtpRefusedSenderException Events

MailBeeSmtpRefusedSenderException Events

The MailBeeSmtpRefusedSenderException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpRefusedSenderException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException Class

MailBeeSmtpSendNegativeResponseException Class
The exception that is thrown when the SMTP server responds with a negative reply (4xx or 5xx, such as 501) during send mail operation.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeNetworkException
MailBeeMailBeeRemoteHostException
MailBeeMailBeeProtocolException
MailBeeMailBeeEmailProtocolException
MailBeeMailBeeEmailProtocolNegativeResponseException
MailBee.SmtpMailMailBeeSmtpNegativeResponseException
MailBee.SmtpMailMailBeeSmtpSendNegativeResponseException
MailBee.SmtpMailMailBeeSmtpRefusedDataException
MailBee.SmtpMailMailBeeSmtpRefusedRecipientException
MailBee.SmtpMailMailBeeSmtpRefusedSenderException

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeSmtpSendNegativeResponseException : MailBeeSmtpNegativeResponseException,
    IMailBeeSmtpSendNeedsResetException, IMailBeeSmtpSendException, IMailBeeSendException
Public MustInherit Class MailBeeSmtpSendNegativeResponseException
    Inherits MailBeeSmtpNegativeResponseException
    Implements IMailBeeSmtpSendNeedsResetException, IMailBeeSmtpSendException, IMailBeeSendException

The MailBeeSmtpSendNegativeResponseException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeSmtpSendNegativeResponseException | Initializes a new instance of the MailBeeSmtpSendNegativeResponseException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException Constructor

MailBeeSmtpSendNegativeResponseException Constructor
Initializes a new instance of the MailBeeSmtpSendNegativeResponseException class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeSmtpSendNegativeResponseException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException Methods

MailBeeSmtpSendNegativeResponseException Methods

The MailBeeSmtpSendNegativeResponseException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException Properties

MailBeeSmtpSendNegativeResponseException Properties

The MailBeeSmtpSendNegativeResponseException type exposes the following members.

Properties
 | Name | Description
Public property | ActualRecipients | Gets the list of recipients the message is addressed to.
Public property | ActualSenderEmail | Gets the e-mail address of the sender of the mail message.
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | IsTransientError | Gets the status of whether the failure is permanent (the client should not retry later) or transient (the client may retry later). (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | MailMessage | Gets the mail message which is being sent.
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Protocol | Gets application-level protocol of the current connection. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteEndPoint | Gets a reference to the end point of the server host. (Inherited from MailBeeRemoteHostException.)
Public property | RemoteHostName | Gets the host name of the server. (Inherited from MailBeeRemoteHostException.)
Public property | ResponseCode | Gets a 3-digit SMTP response status code. (Inherited from MailBeeSmtpNegativeResponseException.)
Public property | ResponseEncoding | Gets the encoding which was used to convert response bytes received from the server into a string. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | ResponseString | Gets the string which contains the negative response data. (Inherited from MailBeeEmailProtocolNegativeResponseException.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Public property | WasConnected | Gets if the connection with the server had already been established to the moment when the exception occurred. (Inherited from MailBeeRemoteHostException.)
Top
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException.ActualRecipients Property

MailBeeSmtpSendNegativeResponseExceptionActualRecipients Property
Gets the list of recipients the message is addressed to.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ActualRecipients { get; }
Public ReadOnly Property ActualRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the EmailAddressCollection object which contains the list of all recipients to the message.

Implements

IMailBeeSendExceptionActualRecipients
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException.ActualSenderEmail Property

MailBeeSmtpSendNegativeResponseExceptionActualSenderEmail Property
Gets the e-mail address of the sender of the mail message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string ActualSenderEmail { get; }
Public ReadOnly Property ActualSenderEmail As String
    Get

Property Value

Type: String
The pure e-mail address (user@domain.com, i.e. without display name or remarks) which was submitted to the SMTP server as the address of the message sender.

Implements

IMailBeeSendExceptionActualSenderEmail
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException.MailMessage Property

MailBeeSmtpSendNegativeResponseExceptionMailMessage Property
Gets the mail message which is being sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MailMessage { get; }
Public ReadOnly Property MailMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the MailMessage object representing the message which is being sent.

Implements

IMailBeeSendExceptionMailMessage
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


MailBeeSmtpSendNegativeResponseException Events

MailBeeSmtpSendNegativeResponseException Events

The MailBeeSmtpSendNegativeResponseException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeSmtpSendNegativeResponseException Class
MailBee.SmtpMail Namespace


DeliveryNotificationOptions Class

DeliveryNotificationOptions Class
Provides properties and methods which control how and when ESMTP Delivery Status Notifications (DSN) are sent.
Inheritance Hierarchy
SystemObject
MailBee.SmtpMailDeliveryNotificationOptions

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DeliveryNotificationOptions
Public Class DeliveryNotificationOptions

The DeliveryNotificationOptions type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Reset | Resets all Delivery Status Notification settings back to defaults.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | NotifyCondition | Gets or sets the events that trigger ESMTP server to send delivery status notification back to the sender of the message.
Public property | ReturnPortion | Gets or sets how much of the original message is returned with the delivery status notification when the message delivery fails.
Public property | TrackingID | Gets or sets the unique string (called message transmission envelope) which will be returned with delivery status notification messages.
Top
Remarks

To access DeliveryNotificationOptions object, use Smtp.DeliveryNotification property.

Note Note
If the SMTP server does not support DSN, the values of all the properties of this class are ignored.
Examples
This sample checks whether the server supports DSN's, submits a message to the server, and tells the server to send DSN on any outcome (sent successfully, failed, or delayed). The DSN message will include the header of the original message.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Set Delivery Status Notification settings:

// Notify always.
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always;

// Notification message will include the message header of the original messsage.
mailer.DeliveryNotification.ReturnPortion = DsnReturnPortion.Header;

// Specify some unique string which will be added to notification messages.
// It can then be used to match notification message with the original message.
mailer.DeliveryNotification.TrackingID = "UNQIUE_STRING_q8sdf74d";

// Set the message fields.
mailer.From.AsString = "John Doe <jdoe@domain1.com>";
mailer.To.AsString = "Bill Smith <b.smith@domain2.com>";
mailer.Subject = "Test message";

// Specify SMTP server to use. If your server does not require authentication,
// just remove last 2 parameters.
mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret");

// Connect to the server and say hello. We need this in order to learn the server
// capabilities (such as DSN support).
// Alternatively, we could not call Hello() and move DSN status check after Send(),
// since Send() method would automatically call Hello() if needed.
mailer.Connect();
mailer.Hello();

// Learn if delivery status notifications are supported by the server.
if (mailer.GetExtension("DSN") != null)
{
    Console.WriteLine("The message will be submitted with DSN support");
}
else
{
    Console.WriteLine("The message will be submitted without DSN support");
}

// Send the message.
mailer.Send();

Console.WriteLine("The message was successfully submitted to the server.");

// Close the connection.
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Set Delivery Status Notification settings:

' Notify always.
mailer.DeliveryNotification.NotifyCondition = DsnNotifyCondition.Always

' Notification message will include the message header of the original messsage.
mailer.DeliveryNotification.ReturnPortion = DsnReturnPortion.Header

' Specify some unique string which will be added to notification messages.
' It can then be used to match notification message with the original message.
mailer.DeliveryNotification.TrackingID = "UNQIUE_STRING_q8sdf74d"

' Set the message fields.
mailer.From.AsString = "John Doe <jdoe@domain1.com>;"
mailer.To.AsString = "Bill Smith <b.smith@domain2.com>"
mailer.Subject = "Test message"

' Specify SMTP server to use. If your server does not require authentication,
' just remove last 2 parameters.
mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret")

' Connect to the server and say hello. We need this in order to learn the server
' capabilities (such as DSN support).
' Alternatively, we could not call Hello() and move DSN status check after Send(),
' since Send() method would automatically call Hello() if needed.
mailer.Connect()
mailer.Hello()

' Learn if delivery status notifications are supported by the server.
If Not mailer.GetExtension("DSN") Is Nothing Then
    Console.WriteLine("The message will be submitted with DSN support")
Else
    Console.WriteLine("The message will be submitted without DSN support")
End If

' Send the message.
mailer.Send()

Console.WriteLine("The message was successfully submitted to the server.")

' Close the connection.
mailer.Disconnect()
See Also

Reference

MailBee.SmtpMail Namespace


DeliveryNotificationOptions Methods

DeliveryNotificationOptions Methods

The DeliveryNotificationOptions type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Reset | Resets all Delivery Status Notification settings back to defaults.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DeliveryNotificationOptions Class
MailBee.SmtpMail Namespace


DeliveryNotificationOptions.Reset Method

DeliveryNotificationOptionsReset Method
Resets all Delivery Status Notification settings back to defaults.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Reset()
Public Sub Reset
See Also

Reference

DeliveryNotificationOptions Class
MailBee.SmtpMail Namespace


DeliveryNotificationOptions Properties

DeliveryNotificationOptions Properties

The DeliveryNotificationOptions type exposes the following members.

Properties
 | Name | Description
Public property | NotifyCondition | Gets or sets the events that trigger ESMTP server to send delivery status notification back to the sender of the message.
Public property | ReturnPortion | Gets or sets how much of the original message is returned with the delivery status notification when the message delivery fails.
Public property | TrackingID | Gets or sets the unique string (called message transmission envelope) which will be returned with delivery status notification messages.
Top
See Also

Reference

DeliveryNotificationOptions Class
MailBee.SmtpMail Namespace


DeliveryNotificationOptions.NotifyCondition Property

DeliveryNotificationOptionsNotifyCondition Property
Gets or sets the events that trigger ESMTP server to send delivery status notification back to the sender of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnNotifyCondition NotifyCondition { get; set; }
Public Property NotifyCondition As DsnNotifyCondition
    Get
    Set

Property Value

Type: DsnNotifyCondition
A set of flags specifying the events that trigger the server to send delivery status notification (the server must support DSN extension). The default value is Default.
See Also

Reference

DeliveryNotificationOptions Class
MailBee.SmtpMail Namespace


DeliveryNotificationOptions.ReturnPortion Property

DeliveryNotificationOptionsReturnPortion Property
Gets or sets how much of the original message is returned with the delivery status notification when the message delivery fails.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DsnReturnPortion ReturnPortion { get; set; }
Public Property ReturnPortion As DsnReturnPortion
    Get
    Set

Property Value

Type: DsnReturnPortion
A DsnReturnPortion value which specifies how much of the original message is returned with the delivery status notification when the message delivery fails (the server must support DSN extension). The default value is Default.
See Also

Reference

DeliveryNotificationOptions Class
MailBee.SmtpMail Namespace


DeliveryNotificationOptions.TrackingID Property

DeliveryNotificationOptionsTrackingID Property
Gets or sets the unique string (called message transmission envelope) which will be returned with delivery status notification messages.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TrackingID { get; set; }
Public Property TrackingID As String
    Get
    Set

Property Value

Type: String
The string which will be returned with delivery status notification messages. The default value is Empty.
Remarks
The developer can set this property in order to be able to match notification messages with original messages. This is useful if many messages being sent and many delivery notifications being returned, and often used in bounced mail processing. For instance, this value will be available through OriginalEnvelopeID property of the delivery status notification message which will be sent by the destination mail server upon delivery (or not delivery) of your e-mail message.
Note Note
In .NET Core and UWP apps, BounceMail component is not supported yet.
See Also

Reference

DeliveryNotificationOptions Class
MailBee.SmtpMail Namespace


DirectSendServerConfig Class

DirectSendServerConfig Class
Provides properties which specify SMTP server settings to be used by Smtp component for SMTP servers found through MX lookup.
Inheritance Hierarchy
SystemObject
MailBee.SmtpMailDirectSendServerConfig

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class DirectSendServerConfig
Public Class DirectSendServerConfig

The DirectSendServerConfig type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | EnableStartTls | Gets or sets whether direct send will occur via SSL/TLS if this is supported by the MX server.
Public property | HelloDomain | Gets or sets the domain string to be used in the EHLO or HELO command when connecting to the server.
Public property | LocalEndPoint | Gets or sets the local end point which will be used when connecting to SMTP MX servers.
Public property | Pipelining | Gets or sets whether to use commands pipelining if it's supported by the server.
Public property | SmtpOptions | Gets or sets ESMTP options specifying which SMTP extensions must not be used when communicating with the server.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.
Top
Remarks

When Smtp component sends mail in direct send mode (such as when SmtpServers collection is empty while DnsServers collection is not), it finds SMTP server for each recipient domain through MX lookup against DNS server. The only information returned by the DNS server is SMTP server name and usage preference (if multiple SMTP servers can accept mail for the given domain). The properties of this class allow the developer to specify some additional settings which affect how MailBee will communicate with the SMTP server which was found through MX lookup.

To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.

Note Note
SMTP servers manually added by the developer (i.e. SmtpServers collection) are NOT affected by any members of DirectSendServerConfig class.
See Also

Reference

MailBee.SmtpMail Namespace


DirectSendServerConfig Methods

DirectSendServerConfig Methods

The DirectSendServerConfig type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DirectSendServerConfig Properties

DirectSendServerConfig Properties

The DirectSendServerConfig type exposes the following members.

Properties
 | Name | Description
Public property | EnableStartTls | Gets or sets whether direct send will occur via SSL/TLS if this is supported by the MX server.
Public property | HelloDomain | Gets or sets the domain string to be used in the EHLO or HELO command when connecting to the server.
Public property | LocalEndPoint | Gets or sets the local end point which will be used when connecting to SMTP MX servers.
Public property | Pipelining | Gets or sets whether to use commands pipelining if it's supported by the server.
Public property | SmtpOptions | Gets or sets ESMTP options specifying which SMTP extensions must not be used when communicating with the server.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.
Top
See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DirectSendServerConfig.EnableStartTls Property

DirectSendServerConfigEnableStartTls Property
Gets or sets whether direct send will occur via SSL/TLS if this is supported by the MX server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EnableStartTls { get; set; }
Public Property EnableStartTls As Boolean
    Get
    Set

Property Value

Type: Boolean
If true, MailBee will use UseStartTlsIfSupported mode when connecting to SMTP MX servers; otherwise, Manual (no SSL/TLS). The default value is false.
Remarks

Sending SMTP traffic via SSL/TLS layer is more secure but it requires more resources and degrades sending performance.

This property has no effect for sending via SMTP relay server (i.e. when you specified the SMTP server explicitly with SmtpServers property).

To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.

See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DirectSendServerConfig.HelloDomain Property

DirectSendServerConfigHelloDomain Property
Gets or sets the domain string to be used in the EHLO or HELO command when connecting to the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HelloDomain { get; set; }
Public Property HelloDomain As String
    Get
    Set

Property Value

Type: String
The domain to be used in the HELO or EHLO command when connecting to the server, or an empty string which tells MailBee to use the local IP address or the host name of the local computer as the domain string. The default value is an empty string.
Remarks

Usually, this property does not need to be changed. If it's an empty string (default value), MailBee will automatically send correct HELO or EHLO command based on the local host's IPv4 address or the local host name if the IPv4 address is not available.

To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.

See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DirectSendServerConfig.LocalEndPoint Property

DirectSendServerConfigLocalEndPoint Property
Gets or sets the local end point which will be used when connecting to SMTP MX servers.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EndPoint LocalEndPoint { get; set; }
Public Property LocalEndPoint As EndPoint
    Get
    Set

Property Value

Type: EndPoint
A reference to the local end point to be used when connecting to SMTP MX servers, or a null reference (Nothing in Visual Basic) if the local end point should be assigned automatically. The default value is a null reference.
Remarks

If the computer running MailBee has multiple IP addresses assigned (for instance, it has several network adapters installed), you can set this property to the IP address and port which should be used for outbound connections. See Bind(EndPoint) and LocalEndPoint topics for more information.

If you're sending to an SMTP relay server rather than using "direct send" mode, the property to be set in this case is SmtpServer.LocalEndPoint.

To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.

See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DirectSendServerConfig.Pipelining Property

DirectSendServerConfigPipelining Property
Gets or sets whether to use commands pipelining if it's supported by the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Pipelining { get; set; }
Public Property Pipelining As Boolean
    Get
    Set

Property Value

Type: Boolean
A Boolean value which specifies whether to join SMTP commands in batches if the server supports PIPELINING extension. The default value is Pipelining.
Remarks

ESMTP PIPELINING extension may provide a great performance benefit if the message being sent has many recipients. If the server does not support pipelining, this value is ignored.

To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.

See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DirectSendServerConfig.SmtpOptions Property

DirectSendServerConfigSmtpOptions Property
Gets or sets ESMTP options specifying which SMTP extensions must not be used when communicating with the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ExtendedSmtpOptions SmtpOptions { get; set; }
Public Property SmtpOptions As ExtendedSmtpOptions
    Get
    Set

Property Value

Type: ExtendedSmtpOptions
An ExtendedSmtpOptions value containing bitwise combination of flags specifying which SMTP extensions (except PIPELINING, which is controlled by the separate Pipelining property) must not be used when communicating with the server. The default value is Default.
Remarks
To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.
See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace
SmtpServerSmtpOptions


DirectSendServerConfig.Timeout Property

DirectSendServerConfigTimeout Property
Gets or sets the amount of time (in milliseconds) the component will wait for a response from the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Timeout { get; set; }
Public Property Timeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error. The default value is DefaultTimeout.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
To access DirectSendServerConfig object, use Smtp.DirectSendDefaults property.
See Also

Reference

DirectSendServerConfig Class
MailBee.SmtpMail Namespace


DsnNotifyCondition Enumeration

DsnNotifyCondition Enumeration
Specifies events that trigger ESMTP server to send delivery status notification back to the sender of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum DsnNotifyCondition
<FlagsAttribute>
Public Enumeration DsnNotifyCondition
Members
Member name | Value | Description
Default | 0 | Send notificaton at the server discretion. Usually, this is equivalent to either Failure or bitwise combination of Failure and Delay.
Failure | 1 | Notify if message delivery fails.
Delay | 2 | Notify if message delivery is delayed.
Success | 4 | Notify if the message delivery succeeds.
Always | 7 | Notify always. This value is a bitwise combination of Failure, Delay, and Success.
Never | 8 | Do not send notification under any circumstances.
Remarks

If the SMTP server the message it submitted to supports ESMTP DSN (Delivery Status Notification) extension, it's possible to tell the server to send notifications on message delivery (successful, failed, or both) to the message sender.

If the SMTP server does not support ESMTP DSN, this value is ignored.

See Also

Reference

MailBee.SmtpMail Namespace


DsnReturnPortion Enumeration

DsnReturnPortion Enumeration
Specifies how much of the original message is returned with the delivery status notification when the message delivery fails.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum DsnReturnPortion
Public Enumeration DsnReturnPortion
Members
Member name | Value | Description
Default | 0 | Let the server decide. By default, most servers return only the message header.
Header | 1 | Return only the message header.
FullMessage | 2 | Return the entire message.
Remarks
If the message delivery succeeds and delivery status notification on succesful delivery is enabled (i.e. Success bit is set in DsnNotifyCondition), this value is not used, and only the message header is returned.
See Also

Reference

MailBee.SmtpMail Namespace


ExtendedSmtpOptions Enumeration

ExtendedSmtpOptions Enumeration
Provides flags specifying which ESMTP extensions will be enabled during SMTP session.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[FlagsAttribute]
public enum ExtendedSmtpOptions
<FlagsAttribute>
Public Enumeration ExtendedSmtpOptions
Members
Member name | Value | Description
Default | 0 | CHUNKING, DSN, SIZE, and AUTH extensions are enabled.
NoChunking | 1 | Disable CHUNKING extension (RFC1830.3). Sending large messages will be less efficient. However, some servers work slowly or don't work at all when CHUNKING is used (even though they advertize CHUNKING in the list of supported extensions). For instance, disabling CHUNKING may help with MS Exchange servers which have SMTP Tar Pitting enabled.
NoDsn | 2 | Disable Delivery Status Notification extension (RFC1891). DeliveryNotification settings will be ignored.
NoSize | 4 | Disable SIZE extension (RFC1870). Exceeding maximum allowed message size will not be detected until the message data is completely sent to the server.
ClassicSmtpMode | 8 | Completely disable ESMTP and send HELO command instead of EHLO as initial greeting. No ESMTP extensions (including PIPELINING) will be available. GetExtensions method will return a null reference (Nothing in Visual Basic). ESMTP authentication will not work (POP-before-SMTP authentication will still work if it's supported by the server).
Remarks

Even if ESMTP extensions are enabled, MailBee will use only those extensions which are supported by a particular ESMTP server. The flags provided by this enumeration should be used if the developer wishes to disable certain ESMTP extensions even if they are supported by the server.

8BITMIME/BINARYMIME ESMTP extensions are disabled by default and cannot be enabled via this enumeration's flags. This is because 8BITMIME/BINARYMIME, when used, cause problems with delivery of e-mail messages via multiple SMTP servers in chain. This happens when MailBee submits a message to 8BITMIME/BINARYMIME-enabled SMTP relay server and that server then attempts to relay the message to the end recipient's SMTP server and that destination SMTP server does not support 8BITMIME/BINARYMIME.

To enable 8BITMIME/BINARYMIME (if it's required for some reason), set Conversion8BitTo7bit property to non-default value.

Note Note
ESMTP PIPELINING extension can be disabled by setting SmtpServer.Pipelining property value to false. Or, for direct send mode (via DNS MX lookup), the property to set is Smtp.DirectSendDefaults.SmtpOptions.

To disable all extended features (except AUTH) and achieve maximum compatibility level, set Global.SafeMode to true prior to creating any instances of MailBee classes or calling their methods.

See Also

Reference

MailBee.SmtpMail Namespace
SmtpServerPipelining
GlobalSafeMode


SendFailureThreshold Enumeration

SendFailureThreshold Enumeration
Specifies whether TestSend(SendFailureThreshold) method should report error if sending failed to at least one recipient, or to all recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum SendFailureThreshold
Public Enumeration SendFailureThreshold
Members
Member name | Value | Description
Default | 0 | Use the same rules which are used when sending with Send methods. In "send to SMTP relay server" mode, AllowRefusedRecipients value is used. In direct send mode (through DNS MX lookup), failed recipients would be always allowed.
AnyRecipientsFailed | 1 | Report error if at least one recipient is refused by the SMTP server, or any other error occurred (such as failed to resolve a domain into IP address, find SMTP MX server name for a domain, connect to an SMTP MX server, etc). Other recipients are not tested (i.e. the method completes once a failed recipient detected).
AllRecipientsFailed | 2 | Report error if all recipients of the message failed, and the message cannot be sent to anybody of them.
See Also

Reference

MailBee.SmtpMail Namespace


SendMailJob Class

SendMailJob Class
Represents a task to send (or submit to the pickup folder) a single e-mail message or a series of e-mail messages created as a mail merge of a data table and an e-mail template.
Inheritance Hierarchy
SystemObject
MailBee.SmtpMailSendMailJob

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SendMailJob
Public Class SendMailJob

The SendMailJob type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetIndicesAsString | Returns the string containing comma-separated list of data table row indices yet to be processed as mail merge.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | DsnSettings | Gets a reference to the delivery status notification settings for the mail message (or their patterns for mail merge jobs).
Public property | ErrorReason | Gets the reason of the error which prevented the mail message from being sent or submitted to the pickup folder.
Public property | IsMessageSent | Gets if the message was successfully sent or submitted to the pickup folder.
Public property | MergeDataReader | Gets the data reader for the mail merge.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergedDsnSettings | Gets a reference to the delivery status notification settings produced by mail merge process.
Public property | MergedMessage | Gets a reference to the mail message produced as a result of mail merge of the template with a data row.
Public property | MergedRecipients | Gets the list of the actual recipients produced by mail merge process.
Public property | MergedSenderEmail | Gets the actual sender e-mail address string produced by mail merge process.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the data table for the mail merge.
Public property | Message | Gets a reference to the mail message object to be sent or merged.
Public property | MessageFilename | Gets the path of the e-mail file which contain the message to be sent.
Public property | PreferXSenderXReceiver | Gets if "X-Sender" and "X-Receiver" message headers have priority over any other method of specifying sender and recipients for this message.
Public property | Recipients | Gets the list of the actual recipients of the mail message (or its pattern for mail merge jobs).
Public property | SenderEmail | Gets the actual sender e-mail address string (or its pattern for mail merge jobs).
Public property | Tag | Gets the tag assigned by the developer to this job.
Top
Remarks

Send-mail job is a task for MailBee to create and/or send individual mail message or a series of messages based on a common template (mail merge).

Note Note
Mail merge over database is not supported in .NET Core and UWP apps yet.

Jobs can be created using AddJob(String, String, EmailAddressCollection) method of Smtp class (there are several overloads for mail merge and single message jobs).

Once one or more jobs have been added to the JobsPending queue, the developer can request to start processing of these jobs. This processing usually involves sending out e-mail messages contained in jobs or submitting these e-mail messages to a pickup folder for direct delivery to the SMTP server or MailBee.NET Queue if it's installed on the same machine where MailBee-powered application is running.

To start processing jobs, use SendJobs, BeginSendJobs(AsyncCallback, Object), or SubmitJobsToPickupFolder(String, Boolean) methods.

When the job assumes sending of a single e-mail message, no extra jobs are created. However, when the job is a mail merge job (and thus actually assumes creating and sending multiple messages), MailBee processes such job via creating a series of individual mail merge jobs (each of them assumes sending a single e-mail message). For instance, if a mail merge job for processing 100 data rows has been put into processing, MailBee will finally end up with 100 items total in JobsSuccessful and JobsFailed collections. This default behavior, however, can be changed with AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) overload.

Note Note
The easiest way to perform mail merge is using SendMailMerge(String, EmailAddressCollection, DataTable) method. It can be used to put a "mail merge over database" job into the queue and immediately process it, doing mail merge for each row in the data table with a e-mail template and then sending out resulting e-mail messages.
See Also

Reference

MailBee.SmtpMail Namespace
SmtpAddJob(String, String, EmailAddressCollection)
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


SendMailJob Methods

SendMailJob Methods

The SendMailJob type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
 | GetIndicesAsString | Returns the string containing comma-separated list of data table row indices yet to be processed as mail merge.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.GetIndicesAsString Method

SendMailJobGetIndicesAsString Method
Returns the string containing comma-separated list of data table row indices yet to be processed as mail merge.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetIndicesAsString()
Public Function GetIndicesAsString As String

Return Value

Type: String
Comma-separated list of data table row indices of a pending mail merge job, index of the data row of the finished job, or "0" string if this job is not a "mail merge over DataTable" job.
Remarks

For jobs which reside in Smtp.JobsPending collection, GetIndicesAsString will usually return "0" for "not a mail merge" jobs (jobs of sending a single message), "x, -1" for mail merge jobs of sending all the rows in the data table (where x is zero initially, and then x will be sequentially incremented as mail merge process comes along), or "y" where y is an index of the data row of the finished mail merge job.

However, mail merge jobs in Smtp.JobsPending can also have arbitrary sets of data row indices to be processed (for instance, "0,4,199,200,501,-1" which means "process rows 0, 4, 199, 200, 501, and the rest of the table", or "5,10,15" which means "process rows 5, 10, and 15"). A mail merge job with arbitrary set of data row indices can be placed into Smtp.JobsPending collection using Smtp.AddJob method overload.

In most cases, to get the results of mail merge (which rows have been processed successfully, which have been failed, etc), the developer should use SendMailJobCollection.GetIndicesAsString method instead. For instance, mailer.JobsFailed.GetIndicesAsString(null) (in C# syntax, assuming mailer is Smtp instance) will return all data row indices for all failed jobs. Thus, there will be no need to manually iterate through JobsFailed and call GetIndicesAsString for every job in the collection.

Note Note
For mail merge over IDataReader jobs, this method returns zero. For data readers, 'index' has no meaning. You can't address certain row of a data reader by index, you can just iterate through entire dataset to read through all the rows. Instead, event handlers must be used to track successful and failed sendings,such as in the example for SendMailMerge(String, EmailAddressCollection, IDataReader) topic.
Examples
You can find the example at AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) topic.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace
SendMailJobCollectionGetIndicesAsString(DataTable, String)
SmtpJobsPending
SmtpJobsSuccessful
SmtpJobsFailed


SendMailJob Properties

SendMailJob Properties

The SendMailJob type exposes the following members.

Properties
 | Name | Description
Public property | DsnSettings | Gets a reference to the delivery status notification settings for the mail message (or their patterns for mail merge jobs).
Public property | ErrorReason | Gets the reason of the error which prevented the mail message from being sent or submitted to the pickup folder.
Public property | IsMessageSent | Gets if the message was successfully sent or submitted to the pickup folder.
Public property | MergeDataReader | Gets the data reader for the mail merge.
Public property | MergeDataReaderColumnNames | Gets the array of all fields' names of the current row of the data reader.
Public property | MergeDataReaderRowValues | Gets the array of all fields' values of the current row of the data reader.
Public property | MergedDsnSettings | Gets a reference to the delivery status notification settings produced by mail merge process.
Public property | MergedMessage | Gets a reference to the mail message produced as a result of mail merge of the template with a data row.
Public property | MergedRecipients | Gets the list of the actual recipients produced by mail merge process.
Public property | MergedSenderEmail | Gets the actual sender e-mail address string produced by mail merge process.
Public property | MergeRowIndex | Gets the index of the data row used for mail merge of this message.
Public property | MergeTable | Gets the data table for the mail merge.
Public property | Message | Gets a reference to the mail message object to be sent or merged.
Public property | MessageFilename | Gets the path of the e-mail file which contain the message to be sent.
Public property | PreferXSenderXReceiver | Gets if "X-Sender" and "X-Receiver" message headers have priority over any other method of specifying sender and recipients for this message.
Public property | Recipients | Gets the list of the actual recipients of the mail message (or its pattern for mail merge jobs).
Public property | SenderEmail | Gets the actual sender e-mail address string (or its pattern for mail merge jobs).
Public property | Tag | Gets the tag assigned by the developer to this job.
Top
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.DsnSettings Property

SendMailJobDsnSettings Property
Gets a reference to the delivery status notification settings for the mail message (or their patterns for mail merge jobs).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryNotificationOptions DsnSettings { get; }
Public ReadOnly Property DsnSettings As DeliveryNotificationOptions
    Get

Property Value

Type: DeliveryNotificationOptions
A reference to the delivery status notification (DSN) settings for the mail message, or DNS template for mail merge jobs.
Remarks

For mail merge, DsnSettings property allows the application to use templates for DSN settings. For instance, using pattern in TrackingID value can be used to assign individual TrackingID for each mail message generated during mail merge.

Note Note
In order to use DSN, make sure the SMTP server supports DSN extension (see DeliveryNotificationOptions section for more information).
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.ErrorReason Property

SendMailJobErrorReason Property
Gets the reason of the error which prevented the mail message from being sent or submitted to the pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailBeeException ErrorReason { get; }
Public ReadOnly Property ErrorReason As MailBeeException
    Get

Property Value

Type: MailBeeException
A reference to the exception (descendant of MailBeeException) which prevented the mail message from successful sending or submitting to the pickup folder, or a null reference (Nothing in Visual Basic) if the mail message was sent or submitted successfully.
Remarks
Because methods which process jobs queue (such as SendJobs or SubmitJobsToPickupFolder(String, Boolean)) operate on multiple jobs in this queue, it would be inconvenient if failure of any job stopped the entire process. Thus, methods which process jobs do not raise exceptions and silently continue to the next job in the queue in the case of error. Still, the application has ways of tracking failures (for instance, MessageNotSent event or JobsFailed collection). In the case of JobsFailed, ErrorReason can be used for every job in this collection to determine exact reason of the error.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace
SmtpJobsFailed


SendMailJob.IsMessageSent Property

SendMailJobIsMessageSent Property
Gets if the message was successfully sent or submitted to the pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsMessageSent { get; }
Public ReadOnly Property IsMessageSent As Boolean
    Get

Property Value

Type: Boolean
true if the message was successfully sent (for methods such as SendJobs) or submitted to the pickup folder (for methods such as SubmitJobsToPickupFolder(String, Boolean)).
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.MergeDataReader Property

SendMailJobMergeDataReader Property
Gets the data reader for the mail merge.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IDataReader MergeDataReader { get; }
Public ReadOnly Property MergeDataReader As IDataReader
    Get

Property Value

Type: IDataReader
A reference to the source of the data for mail merge, or a null reference (Nothing in Visual Basic) if this job is not a "mail merge over data reader" job.
Remarks
This property can be used in single-threaded mode only. In multi-threaded mode, you usually cannot access any data from the reader as it may be accessed by concurrent threads, and they may advance the reader before you get a chance to read anything from it. Use MergeDataReaderRowValues property instead.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.MergeDataReaderColumnNames Property

SendMailJobMergeDataReaderColumnNames Property
Gets the array of all fields' names of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] MergeDataReaderColumnNames { get; }
Public ReadOnly Property MergeDataReaderColumnNames As String()
    Get

Property Value

Type: String
A reference to the string array where each item is the result of GetName(Int32) call for each column, made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks

Can be used in conjunction with MergeDataReaderRowValues property to access elements by their names, such as with e.MergeDataReaderRowValues[Array.IndexOf(e.MergeDataReaderColumnNames, "id")] call (in C# syntax, assuming e is SendMailJob instance).

If you know the index of the field you need to access, you can use it directly, such as e.MergeDataReaderRowValues[0].

See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.MergeDataReaderRowValues Property

SendMailJobMergeDataReaderRowValues Property
Gets the array of all fields' values of the current row of the data reader.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object[] MergeDataReaderRowValues { get; }
Public ReadOnly Property MergeDataReaderRowValues As Object()
    Get

Property Value

Type: Object
A reference to the result of GetValues(Object) call made at the moment when the component extracted data from the current data row, or a null reference (Nothing in Visual Basic) in case if the input wasn't IDataReader.
Remarks
This property is useful in case of multi-threaded e-mail verification when the IDataReader could have already advance to next records to the moment when this event occurs. It guarantees that the data in this array will correspond to that e-mail address for which this event was raised.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.MergedDsnSettings Property

SendMailJobMergedDsnSettings Property
Gets a reference to the delivery status notification settings produced by mail merge process.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryNotificationOptions MergedDsnSettings { get; }
Public ReadOnly Property MergedDsnSettings As DeliveryNotificationOptions
    Get

Property Value

Type: DeliveryNotificationOptions
The delivery status notification (DSN) settings produced by mail merge process, or a null reference (Nothing in Visual Basic) if this job is not a mail merge job or if the merged message is no longer needed.
Remarks
This property plays the same role for DsnSettings as MergedMessage does for Message.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace
SendMailJobDsnSettings
SendMailJobMergedMessage


SendMailJob.MergedMessage Property

SendMailJobMergedMessage Property
Gets a reference to the mail message produced as a result of mail merge of the template with a data row.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage MergedMessage { get; }
Public ReadOnly Property MergedMessage As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the mail message produced as a result of mail merge of the template with a single data table row, or a null reference (Nothing in Visual Basic) if this job is not a mail merge job or if the merged message is no longer needed.
Remarks

In most cases, this property returns null because the merged message is not yet available before the job goes into processing, and is no longer available once the job is finished (MailBee removes merged message object from memory to avoid having MailMessage objects for every data row in memory simultaneously).

However, the developer may prevent automatic disposing of MailMessage objects created during mail merge: to put the mail merge job into pending list, call AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) method with keepMergedData set to true.

See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.MergedRecipients Property

SendMailJobMergedRecipients Property
Gets the list of the actual recipients produced by mail merge process.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection MergedRecipients { get; }
Public ReadOnly Property MergedRecipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
The list of the actual recipients produced by mail merge process, or a null reference (Nothing in Visual Basic) if this job is not a mail merge job or if the merged message is no longer needed.
Remarks
This property plays the same role for Recipients as MergedMessage does for Message.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace
SendMailJobRecipients
SendMailJobMergedMessage


SendMailJob.MergedSenderEmail Property

SendMailJobMergedSenderEmail Property
Gets the actual sender e-mail address string produced by mail merge process.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MergedSenderEmail { get; }
Public ReadOnly Property MergedSenderEmail As String
    Get

Property Value

Type: String
The actual sender e-mail address string produced by mail merge process, or a null reference (Nothing in Visual Basic) if this job is not a mail merge job or if the merged message is no longer needed.
Remarks
This property plays the same role for SenderEmail as MergedMessage does for Message.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace
SendMailJobSenderEmail
SendMailJobMergedMessage


SendMailJob.MergeRowIndex Property

SendMailJobMergeRowIndex Property
Gets the index of the data row used for mail merge of this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MergeRowIndex { get; }
Public ReadOnly Property MergeRowIndex As Integer
    Get

Property Value

Type: Int32
The index of the data row in MergeTable data table used for mail merge of this message, or zero if this mail message was not composed as a merge of database data with mail template.
Remarks

For mail merge operations, job.MergeTable[e.MergeRowIndex] (in C# syntax, assuming job is an instance of SendMailJob class) returns the first DataRow to be merged with the template.

Since SendMailJob objects in JobsPending collection can represent mail merge jobs of processing multiple data rows, MergeRowIndex can actually refer to the first data row index in the entire list data row indices associated with such SendMailJob object. To get all the indices, use GetIndicesAsString method.

See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.MergeTable Property

SendMailJobMergeTable Property
Gets the data table for the mail merge.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DataTable MergeTable { get; }
Public ReadOnly Property MergeTable As DataTable
    Get

Property Value

Type: DataTable
A reference to the source of the data for mail merge, or a null reference (Nothing in Visual Basic) if this job is not a "mail merge over data table" job.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.Message Property

SendMailJobMessage Property
Gets a reference to the mail message object to be sent or merged.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Message { get; }
Public ReadOnly Property Message As MailMessage
    Get

Property Value

Type: MailMessage
A reference to the mail message object (if the job consists of sending a single e-mail message, not mail merge) or a template e-mail for mail merge.
Remarks

If the job is of sending a single e-mail message supplied by the application, Message refers to the mail message object to be sent. If the job is a mail merge job, Message refers to the template which will be merged (or, for finished jobs, was already merged) with data table rows.

For mail merge jobs, the developer can use MergedMessage property to get the result of mail merge of the template with a data row. However, MailBee does not keep merged messages in finished jobs to avoid memory overhead (unless AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) method was called with keepMergedData set to true).

See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace
SendMailJobMergedMessage


SendMailJob.MessageFilename Property

SendMailJobMessageFilename Property
Gets the path of the e-mail file which contain the message to be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string MessageFilename { get; }
Public ReadOnly Property MessageFilename As String
    Get

Property Value

Type: String
The e-mail filename or a null reference (Nothing in Visual Basic) if this job is not a "send e-mail from file" job.
Remarks
This property provides access to the value of msgFilename parameter of AddJob(String, String, Boolean, String, EmailAddressCollection) method call which was used to create this job.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.PreferXSenderXReceiver Property

SendMailJobPreferXSenderXReceiver Property
Gets if "X-Sender" and "X-Receiver" message headers have priority over any other method of specifying sender and recipients for this message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool PreferXSenderXReceiver { get; }
Public ReadOnly Property PreferXSenderXReceiver As Boolean
    Get

Property Value

Type: Boolean
true if "X-Sender" and "X-Receiver" message headers have priority over any other method of specifying sender and recipients for this message; otherwise, false. Not defined for jobs which are not "send e-mail from file" jobs.
Remarks
This property provides access to the value of preferXSenderXReceiver parameter of AddJob(String, String, Boolean, String, EmailAddressCollection) method call which was used to create this job.
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.Recipients Property

SendMailJobRecipients Property
Gets the list of the actual recipients of the mail message (or its pattern for mail merge jobs).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Recipients { get; }
Public ReadOnly Property Recipients As EmailAddressCollection
    Get

Property Value

Type: EmailAddressCollection
A reference to the collection of the actual recipients of the mail message, or an actual recipients template for mail merge jobs.
Remarks
This collection usually lists "To", "CC", and "BCC" recipients of the mail message. However, it can be different if the e-mail or mail merge needs to be sent to fake addresses (when "To:" and/or "Cc:" and "Bcc:" addresses are different from SMTP "RCPT TO:" addresses). To achieve this, call AddJob(String, String, EmailAddressCollection) method with non-null value of recipients parameter (or recipientsPattern for mail merge overloads of this method).
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.SenderEmail Property

SendMailJobSenderEmail Property
Gets the actual sender e-mail address string (or its pattern for mail merge jobs).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SenderEmail { get; }
Public ReadOnly Property SenderEmail As String
    Get

Property Value

Type: String
The string containing the e-mail address of the actual sender of the mail message, or an actual sender e-mail address template for mail merge jobs.
Remarks
This address is usually the same as "From:" address of the mail message (or mail merge template). However, it can be different if the e-mail or mail merge needs to be sent from fake address (when "From:" address is different from SMTP "MAIL FROM:" address). To achieve this, call AddJob(String, String, EmailAddressCollection) method with non-null value of senderEmail parameter (or senderEmailPattern for mail merge overloads of this method).
See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJob.Tag Property

SendMailJobTag Property
Gets the tag assigned by the developer to this job.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Tag { get; }
Public ReadOnly Property Tag As String
    Get

Property Value

Type: String
A string assigned to the job by the developer, or empty string if tag was not assigned.
Remarks

The developer can use tags to to keep track of the processed jobs. Tags also appear in the log helping to match log messages to particular jobs.

To enqueue a job so that it would have tag assigned, the developer should use Smtp.AddJob(string, string, EmailAddressCollection) or Smtp.AddJob(string, string, EmailAddressCollection, DataTable, object, bool, bool) methods.

See Also

Reference

SendMailJob Class
MailBee.SmtpMail Namespace


SendMailJobCollection Class

SendMailJobCollection Class
Represents a collection of assigned tasks of sending e-mails.
Inheritance Hierarchy
SystemObject
MailBee.SmtpMailSendMailJobCollection

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class SendMailJobCollection : ICollection,
    IEnumerable
Public Class SendMailJobCollection
    Implements ICollection, IEnumerable

The SendMailJobCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds a send-mail job into the collection.
Public method | Clear | Removes all elements from the collection.
Public method | CopyTo | Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that can iterate through the collection.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetIndicesAsArray | Returns the integer array containing list of data table row indices associated with the jobs belonging to the collection.
 | GetIndicesAsString | Returns the string containing comma-separated list of data table row indices associated with the jobs belonging to the collection.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Remove | Removes the specified SendMailJob from the collection.
Public method | RemoveAt | Removes the job with the specified index from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Count | Gets the number of elements contained in the collection.
Public property | IsReadOnly | Gets whether the collection may not be modified.
Public property | IsSynchronized | Gets a value indicating whether access to the collection is synchronized (thread-safe).
Public property | Item | Gets the element at the specified index.
Public property | SyncRoot | Gets an object that can be used to synchronize access to the collection.
Top
Remarks

In MailBee, instances of this class contain lists of mail messages or mail merge tasks which will be (or already have been) processed.

JobsPending, JobsRunning, JobsSuccessful, and JobsFailed properties of Smtp class have SendMailJobCollection type.

JobsPending contains jobs to be processed, JobsRunning - currently being processed, JobsSuccessful and JobsFailed - finished jobs.

During processing, jobs migrate between the collections (i.e. the job which had originally been placed into JobsPending moves into JobsRunning when processing starts, and ends up in JobsSuccessful or JobsFailed).

However, mail merge jobs may spawn additional jobs. I.e. if a mail merge job of processing 10 data table rows goes into processing, it resides in JobsPending for a while (and the number of rows yet to be processed sequentially decrements to 9, 8, etc). At the same time, rows which are being processed are converted into SendMailJob objects representing tasks to process a single data row as mail merge. Thus, usually mail merge of 10 data rows (a single job) finally ends up in 10 SendMailJob objects in JobsSuccessful or JobsFailed collections. To change this behavior, create mail merge jobs using Smtp.AddJob(string, string, EmailAddressCollection, DataTable, object, bool, bool) overload or its IDataReader version (Smtp.AddJob(string, string, EmailAddressCollection, IDataReader, object, bool, bool)).

Note Note
In .NET Core and UWP apps, only single-message mail jobs are supported. There is no mail merge over database support.
See Also

Reference

MailBee.SmtpMail Namespace
MailBee.SmtpMailSendMailJob


SendMailJobCollection Methods

SendMailJobCollection Methods

The SendMailJobCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add | Adds a send-mail job into the collection.
Public method | Clear | Removes all elements from the collection.
Public method | CopyTo | Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that can iterate through the collection.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetIndicesAsArray | Returns the integer array containing list of data table row indices associated with the jobs belonging to the collection.
 | GetIndicesAsString | Returns the string containing comma-separated list of data table row indices associated with the jobs belonging to the collection.
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Remove | Removes the specified SendMailJob from the collection.
Public method | RemoveAt | Removes the job with the specified index from the collection.
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.Add Method

SendMailJobCollectionAdd Method
Adds a send-mail job into the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    SendMailJob job
)
Public Sub Add (
    job As SendMailJob
)

Parameters

job
Type: MailBee.SmtpMailSendMailJob
A job of sending a single e-mail or processing one or more data table rows as mail merge.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | job is a null reference (Nothing in Visual Basic).
MailBeeInvalidStateException | The collection is read-only.
Remarks
JobsRunning collection is read-only. Only MailBee itself can modify this collection. Other collections (JobsPending, JobsSuccessful, JobsFailed) are editable.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.Clear Method

SendMailJobCollectionClear Method
Removes all elements from the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Clear()
Public Sub Clear
Exceptions
Exception | Condition
MailBeeInvalidStateException | The collection is read-only.
Remarks
JobsRunning collection is read-only. Only MailBee itself can modify this collection. Other collections (JobsPending, JobsSuccessful, JobsFailed) are editable.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.CopyTo Method

SendMailJobCollectionCopyTo Method
Copies the entire collection to a compatible one-dimensional Array, starting at the specified index of the target array.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void CopyTo(
    Array array,
    int index
)
Public Sub CopyTo (
    array As Array,
    index As Integer
)

Parameters

array
Type: SystemArray
The one-dimensional Array that is the destination of the elements copied from the collection. The Array must have zero-based indexing.
index
Type: SystemInt32
The zero-based index in array at which copying begins.

Implements

ICollectionCopyTo(Array, Int32)
Remarks
This method simply calls CopyTo(Array) to copy the elements and thus may also throw exceptions specific to that method.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.GetEnumerator Method

SendMailJobCollectionGetEnumerator Method
Returns an enumerator that can iterate through the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public IEnumerator GetEnumerator()
Public Function GetEnumerator As IEnumerator

Return Value

Type: IEnumerator
An IEnumerator for the collection.

Implements

IEnumerableGetEnumerator
Remarks
This method simply calls GetEnumerator to get the enumerator.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.GetIndicesAsArray Method

SendMailJobCollectionGetIndicesAsArray Method
Returns the integer array containing list of data table row indices associated with the jobs belonging to the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int[] GetIndicesAsArray(
    DataTable mergeTable,
    string tag
)
Public Function GetIndicesAsArray (
    mergeTable As DataTable,
    tag As String
) As Integer()

Parameters

mergeTable
Type: System.DataDataTable
A reference to the data table for which data row indices should be returned, or a null reference (Nothing in Visual Basic) if data rows should be returned regardless with which mail merge tables they are associated.
tag
Type: SystemString
The string equal to Tag of jobs for which data row indices should be returned, or a null reference (Nothing in Visual Basic) if data rows should be returned regardless of their Tag value. String comparison is case-sensitive, i.e. Merge1 and MERGE1 won't match!

Return Value

Type: Int32
The integer array containing list of data table row indices associated with the jobs belonging to the collection and associated with the given data table, or an empty integer array if the collection is empty.
Remarks
This method is identical to GetIndicesAsString(DataTable, String) except for the type of the returned value.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace
SendMailJobCollectionGetIndicesAsString(DataTable, String)


SendMailJobCollection.GetIndicesAsString Method

SendMailJobCollectionGetIndicesAsString Method
Returns the string containing comma-separated list of data table row indices associated with the jobs belonging to the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetIndicesAsString(
    DataTable mergeTable,
    string tag
)
Public Function GetIndicesAsString (
    mergeTable As DataTable,
    tag As String
) As String

Parameters

mergeTable
Type: System.DataDataTable
A reference to the data table for which data row indices should be returned, or a null reference (Nothing in Visual Basic) if data rows should be returned regardless with which mail merge tables they are associated.
tag
Type: SystemString
The string equal to Tag of jobs for which data row indices should be returned, or a null reference (Nothing in Visual Basic) if data rows should be returned regardless of their Tag value. String comparison is case-sensitive, i.e. Merge1 and MERGE1 won't match!

Return Value

Type: String
The string containing comma-separated list of data table row indices associated with the jobs belonging to the collection and associated with the given data table, or an empty string if the collection is empty.
Remarks

This method can be typically used to get the results of mail merge (which rows have been processed successfully, which have been failed, etc). Later, Smtp.AddJobs method can be used to populate Smtp.JobsPending collection with the stored values.

If, for some reason, the developer needs to work with indices of particular jobs, this can be done using SendMailJob.GetIndicesAsString method. The current method internally uses SendMailJob.GetIndicesAsString to get indices for jobs that match the given criteria. See SendMailJob.GetIndicesAsString method documentation for more information on how MailBee returns indices of a single job's data rows.

Note Note

To place failed jobs back into Smtp.JobsPending collection, it's easier to use Smtp.RetryFailedJobs method. However, Smtp.RetryFailedJobs method cannot be used in the case if the application shuts down after performing mail merge cycle and thus all the information in the Smtp.JobsXXX collections gets lost.

In this case, the developer may want to get the list of failed data rows and then save it into persistent storage such as a file or a database. Later, the application starts again, loads this file and gets the list of data rows to process, and processes them. This scenario can be implemented with GetIndicesAsString(DataTable, String) and Smtp.AddJobs methods.

Examples
You can find the example at AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) topic.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace
SendMailJobGetIndicesAsString
SmtpJobsPending
SmtpJobsSuccessful
SmtpJobsFailed


SendMailJobCollection.Remove Method

SendMailJobCollectionRemove Method
Removes the specified SendMailJob from the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Remove(
    SendMailJob job
)
Public Sub Remove (
    job As SendMailJob
)

Parameters

job
Type: MailBee.SmtpMailSendMailJob
The job (which assumes sending a single e-mail or processing one or more data table rows as mail merge) to be removed from the collection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | The collection is read-only.
Remarks
JobsRunning collection is read-only. Only MailBee itself can modify this collection. Other collections (JobsPending, JobsSuccessful, JobsFailed) are editable.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.RemoveAt Method

SendMailJobCollectionRemoveAt Method
Removes the job with the specified index from the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RemoveAt(
    int index
)
Public Sub RemoveAt (
    index As Integer
)

Parameters

index
Type: SystemInt32
The zero-based index of SendMailJob to be removed from the collection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | The collection is read-only.
Remarks

JobsRunning collection is read-only. Only MailBee itself can modify this collection. Other collections (JobsPending, JobsSuccessful, JobsFailed) are editable.

Except for read-only check, this method simply calls RemoveAt(Int32) and thus may also throw exceptions specific to that method.

See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection Properties

SendMailJobCollection Properties

The SendMailJobCollection type exposes the following members.

Properties
 | Name | Description
Public property | Count | Gets the number of elements contained in the collection.
Public property | IsReadOnly | Gets whether the collection may not be modified.
Public property | IsSynchronized | Gets a value indicating whether access to the collection is synchronized (thread-safe).
Public property | Item | Gets the element at the specified index.
Public property | SyncRoot | Gets an object that can be used to synchronize access to the collection.
Top
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.Count Property

SendMailJobCollectionCount Property
Gets the number of elements contained in the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Count { get; }
Public ReadOnly Property Count As Integer
    Get

Property Value

Type: Int32
The number of elements contained in the collection.

Implements

ICollectionCount
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.IsReadOnly Property

SendMailJobCollectionIsReadOnly Property
Gets whether the collection may not be modified.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsReadOnly { get; }
Public ReadOnly Property IsReadOnly As Boolean
    Get

Property Value

Type: Boolean
true if the collection may not be modified and any attempt to call a method which modifies the collection will raise MailBeeInvalidStateException exception; otherwise, false.
Remarks
JobsRunning is a collection which may not be modified by the application. MailBee maintains this collection itself, the application is only allowed to monitor it (for instance, to keep track of the jobs currently being processed).
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.IsSynchronized Property

SendMailJobCollectionIsSynchronized Property
Gets a value indicating whether access to the collection is synchronized (thread-safe).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSynchronized { get; }
Public ReadOnly Property IsSynchronized As Boolean
    Get

Property Value

Type: Boolean
true if access to the collection is synchronized (thread-safe); otherwise, false. The default is false.

Implements

ICollectionIsSynchronized
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.Item Property

SendMailJobCollectionItem Property
Gets the element at the specified index.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SendMailJob this[
    int index
] { get; }
Public ReadOnly Default Property Item (
    index As Integer
) As SendMailJob
    Get

Parameters

index
Type: SystemInt32
The zero-based index of the entry to get.

Property Value

Type: SendMailJob
The element at the specified index.
Remarks
This method simply calls ItemInt32 to get the element and thus may also throw exceptions specific to that method.
See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


SendMailJobCollection.SyncRoot Property

SendMailJobCollectionSyncRoot Property
Gets an object that can be used to synchronize access to the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object SyncRoot { get; }
Public ReadOnly Property SyncRoot As Object
    Get

Property Value

Type: Object
An object that can be used to synchronize access to the collection.

Implements

ICollectionSyncRoot
Remarks

Synchronized access to the collection is required in multi-thread mode when multiple threads can access it at the same time.

SyncRoot property can be used just in the same way as other SyncRoot properties in the .NET framework, for instance, Array.SyncRoot.

See Also

Reference

SendMailJobCollection Class
MailBee.SmtpMail Namespace


Smtp Class

Smtp Class
Provides properties and methods for sending messages using the SMTP protocol.
Inheritance Hierarchy
SystemObject
MailBee.SmtpMailSmtp

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class Smtp : IComponent, IDisposable
Public Class Smtp
    Implements IComponent, IDisposable

The Smtp type exposes the following members.

Constructors
 | Name | Description
Public method | Smtp | Creates an instance of Smtp class.
Public method | Smtp(String) | Creates and unlocks an instance of Smtp class.
Top
Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | AddAttachment | Reads the specified file from disk and adds it as attachment to the message.
Public method | AddAttachmentAsync | async/await version of AddAttachment(String).
 | AddJob(String, String, EmailAddressCollection) | Puts an e-mail message onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, MailMessage, String, EmailAddressCollection) | Puts the specified e-mail message onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, DataTable) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, IDataReader) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, Boolean, String, EmailAddressCollection) | Puts the e-mail message stored in an .EML file onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, IDataReader, Boolean, Boolean) | Puts a "mail merge over data reader" job onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
 | AuthPopBeforeSmtp | Authenticates the user on a mail server using POP-before-SMTP authentication.
Public method | AuthPopBeforeSmtpAsync | async/await version of AuthPopBeforeSmtp(String, Int32, String, String).
 | BeginAuthPopBeforeSmtp | Obsolete. Begins an asynchronous request for a POP-before-SMTP authentication on a mail server.
 | BeginConnect | Obsolete. Begins an asynchronous request for connecting to an SMTP server.
Public method | BeginDisconnect | Obsolete. Begins an asynchronous request for a disconnection from the server.
 | BeginExecuteCustomCommand | Obsolete. Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.
 | BeginHello | Obsolete. Begins an asynchronous request for sending initial greeting to the SMTP server.
 | BeginLogin | Obsolete. Begins an asynchronous request for authenticating the user on the SMTP server.
 | BeginRelayFromEmlFile | Obsolete. Begins an asynchronous request for relaying a mail message to recipients.
 | BeginSend | Obsolete. Begins an asynchronous request for sending a mail message to recipients.
 | BeginSendJobs | Obsolete. Begins an asynchronous request to process the pending jobs and send out the resulting e-mails.
 | BeginStartTls | Obsolete. Begins an asynchronous request to start TLS/SSL negotiation with the server.
 | Connect | Connects to an SMTP server.
Public method | ConnectAsync | async/await version of Connect.
Public method | Disconnect | Disconnects from the SMTP server and releases any used resources.
Public method | DisconnectAsync | async/await version of Disconnect.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Public method | EndAuthPopBeforeSmtp | Ends the pending asynchronous request for POP-before-SMTP authentication on a mail server.
Public method | EndConnect | Ends the pending asynchronous request for connecting to the SMTP server.
Public method | EndDisconnect | Ends a pending asynchronous disconnection request.
Public method | EndExecuteCustomCommand | Ends the pending asynchronous request for sending user-defined command to the server.
Public method | EndHello | Ends the pending asynchronous request for sending a greeting to the SMTP server.
Public method | EndLogin | Ends the pending asynchronous request for authenticating the user on the SMTP server.
Public method | EndRelayFromEmlFile | Ends the pending asynchronous request for relaying the message to the recipients.
Public method | EndSend | Ends the pending asynchronous request for sending the message to the recipients.
Public method | EndSendJobs | Ends the pending asynchronous request for processing the pending jobs and sending out the resulting e-mails.
Public method | EndStartTls | Ends a pending asynchronous TLS/SSL negotiation request.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | ExecuteCustomCommand | Sends user-defined command to the server and receives the server response to this command.
Public method | ExecuteCustomCommandAsync | async/await version of ExecuteCustomCommand(String).
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAcceptedRecipients | Returns the list of the recipients accepted by the SMTP server.
Public method | GetCurrentSmtpServerIndex | Returns SmtpServers collection's index of the server to which the component is connected or will connect on the next connection attempt.
Public method | GetErrorDescription | Returns a textual description of the last error.
 | GetExtension | Returns the name or parameters of the specified ESMTP capability.
 | GetExtensions | Returns a reference to the key-value list of the server capabilities.
Public method | GetExtensionValue | Returns the parameters of the specified ESMTP capability, or an empty string if the capability has no parameters.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMaxMessageSize | Returns the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.
 | GetMXHosts | Retrieves the list of hosts willing to accept mail for the given domain.
Public method | GetMXHostsAsync | async/await version of GetMXHosts(String).
 | GetPtrData | Retrieves the list of domain names for the specified IP address.
Public method | GetPtrDataAsync | async/await version of GetPtrData(String).
Public method | GetRefusedRecipients | Returns the list of the recipients rejected by the SMTP server.
Public method | GetServerResponse | Returns the last response from the server.
Public method | GetServerResponseCode | Returns an integer value containing the status code of the last SMTP operation.
Public method | GetSocket | Returns the underlying Socket MailBee uses for the current SMTP connection.
Public method | GetSocketError | Returns a Win32 error code of the last socket-related error.
Public method | GetStream | Returns the underlying Stream MailBee uses for the current network connection.
 | GetSupportedAuthMethods | Returns a set of flags indicating which authentication methods are supported by the server.
 | GetTxtData | Retrieves the list of TXT strings of DNS data of the specified domain.
Public method | GetTxtDataAsync | async/await version of GetTxtData(String).
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | Hello | Sends initial greeting to the SMTP server.
Public method | HelloAsync | async/await version of Hello.
 | Login | Authenticates the user on the SMTP server if ESMTP authentication is enabled.
Public method | LoginAsync | async/await version of Login.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Noop | Sends a NOOP command to the server.
Public method | NoopAsync | async/await version of Noop.
Protected method | OnConnected | Used by MailBee to raise Connected event.
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnDisconnected | Used by MailBee to raise Disconnected event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnFinishingJob | Used by MailBee to raise FinishingJob event.
Protected method | OnHostResolved | Used by MailBee to raise HostResolved event.
Protected method | OnLoggedIn | Used by MailBee to raise LoggedIn event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnLowLevelDataReceived | Used by MailBee to raise LowLevelDataReceived event.
Protected method | OnLowLevelDataSent | Used by MailBee to raise LowLevelDataSent event.
Protected method | OnMergingMessage | Used by MailBee to raise MergingMessage event.
Protected method | OnMessageDataChunkSent | Used by MailBee to raise MessageDataChunkSent event.
Protected method | OnMessageDirectSendDone | Used by MailBee to raise MessageDirectSendDone event.
Protected method | OnMessageMXLookupDone | Used by MailBee to raise MessageMXLookupDone event.
Protected method | OnMessageNotSent | Used by MailBee to raise MessageNotSent event.
Protected method | OnMessageRecipientSubmitted | Used by MailBee to raise MessageRecipientSubmitted event.
Protected method | OnMessageSenderSubmitted | Used by MailBee to raise MessageSenderSubmitted event.
Protected method | OnMessageSent | Used by MailBee to raise MessageSent event.
Protected method | OnMessageSubmittedToPickupFolder | Used by MailBee to raise MessageSubmittedToPickupFolder event.
Protected method | OnMessageSubmittedToServer | Used by MailBee to raise MessageSubmittedToServer event.
Protected method | OnSendingMessage | Used by MailBee to raise SendingMessage event.
Protected method | OnSocketConnected | Used by MailBee to raise SocketConnected event.
Protected method | OnSocketCreating | Used by MailBee to raise SocketCreating event.
Protected method | OnSubmittingMessageToPickupFolder | Used by MailBee to raise SubmittingMessageToPickupFolder event.
Protected method | OnTlsStarted | Used by MailBee to raise TlsStarted event.
Protected method | OnTransientErrorOccurred | Used by MailBee to raise TransientErrorOccurred event.
 | QuickSend(MailMessage) | Sends a mail message, in a single line of code.
 | QuickSend(String, String, String, String) | Sends a mail message, in a single line of code.
 | QuickSend(String, String, String, String, String, String, String) | Sends a mail message, in a single line of code.
 | RelayFromEmlFile(String, String, EmailAddressCollection) | Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.
 | RelayFromEmlFile(String, String, String) | Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.
Public method | RelayFromEmlFileAsync(String, String, EmailAddressCollection) | async/await version of RelayFromEmlFile(String, String, EmailAddressCollection).
Public method | RelayFromEmlFileAsync(String, String, String) | async/await version of RelayFromEmlFile(String, String, String).
Public method | ResetMessage | Resets all properties of Message object to defaults. Delivery Status Notification settings (DeliveryNotification object) are also reset.
Public method | ResetState | Resets the internal state of the component.
 | RetryFailedJobs | Puts all failed send-mail jobs back into the queue.
 | Send | Sends the mail message to the recipients specified in the message.
 | Send(String, EmailAddressCollection) | Sends the mail message to the specified recipients.
 | Send(String, String) | Sends the mail message to the specified recipients e-mail addresses.
Public method | SendAsync | async/await version of Send.
Public method | SendAsync(String, EmailAddressCollection) | async/await version of Send(String, EmailAddressCollection).
Public method | SendAsync(String, String) | async/await version of Send(String, String).
 | SendJobs | Sends out all e-mails in the pending jobs queue (including e-mails generated via mail merge).
Public method | SendJobsAsync | async/await version of SendJobs.
 | SendMailMerge(String, EmailAddressCollection, DataTable) | Creates a series of e-mails based on an e-mail message template and a data table and sends these e-mails out.
 | SendMailMerge(String, EmailAddressCollection, IDataReader) | Creates a series of e-mails based on an e-mail message template and a data reader and sends these e-mails out.
Public method | SendMailMergeAsync(String, EmailAddressCollection, DataTable) | async/await version of SendMailMerge(String, EmailAddressCollection, DataTable).
Public method | SendMailMergeAsync(String, EmailAddressCollection, IDataReader) | async/await version of SendMailMerge(String, EmailAddressCollection, IDataReader).
 | StartTls | Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.
Public method | StartTlsAsync | async/await version of StartTls.
 | StopJobs | Notifies MailBee to stop processing jobs, completing sending out of all messages currently being processed.
 | SubmitJobsToPickupFolder | Saves all e-mails in the pending jobs queue (including e-mails generated via mail merge) as files in the pickup folder of MailBee.NET Queue or IIS SMTP service.
Public method | SubmitJobsToPickupFolderAsync | async/await version of SubmitJobsToPickupFolder(String, Boolean).
 | SubmitToPickupFolder(String, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
 | SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
 | SubmitToPickupFolder(String, String, String, String, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
Public method | SubmitToPickupFolderAsync(String, Boolean) | async/await version of SubmitToPickupFolder(String, Boolean).
Public method | SubmitToPickupFolderAsync(String, String, String, EmailAddressCollection, Boolean) | async/await version of SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean).
Public method | SubmitToPickupFolderAsync(String, String, String, String, Boolean) | async/await version of SubmitToPickupFolder(String, String, String, String, Boolean).
 | TestSend | Tests sending a mail message to the recipients without actual submitting of the message data.
Public method | TestSendAsync | async/await version of TestSend(SendFailureThreshold).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | ValidateEmailAddressSyntax | Verifies if the specified string is a correctly formatted e-mail address.
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
Properties
 | Name | Description
 | Bcc | Gets or sets EmailAddressCollection object specifying BCC: recipients of the message.
 | BodyHtmlText | Gets or sets HTML version of the message body.
 | BodyPlainText | Gets or sets plain-text version of the message body.
 | Cc | Gets or sets EmailAddressCollection object specifying CC: recipients of the message.
 | Charset | Gets or sets charset of the message.
Public property | Conversion8BitTo7bit | Gets or sets if (and how) the component should perform 8bit-to-7bit conversion of the message data if the given SMTP server does not support transmission of 8bit data but the message does contain such data.
Public property | DeliveryNotification | Provides access to properties which control when and how ESMTP Delivery Status Notification messages will be sent to the message sender.
 | DirectSendDefaults | Provides access to the default SMTP server settings to be used when connecting to SMTP servers discovered by MailBee via DNS MX lookup.
 | DnsServers | Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.
 | From | Gets or sets EmailAddress object specifying the message sender.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | IsConnected | Indicates whether the component is connected to the server.
Public property | IsLoggedIn | Indicates whether the component has already successfully authenticated on the server and logged in the user account.
Public property | IsSmtpContext | Indicates whether the component is currently operating in a single thread mode, and the current connection (if any) is an SMTP connection.
Public property | IsSslConnection | Indicates whether the current connection (if any) is secured with TLS/SSL layer.
Public property | JobsFailed | Gets the list of e-mail tasks failed during processing.
Public property | JobsPending | Gets the list of send-mail (sending a single message or mail-merge) tasks ready for processing.
Public property | JobsRunning | Gets the list of e-mail tasks being processed right now.
Public property | JobsSuccessful | Gets the list of successfully processed e-mail tasks.
 | JobsSyncRoot | Gets the object to be used for synchronized access to the jobs collections.
Public property | LastResult | Gets a numeric code of the last error.
 | LicenseKey | Obsolete. Assigns the license key.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
 | MaxThreadCount | Gets or sets the maximum number of threads MailBee may create during send mail operations.
 | Message | Gets or sets the mail message which will be sent by the component on Send method call.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RaiseEventsViaMessageLoop | Gets or sets whether the events will be raised on the message loop of the application or not.
 | ReplyTo | Gets or sets EmailAddressCollection object specifying e-mail addresses to which the replies to this message should be sent.
Public property | RequestEncoding | Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the server.
Public property | ResponseEncoding | Gets or sets the encoding used to convert a byte data received from the server into a string.
Public property | Site | Gets or sets the object to be used as a site for the component.
 | SmtpServers | Gets the SmtpServerCollection object containing the list of SMTP relay servers to be used for sending mail.
Public property | StopJobsOnError | Gets or sets if processing of the jobs must be stopped if an error occurs.
 | Subject | Gets or sets the subject of the message.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
 | To | Gets or sets EmailAddressCollection object specifying To: recipients of the message.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
Events
 | Name | Description
 | Connected | Occurs when the connection with the server is successfully established.
 | DataReceived | Occurs when data is received from the network.
 | DataSent | Occurs when data is sent to the network.
 | Disconnected | Occurs when the connection with the server gets closed.
Public event | Disposed | Occurs after the component was disposed.
 | ErrorOccurred | Occurs when the MailBeeException is thrown.
Public event | FinishingJob | Occurs when the component is about to finish a job of sending an individual e-mail message or a mail merge series.
 | HostResolved | Occurs when the SMTP server name is successully resolved into IP address(es).
 | LoggedIn | Occurs when the component successfully authenticates the user on the SMTP server and logs in the user account.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Smtp.Log.MemoryLog is true).
 | LowLevelDataReceived | Occurs when data is received from the connected socket.
 | LowLevelDataSent | Occurs when data is sent to the connected socket.
 | MergingMessage | Occurs when the component is about to merge the e-mail template with a single data table row.
 | MessageDataChunkSent | Occurs on progress of sending message source data to the SMTP server.
 | MessageDirectSendDone | Occurs in direct send mode when the component finished submitting the mail message to all SMTP MX servers of recipients domains.
 | MessageMXLookupDone | Occurs in direct send mode after the component finished DNS MX lookup of SMTP MX servers of recipients domains.
 | MessageNotSent | Occurs when the message was not sent due to an error.
 | MessageRecipientSubmitted | Occurs each time the next recipient in the mail message recipients list is accepted or refused by the SMTP server.
 | MessageSenderSubmitted | Occurs after the sender of the mail message was successfully submitted to the SMTP server.
 | MessageSent | Occurs after the message was successfully sent.
 | MessageSubmittedToPickupFolder | Occurs after the current message was saved to MailBee.NET Queue or IIS SMTP pickup folder.
 | MessageSubmittedToServer | Occurs each time the message is successfully submitted to the SMTP server.
 | SendingMessage | Occurs when the message is about to be sent.
 | SocketConnected | Occurs when the SMTP server accepts the connection attempt and opens the transmission channel between the remote host (SMTP server) and the client (MailBee).
 | SocketCreating | Occurs when MailBee needs a new socket object for establishing a connection with the SMTP server.
 | SubmittingMessageToPickupFolder | Occurs when the message is about to be saved into MailBee.NET Queue or IIS SMTP pickup folder.
 | TlsStarted | Occurs when the connection with the server becomes secure.
 | TransientErrorOccurred | Occurs on a transient SMTP error which can be ignored because at least one fail-over SMTP server hasn't been tried yet.
Top
Remarks
You can perform the following operations using this class:
  • Send messages to an SMTP server
  • Perform mail merge over database to easily create and send bulk mail
  • Send messages in direct send mode (using MX lookup) when no SMTP relay server is available
  • Specify multiple SMTP and DNS servers for increased reliability and speed of sending very large volumes of messages
  • Authenticate on an SMTP server using a number of methods (including secure authentication methods, OAuth2, and POP-before-SMTP)
  • Take advantage of ESMTP pipelining which dramatically speeds up sending messages to multiple recipients
  • Take advantage of ESMTP chunking which significantly speeds up sending large messages
  • Track message delivery using ESMTP Delivery Status Notifications
  • Send messages with a single line of code (using static methods)
  • Submit messages directly to MailBee.NET Queue or IIS SMTP pickup service
  • Send messages through TLS/SSL secure connection
  • Establish connection via a proxy server (SOCKS4, SOCKS5, and HTTP proxy are supported)
  • Perform DNS MX, TXT, and reverse DNS queries
Also, DomainKeys object uses Smtp object to perform DNS TXT queries for verification of DomainKeys signatures of e-mails.
Note Note
Database-related functionality (such as mail merge over database) is not available in .NET Core and UWP.
Examples
This sample sends plain-text message to the SMTP server. We also disable ESMTP CHUNKING here (it improves sending performance but some servers support it incorrectly, so you may try both methods, with CHUNKING on and off).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class).

Smtp mailer = new Smtp();

// Set the message fields.
mailer.From.AsString = "John Doe <jdoe@domain1.com>";
mailer.To.AsString = "Bill Smith <b.smith@domain2.com>";
mailer.Subject = "Weekly newsletter";
mailer.BodyPlainText = "This is the newsletter contents";

// Specify the server to use. If your server does not require authentication,
// just remove last 2 parameters.
mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret");

// Disable ESMTP CHUNKING even if the server claims CHUNKING is supported
// (often helps with MS Exchange servers).
mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

// Send the message.
mailer.Send();

Console.WriteLine("The message was successfully submitted to the server.");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class).

Dim mailer As New Smtp

' Set the message fields.
mailer.From.AsString = "John Doe <jdoe@domain1.com>"
mailer.To.AsString = "Bill Smith <b.smith@domain2.com>"
mailer.Subject = "Weekly newsletter"
mailer.BodyPlainText = "This is the newsletter contents"

' Specify the server to use. If your server does not require authentication,
' just remove last 2 parameters.
mailer.SmtpServers.Add("smtp.domain1.com", "jdoe", "secret")

' Disable ESMTP CHUNKING even if the server claims CHUNKING is supported
' (often helps with MS Exchange servers).
mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

' Send the message.
mailer.Send()

Console.WriteLine("The message was successfully submitted to the server.")
See Also

Reference

MailBee.SmtpMail Namespace


Smtp Constructor

Smtp Constructor
Creates an instance of Smtp class.
Overload List
 | Name | Description
Public method | Smtp | Creates an instance of Smtp class.
Public method | Smtp(String) | Creates and unlocks an instance of Smtp class.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp Constructor

Smtp Constructor
Creates an instance of Smtp class.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Smtp()
Public Sub New
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET SMTP not licensed.
Remarks
This overload requires the license key be already set (such as with MailBee.Global.LicenseKey property, app.config, web.config, or in Windows registry).
See Also

Reference

Smtp Class
Smtp Overload
MailBee.SmtpMail Namespace


Smtp Constructor (String)

Smtp Constructor (String)
Creates and unlocks an instance of Smtp class.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Smtp(
    string licenseKey
)
Public Sub New (
    licenseKey As String
)

Parameters

licenseKey
Type: SystemString
The license key. Can be a null reference (Nothing in Visual Basic) in case if the product is already unlocked (the license key was specified in app.config, web.config, Windows registry, or in MailBee.Global.LicenseKey property).
Exceptions
Exception | Condition
MailBeeLicenseException | MailBee.NET SMTP not licensed and the supplied license key is invalid.
See Also

Reference

Smtp Class
Smtp Overload
MailBee.SmtpMail Namespace


Smtp Methods

Smtp Methods

The Smtp type exposes the following members.

Methods
 | Name | Description
Public method | Abort | Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.
 | AddAttachment | Reads the specified file from disk and adds it as attachment to the message.
Public method | AddAttachmentAsync | async/await version of AddAttachment(String).
 | AddJob(String, String, EmailAddressCollection) | Puts an e-mail message onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, MailMessage, String, EmailAddressCollection) | Puts the specified e-mail message onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, DataTable) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, IDataReader) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, Boolean, String, EmailAddressCollection) | Puts the e-mail message stored in an .EML file onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, IDataReader, Boolean, Boolean) | Puts a "mail merge over data reader" job onto waiting list for subsequent processing in bulk mode.
 | AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
 | AuthPopBeforeSmtp | Authenticates the user on a mail server using POP-before-SMTP authentication.
Public method | AuthPopBeforeSmtpAsync | async/await version of AuthPopBeforeSmtp(String, Int32, String, String).
 | BeginAuthPopBeforeSmtp | Obsolete. Begins an asynchronous request for a POP-before-SMTP authentication on a mail server.
 | BeginConnect | Obsolete. Begins an asynchronous request for connecting to an SMTP server.
Public method | BeginDisconnect | Obsolete. Begins an asynchronous request for a disconnection from the server.
 | BeginExecuteCustomCommand | Obsolete. Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.
 | BeginHello | Obsolete. Begins an asynchronous request for sending initial greeting to the SMTP server.
 | BeginLogin | Obsolete. Begins an asynchronous request for authenticating the user on the SMTP server.
 | BeginRelayFromEmlFile | Obsolete. Begins an asynchronous request for relaying a mail message to recipients.
 | BeginSend | Obsolete. Begins an asynchronous request for sending a mail message to recipients.
 | BeginSendJobs | Obsolete. Begins an asynchronous request to process the pending jobs and send out the resulting e-mails.
 | BeginStartTls | Obsolete. Begins an asynchronous request to start TLS/SSL negotiation with the server.
 | Connect | Connects to an SMTP server.
Public method | ConnectAsync | async/await version of Connect.
Public method | Disconnect | Disconnects from the SMTP server and releases any used resources.
Public method | DisconnectAsync | async/await version of Disconnect.
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Public method | EndAuthPopBeforeSmtp | Ends the pending asynchronous request for POP-before-SMTP authentication on a mail server.
Public method | EndConnect | Ends the pending asynchronous request for connecting to the SMTP server.
Public method | EndDisconnect | Ends a pending asynchronous disconnection request.
Public method | EndExecuteCustomCommand | Ends the pending asynchronous request for sending user-defined command to the server.
Public method | EndHello | Ends the pending asynchronous request for sending a greeting to the SMTP server.
Public method | EndLogin | Ends the pending asynchronous request for authenticating the user on the SMTP server.
Public method | EndRelayFromEmlFile | Ends the pending asynchronous request for relaying the message to the recipients.
Public method | EndSend | Ends the pending asynchronous request for sending the message to the recipients.
Public method | EndSendJobs | Ends the pending asynchronous request for processing the pending jobs and sending out the resulting e-mails.
Public method | EndStartTls | Ends a pending asynchronous TLS/SSL negotiation request.
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
 | ExecuteCustomCommand | Sends user-defined command to the server and receives the server response to this command.
Public method | ExecuteCustomCommandAsync | async/await version of ExecuteCustomCommand(String).
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetAcceptedRecipients | Returns the list of the recipients accepted by the SMTP server.
Public method | GetCurrentSmtpServerIndex | Returns SmtpServers collection's index of the server to which the component is connected or will connect on the next connection attempt.
Public method | GetErrorDescription | Returns a textual description of the last error.
 | GetExtension | Returns the name or parameters of the specified ESMTP capability.
 | GetExtensions | Returns a reference to the key-value list of the server capabilities.
Public method | GetExtensionValue | Returns the parameters of the specified ESMTP capability, or an empty string if the capability has no parameters.
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetMaxMessageSize | Returns the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.
 | GetMXHosts | Retrieves the list of hosts willing to accept mail for the given domain.
Public method | GetMXHostsAsync | async/await version of GetMXHosts(String).
 | GetPtrData | Retrieves the list of domain names for the specified IP address.
Public method | GetPtrDataAsync | async/await version of GetPtrData(String).
Public method | GetRefusedRecipients | Returns the list of the recipients rejected by the SMTP server.
Public method | GetServerResponse | Returns the last response from the server.
Public method | GetServerResponseCode | Returns an integer value containing the status code of the last SMTP operation.
Public method | GetSocket | Returns the underlying Socket MailBee uses for the current SMTP connection.
Public method | GetSocketError | Returns a Win32 error code of the last socket-related error.
Public method | GetStream | Returns the underlying Stream MailBee uses for the current network connection.
 | GetSupportedAuthMethods | Returns a set of flags indicating which authentication methods are supported by the server.
 | GetTxtData | Retrieves the list of TXT strings of DNS data of the specified domain.
Public method | GetTxtDataAsync | async/await version of GetTxtData(String).
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
 | Hello | Sends initial greeting to the SMTP server.
Public method | HelloAsync | async/await version of Hello.
 | Login | Authenticates the user on the SMTP server if ESMTP authentication is enabled.
Public method | LoginAsync | async/await version of Login.
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | Noop | Sends a NOOP command to the server.
Public method | NoopAsync | async/await version of Noop.
Protected method | OnConnected | Used by MailBee to raise Connected event.
Protected method | OnDataReceived | Used by MailBee to raise DataReceived event.
Protected method | OnDataSent | Used by MailBee to raise DataSent event.
Protected method | OnDisconnected | Used by MailBee to raise Disconnected event.
Protected method | OnErrorOccurred | Used by MailBee to raise ErrorOccurred event.
Protected method | OnFinishingJob | Used by MailBee to raise FinishingJob event.
Protected method | OnHostResolved | Used by MailBee to raise HostResolved event.
Protected method | OnLoggedIn | Used by MailBee to raise LoggedIn event.
Protected method | OnLogNewEntry | Used by MailBee to raise LogNewEntry event.
Protected method | OnLowLevelDataReceived | Used by MailBee to raise LowLevelDataReceived event.
Protected method | OnLowLevelDataSent | Used by MailBee to raise LowLevelDataSent event.
Protected method | OnMergingMessage | Used by MailBee to raise MergingMessage event.
Protected method | OnMessageDataChunkSent | Used by MailBee to raise MessageDataChunkSent event.
Protected method | OnMessageDirectSendDone | Used by MailBee to raise MessageDirectSendDone event.
Protected method | OnMessageMXLookupDone | Used by MailBee to raise MessageMXLookupDone event.
Protected method | OnMessageNotSent | Used by MailBee to raise MessageNotSent event.
Protected method | OnMessageRecipientSubmitted | Used by MailBee to raise MessageRecipientSubmitted event.
Protected method | OnMessageSenderSubmitted | Used by MailBee to raise MessageSenderSubmitted event.
Protected method | OnMessageSent | Used by MailBee to raise MessageSent event.
Protected method | OnMessageSubmittedToPickupFolder | Used by MailBee to raise MessageSubmittedToPickupFolder event.
Protected method | OnMessageSubmittedToServer | Used by MailBee to raise MessageSubmittedToServer event.
Protected method | OnSendingMessage | Used by MailBee to raise SendingMessage event.
Protected method | OnSocketConnected | Used by MailBee to raise SocketConnected event.
Protected method | OnSocketCreating | Used by MailBee to raise SocketCreating event.
Protected method | OnSubmittingMessageToPickupFolder | Used by MailBee to raise SubmittingMessageToPickupFolder event.
Protected method | OnTlsStarted | Used by MailBee to raise TlsStarted event.
Protected method | OnTransientErrorOccurred | Used by MailBee to raise TransientErrorOccurred event.
 | QuickSend(MailMessage) | Sends a mail message, in a single line of code.
 | QuickSend(String, String, String, String) | Sends a mail message, in a single line of code.
 | QuickSend(String, String, String, String, String, String, String) | Sends a mail message, in a single line of code.
 | RelayFromEmlFile(String, String, EmailAddressCollection) | Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.
 | RelayFromEmlFile(String, String, String) | Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.
Public method | RelayFromEmlFileAsync(String, String, EmailAddressCollection) | async/await version of RelayFromEmlFile(String, String, EmailAddressCollection).
Public method | RelayFromEmlFileAsync(String, String, String) | async/await version of RelayFromEmlFile(String, String, String).
Public method | ResetMessage | Resets all properties of Message object to defaults. Delivery Status Notification settings (DeliveryNotification object) are also reset.
Public method | ResetState | Resets the internal state of the component.
 | RetryFailedJobs | Puts all failed send-mail jobs back into the queue.
 | Send | Sends the mail message to the recipients specified in the message.
 | Send(String, EmailAddressCollection) | Sends the mail message to the specified recipients.
 | Send(String, String) | Sends the mail message to the specified recipients e-mail addresses.
Public method | SendAsync | async/await version of Send.
Public method | SendAsync(String, EmailAddressCollection) | async/await version of Send(String, EmailAddressCollection).
Public method | SendAsync(String, String) | async/await version of Send(String, String).
 | SendJobs | Sends out all e-mails in the pending jobs queue (including e-mails generated via mail merge).
Public method | SendJobsAsync | async/await version of SendJobs.
 | SendMailMerge(String, EmailAddressCollection, DataTable) | Creates a series of e-mails based on an e-mail message template and a data table and sends these e-mails out.
 | SendMailMerge(String, EmailAddressCollection, IDataReader) | Creates a series of e-mails based on an e-mail message template and a data reader and sends these e-mails out.
Public method | SendMailMergeAsync(String, EmailAddressCollection, DataTable) | async/await version of SendMailMerge(String, EmailAddressCollection, DataTable).
Public method | SendMailMergeAsync(String, EmailAddressCollection, IDataReader) | async/await version of SendMailMerge(String, EmailAddressCollection, IDataReader).
 | StartTls | Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.
Public method | StartTlsAsync | async/await version of StartTls.
 | StopJobs | Notifies MailBee to stop processing jobs, completing sending out of all messages currently being processed.
 | SubmitJobsToPickupFolder | Saves all e-mails in the pending jobs queue (including e-mails generated via mail merge) as files in the pickup folder of MailBee.NET Queue or IIS SMTP service.
Public method | SubmitJobsToPickupFolderAsync | async/await version of SubmitJobsToPickupFolder(String, Boolean).
 | SubmitToPickupFolder(String, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
 | SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
 | SubmitToPickupFolder(String, String, String, String, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
Public method | SubmitToPickupFolderAsync(String, Boolean) | async/await version of SubmitToPickupFolder(String, Boolean).
Public method | SubmitToPickupFolderAsync(String, String, String, EmailAddressCollection, Boolean) | async/await version of SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean).
Public method | SubmitToPickupFolderAsync(String, String, String, String, Boolean) | async/await version of SubmitToPickupFolder(String, String, String, String, Boolean).
 | TestSend | Tests sending a mail message to the recipients without actual submitting of the message data.
Public method | TestSendAsync | async/await version of TestSend(SendFailureThreshold).
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
 | ValidateEmailAddressSyntax | Verifies if the specified string is a correctly formatted e-mail address.
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Abort Method

SmtpAbort Method
Forces MailBee to cancel all pending operations and close all opened connections as soon as possible.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Abort()
Public Sub Abort
Remarks

A method which was in progress when Abort method has been called will throw MailBeeUserAbortException (unless ThrowExceptions is not false). If the component was not doing any work at the moment (IsBusy was false), the connection is aborted but no exception is thrown.

This method tries to abort the current network operation immediately, which works for all cases except of resolving a domain name into IP address. Due to .NET framework limitations, this operation cannot be aborted. Thus, sometimes you may experience a several seconds delay between calling this method and getting MailBeeUserAbortException (the time needed for DNS resolve to complete).

Note Note
No events will be raised after this method has been called.
To restore the component from the aborted state, the developer can use ResetState method.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpIsAborted
SmtpResetState


Smtp.AddAttachment Method

SmtpAddAttachment Method
Reads the specified file from disk and adds it as attachment to the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AddAttachment(
    string filename
)
Public Function AddAttachment (
    filename As String
) As Boolean

Parameters

filename
Type: SystemString
The full path and filename of the file to be attached.

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Smtp.AddAttachment method is equivalent to Smtp.Message.Attachments.Add method (see Add(String)).

The developer can use overloads of Add(Attachment) method to add attachments in an advanced way (memory or stream attachments, attachments of a specific type, etc).

Note Note
If you send multiple messages reusing the same Message object, be sure to clear Attachments collection of Message object by calling Clear method after each send. Otherwise, the attachments added to the collection during send operation will still remain in the collection when new attachments are added for the next send operation.
Examples
Adding an attachment to the message using Smtp.AddAttachment and Smtp.Message.Attachments.Add methods.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Add attachment under real name.
mailer.AddAttachment(@"C:\My Documents\Report.xls");

// Add B4DVIS9H.TMP file as "Annual report.doc".
mailer.Message.Attachments.Add(@"C:\DataFiles\B4DVIS9H.TMP", "Annual report.doc");
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Add attachment under real name.
mailer.AddAttachment("C:\My Documents\Report.xls")

' Add B4DVIS9H.TMP file as "Annual report.doc".
mailer.Message.Attachments.Add("C:\DataFiles\B4DVIS9H.TMP", "Annual report.doc")
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.AddAttachmentAsync Method

SmtpAddAttachmentAsync Method
async/await version of AddAttachment(String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> AddAttachmentAsync(
    string filename
)
Public Function AddAttachmentAsync (
    filename As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The full path and filename of the file to be attached.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.AddJob Method

SmtpAddJob Method
Puts an e-mail message or a mail merge job onto waiting list for subsequent processing in bulk mode.
Overload List
Name | Description
AddJob(String, String, EmailAddressCollection) | Puts an e-mail message onto waiting list for subsequent processing in bulk mode.
AddJob(String, MailMessage, String, EmailAddressCollection) | Puts the specified e-mail message onto waiting list for subsequent processing in bulk mode.
AddJob(String, String, EmailAddressCollection, DataTable) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
AddJob(String, String, EmailAddressCollection, IDataReader) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
AddJob(String, String, Boolean, String, EmailAddressCollection) | Puts the e-mail message stored in an .EML file onto waiting list for subsequent processing in bulk mode.
AddJob(String, String, EmailAddressCollection, IDataReader, Boolean, Boolean) | Puts a "mail merge over data reader" job onto waiting list for subsequent processing in bulk mode.
AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) | Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.AddJob Method (String, String, EmailAddressCollection)

SmtpAddJob Method (String, String, EmailAddressCollection)
Puts an e-mail message onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    string senderEmail,
    EmailAddressCollection recipients
)
Public Sub AddJob (
    tag As String,
    senderEmail As String,
    recipients As EmailAddressCollection
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
Remarks

This method can be used to send out large volumes of messages (in conjunction with SendJobs method). The given overload composes a single e-mail message from the current values of Message and DeliveryNotification objects and then adds it as a job waiting for processing into JobsPending queue. Then, once SendJobs method has been called, MailBee starts processing all the jobs in this queue and sending out all the accompanied e-mails.

Alternatively, if SubmitJobsToPickupFolder(String, Boolean) has been called instead of SendJobs, the pending e-mails will be saved as .EML files in MailBee.NET Queue or IIS pickup folder.

To destroy finished jobs instead of placing them in JobsSuccessful or JobsFailed collections, subscribe to FinishingJob event and set KeepIt to false. This is useful if you're sending a lot of e-mails and do not want to waste memory with e-mails which have already been processed.

Or, you can set KeepIt to false for failed messages only (so that you could try them again later with RetryFailedJobs method. FinishingJob event provides this information so that you can selectively decide whether you'll need the particular failed or successful message later or not.

Another AddJob(String, String, EmailAddressCollection, DataTable) overload can be used to enqueue a mail merge job of processing a bulk of similar messages based on a common template and a data table.

Note Note
You don't need to re-create or reset Message object (which actually contains the message to be added to the job list) after each call when you're preparing multiple messages. MailBee actually puts a copy of that Message object into the job list. Thus, you're a free to modify its properties again and it won't affect the copy which is already in the job list.
Examples
This sample adds two e-mails into the jobs queue and then sends them in a batch.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Because SendJobs does not throw exceptions during sending of
        // individual messages, logging is very useful for debugging.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Clear();

        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Compose the message #1.
        mailer.From.AsString = "John Doe <jdoe@domain.com>";
        mailer.To.AsString = "sales@company1.com, Bob <bob@company2.com>";
        mailer.Subject = "This is subject";
        mailer.BodyPlainText = "This is body text";

        // Put the message #1 into the queue. The message will actually be
        // sent from bounce@domain.com while jdoe@domain.com will appear
        // in "From:" header of the message.
        mailer.AddJob(null, "bounce@domain.com", null);

        // Compose the message #2.
        mailer.From.AsString = "John Doe <jdoe@domain.com>";
        mailer.To.AsString = "peter@company.com";
        mailer.Subject = "This is another subject";
        mailer.BodyPlainText = "This is another body text";

        // Put the message #2 into the queue.
        mailer.AddJob(null, null, null);

        // Send out the bulk of 2 messages.
        mailer.SendJobs();

        // Print the outcome.
        Console.WriteLine(mailer.JobsSuccessful.Count + " message(s) succeeded");
        Console.WriteLine(mailer.JobsFailed.Count + " message(s) failed");
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Because SendJobs does not throw exceptions during sending of
        ' individual messages, logging is very useful for debugging.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Clear()

        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Compose the message #1.
        mailer.From.AsString = "John Doe <jdoe@domain.com>"
        mailer.To.AsString = "sales@company1.com, Bob <bob@company2.com>"
        mailer.Subject = "This is subject"
        mailer.BodyPlainText = "This is body text"

        ' Put the message #1 into the queue. The message will actually be
        ' sent from bounce@domain.com while jdoe@domain.com will appear
        ' in "From:" header of the message.
        mailer.AddJob(Nothing, "bounce@domain.com", Nothing)

        ' Compose the message #2.
        mailer.From.AsString = "John Doe <jdoe@domain.com>"
        mailer.To.AsString = "peter@company.com"
        mailer.Subject = "This is another subject"
        mailer.BodyPlainText = "This is another body text"

        ' Put the message #2 into the queue.
        mailer.AddJob(Nothing, Nothing, Nothing)

        ' Send out the bulk of 2 messages.
        mailer.SendJobs()

        ' Print the outcome.
        Console.WriteLine(mailer.JobsSuccessful.Count & " message(s) succeeded")
        Console.WriteLine(mailer.JobsFailed.Count & " message(s) failed")
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace
SmtpSendJobs
SmtpSubmitJobsToPickupFolder(String, Boolean)


Smtp.AddJob Method (String, MailMessage, String, EmailAddressCollection)

SmtpAddJob Method (String, MailMessage, String, EmailAddressCollection)
Puts the specified e-mail message onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    MailMessage msg,
    string senderEmail,
    EmailAddressCollection recipients
)
Public Sub AddJob (
    tag As String,
    msg As MailMessage,
    senderEmail As String,
    recipients As EmailAddressCollection
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
msg
Type: MailBee.MimeMailMessage
A reference to the mail message to be sent.
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
Remarks
This method is similar to AddJob(string, string, EmailAddressCollection) overload but it takes the mail message to be scheduled from msg parameter rather than from Message property.
Examples
The version of AddJob(string, string, EmailAddressCollection) sample which explicitly creates a MailMessage instance to add jobs from. This has no practical meaning in this sample but shows how this can be done if for some reason your app already has MailMessage objects to be sent and you don't want to set up a message directly through mailer.Message properties.
C#
VB
Copy
using System;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Because SendJobs does not throw exceptions during sending of
        // individual messages, logging is very useful for debugging.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Clear();

        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        MailMessage msg = new MailMessage();

        // Compose the message #1.
        msg.From.AsString = "John Doe <jdoe@domain.com>";
        msg.To.AsString = "sales@company1.com, Bob <bob@company2.com>";
        msg.Subject = "This is subject";
        msg.BodyPlainText = "This is body text";

        // Put the message #1 into the queue. The message will actually be
        // sent from bounce@domain.com while jdoe@domain.com will appear
        // in "From:" header of the message.
        mailer.AddJob(null, msg, "bounce@domain.com", null);

        // Note that we do re-recreate a MailMessage object. This overload of AddJob actually places
        // msg itself into the job list, not its copy. For AddJob(string, string, EmailAddressCollection)
        // overload, that would be different (it makes a snapshot of what's currently in mailer.Message
        // and puts a copy of mailer.Message object into the job list, not mailer.Message object itself).
        msg = new MailMessage();

        // Compose the message #2.
        msg.From.AsString = "John Doe <jdoe@domain.com>";
        msg.To.AsString = "peter@company.com";
        msg.Subject = "This is another subject";
        msg.BodyPlainText = "This is another body text";

        // Put the message #2 into the queue.
        mailer.AddJob(null, msg, null, null);

        // Send out the bulk of 2 messages.
        mailer.SendJobs();

        // Print the outcome.
        Console.WriteLine(mailer.JobsSuccessful.Count + " message(s) succeeded");
        Console.WriteLine(mailer.JobsFailed.Count + " message(s) failed");
    }
}
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp()

        ' Because SendJobs does not throw exceptions during sending of
        ' individual messages, logging is very useful for debugging.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Clear()

        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        Dim msg As New MailMessage()

        ' Compose the message #1.
        msg.From.AsString = "John Doe <jdoe@domain.com>"
        msg.To.AsString = "sales@company1.com, Bob <bob@company2.com>"
        msg.Subject = "This is subject"
        msg.BodyPlainText = "This is body text"

        ' Put the message #1 into the queue. The message will actually be
        ' sent from bounce@domain.com while jdoe@domain.com will appear
        ' in "From:" header of the message.
        mailer.AddJob(Nothing, msg, "bounce@domain.com", Nothing)

        ' Note that we do re-recreate a MailMessage object. This overload of AddJob actually places
        ' msg itself into the job list, not its copy. For AddJob(string, string, EmailAddressCollection)
        ' overload, that would be different (it makes a snapshot of what's currently in mailer.Message
        ' and puts a copy of mailer.Message object into the job list, not mailer.Message object itself).
        msg = New MailMessage()

        ' Compose the message #2.
        msg.From.AsString = "John Doe <jdoe@domain.com>"
        msg.[To].AsString = "peter@company.com"
        msg.Subject = "This is another subject"
        msg.BodyPlainText = "This is another body text"

        ' Put the message #2 into the queue.
        mailer.AddJob(Nothing, msg, Nothing, Nothing)

        ' Send out the bulk of 2 messages.
        mailer.SendJobs()

        ' Print the outcome.
        Console.WriteLine(mailer.JobsSuccessful.Count & " message(s) succeeded")
        Console.WriteLine(mailer.JobsFailed.Count & " message(s) failed")
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace


Smtp.AddJob Method (String, String, EmailAddressCollection, DataTable)

SmtpAddJob Method (String, String, EmailAddressCollection, DataTable)
Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    DataTable mergeTable
)
Public Sub AddJob (
    tag As String,
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeTable As DataTable
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The e-mail address template of the recipients list. If it's a null reference (Nothing in Visual Basic), the recipients list will be constructed via merge of To, Cc, and Bcc patterns with actual values from the data source.
mergeTable
Type: System.DataDataTable
The data source for mail merge.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | mergeTable is a null reference (Nothing in Visual Basic).
Remarks

This method allows the application to schedule mail merge over database for subsequent processing with SendJobs, BeginSendJobs(AsyncCallback, Object), or SubmitJobsToPickupFolder(String, Boolean) method.

Note Note
To perform mail merge immediately rather than schedule it, use SendMailMerge(String, EmailAddressCollection, DataTable) method.
Note Note
This method is not available in .NET Core and UWP editions.

The mail merge requirements:

  • The template of e-mail to be merged with mergeTable data must be specified in Message property. Normally, Message property specifies the e-mail message to be sent out by Smtp object. In the case of mail merge, this e-mail message is considered as a template where ##Column_Name## patterns will be replaced with the actual data from database table rows during the mail merge process.
  • Smtp.DeliveryNotification.TrackingID may also contain a pattern if desired. Thus, it's possible to automatically assign unique tracking ID to the each message sent during mail merge and then receive this ID with bounced messages.
  • mergeTable must be the data source containing all the data rows for which e-mails should be generated and sent; typically, this data source is a result of SQL query.
  • Names of columns of mergeTable must match pattern names in the e-mail template. For instance, if there is Email column in the data table and the developer wishes to make values from this column appear in resulting e-mails, then the e-mail template must contain ##Email## string in the places where the e-mail address needs to be placed. Patterns are case-sensitive! For instance, if data table column name is Email, only ##Email## pattern will be replaced with the column value. ##email## and ##EMAIL## patterns will be left intact.
  • senderEmailPattern can be left null. However, if resulting e-mails should actually be sent from another e-mail address (for instance, resulting e-mails have newsletter@domain.com in "From:" field while you wish to send them from "bounces@domain.com"), then it's required to specify senderEmailPattern. It can contain a pattern (e.g. ##Something##) or refer to the actual value (e.g. from@company.com).
  • recipientsPattern have the same meaning for specifying the actual recipients as senderEmailPattern - for the actual sender. For instance, to set the pattern which will take the 1st recipient's e-mail address from Email field of the data table while the 2nd recipient's email address is hard-coded, pass the following as recipientsPattern value: new EmailAddressCollection("##Email##, archive-copy@company.com").
  • Setting tag to non-empty value helps to distinguish the current mail merge from other jobs if there are any. This is useful if the application submits and processes multiple jobs and the developer wants to track processing of each job separately. Jobs tags also appear in the log if logging is enabled.

Calling this overload is equivalent to calling AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) with mergeRowIndices set to null, keepProducedJobs set to true, and keepMergedData set to false.

Examples
This console sample sends out 2 newsletters based on the same database table and different e-mail templates. Both newsletters are sent out from the same sender to the same recipients. The first newsletter is more complex and may contain attachments. The second newsletter is simpler.
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Occurs when an e-mail message is ready to be sent.
    static void mailer_SendingMessage(object sender, SmtpSendingMessageEventArgs e)
    {
        // Display e-mail address of the e-mail to be sent.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " of '" + e.Tag + "'");

        // You can also subscribe to events like MergingMessage, MessageSent, MessageNotSent
        // to keep the detailed track of mail merge progress.
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to event to track send bulk mail progress.
        mailer.SendingMessage += new SmtpSendingMessageEventHandler(mailer_SendingMessage);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our newsletter";

        // Setup DSN template for mail merge. In particular, this can be useful
        // to track bounced messages which may come back from some addresses after
        // sending bulk mail out. If the SMTP server does not support DSN, this
        // setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "##ID##-N";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Setup template for adding file attachments upon the specified path.
        // In this sample, the path to attachment files will be constructed as
        // "C:\" + DatabaseRecordField("Doc_path").
        mailer.Message.Merge.AddAttachmentPattern(@"C:\##Doc_path##");

        // Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8";

        // Tell MailBee to generate alternative plain-text version
        // of each e-mail automatically.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfHtml;

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        DataTable table = new DataTable();

        // Connect to the database and populate mail merge job to-do list with
        // the data from "mailing_list" table.
        using (OleDbConnection conn = new OleDbConnection(connParams))
        {
            // Open the connection and get the data.
            OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = command;
            adapter.Fill(table);

            // Create a job which is the following task for MailBee: perform mail merge
            // of a newsletter template with data rows of the specified data table and
            // send out each resulting e-mail to its intended recipients.
            mailer.AddJob("Newsletter #1", null, null, table);

            // Change template parameters for another newsletter.
            mailer.Message.Subject = "Newsletter update";

            // Setup DSN template for mail merge. In particular, this can be useful
            // to track bounced messages which may come back from some addresses after
            // sending bulk mail out. If the SMTP server does not support DSN, this
            // setting will be ignored.
            mailer.DeliveryNotification.TrackingID = "##ID##-NU";

            // Setup HTML body template.
            mailer.Message.BodyHtmlText = "<html>Please disregard the newsletter you just received.</html>";

            // If we do not want attachments in second newsletter, remove the pattern.
            mailer.Message.Merge.ClearAttachmentPatterns();

            // Create a job of sending another newsletter to the same recipients.
            mailer.AddJob("Newsletter #2", null, null, table);
        }

        // Run the jobs. The actual mail merge takes place here.
        mailer.SendJobs();
        Console.WriteLine();

        // Report results (row indices in the data table) to the console.
        if (mailer.JobsFailed.Count == 0)
        {
            Console.WriteLine("Both newsletters have been sent out without any errors.");
        }
        else
        {
            if (mailer.JobsSuccessful.Count == 0)
            {
                Console.WriteLine("All newsletter e-mails failed to be sent.");
            }
            else
            {
                Console.WriteLine("Not all newsletter e-mails have been sent.");
                Console.WriteLine();

                Console.WriteLine("Successful rows (Our newsletter): ");
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, "Newsletter #1"));
                Console.WriteLine();

                Console.WriteLine("Failed rows (Our newsletter): ");
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, "Newsletter #1"));
                Console.WriteLine();

                Console.WriteLine("Successful rows (Newsletter update): ");
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, "Newsletter #2"));
                Console.WriteLine();

                Console.WriteLine("Failed rows (Newsletter update): ");
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, "Newsletter #2"));
            }
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Occurs when an e-mail message is ready to be sent.
    Shared Sub mailer_SendingMessage(ByVal sender As Object, ByVal e As SmtpSendingMessageEventArgs)
        ' Display e-mail address of the e-mail to be sent.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " of '" & e.Tag & "'")

        ' You can also subscribe to events like MergingMessage, MessageSent, MessageNotSent
        ' to keep the detailed track of mail merge progress.
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to event to track send bulk mail progress.
        AddHandler mailer.SendingMessage, AddressOf mailer_SendingMessage

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our newsletter"

        ' Setup DSN template for mail merge. In particular, this can be useful
        ' to track bounced messages which may come back from some addresses after
        ' sending bulk mail out. If the SMTP server does not support DSN, this
        ' setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "##ID##-N"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Setup template for adding file attachments upon the specified path.
        ' In this sample, the path to attachment files will be constructed as
        ' "C:\" + DatabaseRecordField("Doc_path").
        mailer.Message.Merge.AddAttachmentPattern("C:\##Doc_path##")

        ' Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8"

        ' Tell MailBee to generate alternative plain-text version
        ' of each e-mail automatically.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfHtml

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        Dim table As DataTable = New DataTable

        ' Connect to the database and populate mail merge job to-do list with
        ' the data from "mailing_list" table.
        Dim conn As OleDbConnection
        Try
            conn = New OleDbConnection(connParams)
            ' Open the connection and get the data.
            Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
            conn.Open()
            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
            adapter.SelectCommand = command
            adapter.Fill(table)

            ' Create a job which is the following task for MailBee: perform mail merge
            ' of a newsletter template with data rows of the specified data table and
            ' send out each resulting e-mail to its intended recipients.
            mailer.AddJob("Newsletter #1", Nothing, Nothing, table)

            ' Change template parameters for another newsletter.
            mailer.Message.Subject = "Newsletter update"

            ' Setup DSN template for mail merge. In particular, this can be useful
            ' to track bounced messages which may come back from some addresses after
            ' sending bulk mail out. If the SMTP server does not support DSN, this
            ' setting will be ignored.
            mailer.DeliveryNotification.TrackingID = "##ID##-NU"

            ' Setup HTML body template.
            mailer.Message.BodyHtmlText = "<html>Please disregard the newsletter you just received.</html>"

            ' If we do not want attachments in second newsletter, remove the pattern.
            mailer.Message.Merge.ClearAttachmentPatterns()

            ' Create a job of sending another newsletter to the same recipients.
            mailer.AddJob("Newsletter #2", Nothing, Nothing, table)

        Finally
            If Not conn Is Nothing Then
                conn.Close()
            End If
        End Try

        ' Run the jobs. The actual mail merge takes place here.
        mailer.SendJobs()
        Console.WriteLine()

        ' Report results (row indices in the data table) to the console.
        If mailer.JobsFailed.Count = 0 Then
            Console.WriteLine("Both newsletters have been sent out without any errors.")
        Else
            If mailer.JobsSuccessful.Count = 0 Then
                Console.WriteLine("All newsletter e-mails failed to be sent.")
            Else
                Console.WriteLine("Not all newsletter e-mails have been sent.")
                Console.WriteLine()

                Console.WriteLine("Successful rows (Our newsletter): ")
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, "Newsletter #1"))
                Console.WriteLine()

                Console.WriteLine("Failed rows (Our newsletter): ")
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, "Newsletter #1"))
                Console.WriteLine()

                Console.WriteLine("Successful rows (Newsletter update): ")
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, "Newsletter #2"))
                Console.WriteLine()

                Console.WriteLine("Failed rows (Newsletter update): ")
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, "Newsletter #2"))
            End If
        End If
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace
SmtpRetryFailedJobs
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


Smtp.AddJob Method (String, String, EmailAddressCollection, IDataReader)

SmtpAddJob Method (String, String, EmailAddressCollection, IDataReader)
Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    IDataReader mergeDataReader
)
Public Sub AddJob (
    tag As String,
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeDataReader As IDataReader
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The e-mail address template of the recipients list. If it's a null reference (Nothing in Visual Basic), the recipients list will be constructed via merge of To, Cc, and Bcc patterns with actual values from the data source.
mergeDataReader
Type: System.DataIDataReader
The data source for mail merge, such as SqlDataReader.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | mergeDataReader is a null reference (Nothing in Visual Basic).
Remarks
This overload is similar to AddJob(String, String, EmailAddressCollection, DataTable).
Note Note
This method is not available in .NET Core and UWP editions.
Examples
C#
VB
Copy
using System;
using System.Data;
using System.Data.SqlClient;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports successful attempt of sending e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        // We assume field #0 is ID, field #1 is Email, etc.
        string email = e.MergeDataReaderRowValues[1].ToString();
        Console.WriteLine(string.Format("{0} SUCCEEDED", email));
    }

    // Reports failed attempt of sending e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        // We assume field #0 is ID, field #1 is Email, etc.
        string email = e.MergeDataReaderRowValues[1].ToString();
        Console.WriteLine(string.Format("{0} FAILED", email));
    }

    static void Main(string[] args)
    {
        // By the way, you can pass the license key directly in the constructor.
        Smtp mailer = new Smtp("MN100-0123456789ABCDEF-0123");

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60) and increase performance.
        // Note that not all SMTP servers will support so many incoming connections (each thread creates its own).

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our Oct/2013 newsletter";

        // Setup DSN template for mail merge. In particular, this can be useful
        // to track bounced messages which may come back from some addresses after
        // sending bulk mail out. If the SMTP server does not support DSN, this
        // setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "Oct2013_##ID##";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "##HTML_body##";

        // For a change, setup plain-text body template. In other samples, we set HTML body only
        // and let MailBee create plain-text version.
        mailer.Message.BodyPlainText = "##Plain_body##";

        // Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8";

        // The app will take care of plain-text version. MailBee shouldn't do it.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.Never;

        // Specify database connection string (it may be different in your case).
        string connParams = @"server=(local)\SQLEXPRESS;Initial Catalog=afterlogic;Integrated Security=True";

        using (SqlConnection conn = new SqlConnection(connParams))
        {
            conn.Open();
            using (SqlCommand command = conn.CreateCommand())
            {
                // The 'newsletter' table or query must have these fields:
                // #0: ID (int)
                // #1: Email (nvarchar)
                // #2: Name (nvarchar)
                // #3: Plain_body (nvarchar)
                // #4; HTML_body (nvarchar)
                // Table row example: 15, "jdoe@domain.com", "John", "Some text", "<html>Some&nbsp;text</html>".
                command.CommandText = "SELECT * FROM newsletter";

                // Populate mail merge job to-do list with from the specified table.
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    // Submit the job to MailBee.
                    mailer.AddJob(null, null, null, reader);

                    // Run the job. The actual mail merge takes place here.
                    mailer.SendJobs();

                    Console.WriteLine();

                    // Report results (row indices in the data table) to the console.
                    if (mailer.JobsFailed.Count == 0)
                    {
                        Console.WriteLine(
                            "All of the rows of the table have been processed and sent as e-mails.");
                    }
                    else
                    {
                        if (mailer.JobsSuccessful.Count == 0)
                        {
                            Console.WriteLine(
                                "None of the rows of the table has been processed and sent as e-mail.");
                        }
                        else
                        {
                            Console.WriteLine(
                                "Not all rows of the table have been processed and sent as e-mails.");
                            Console.WriteLine();

                            Console.WriteLine("Successful rows count: " +
                                mailer.JobsSuccessful.Count.ToString());
                            Console.WriteLine();

                            Console.WriteLine("Failed rows count: " +
                                mailer.JobsFailed.Count.ToString());
                        }
                        Console.WriteLine();

                        mailer.JobsSuccessful.Clear();
                        mailer.JobsFailed.Clear();
                    }
                }
            }
        }
    }
}
Imports System.Data
Imports System.Data.SqlClient
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports successful attempt of sending e-mail.
    Private Shared Sub mailer_MessageSent(sender As Object, e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        ' We assume field #0 is ID, field #1 is Email, etc.
        Dim email As String = e.MergeDataReaderRowValues(1).ToString()
        Console.WriteLine(String.Format("{0} SUCCEEDED", email))
    End Sub

    ' Reports failed attempt of sending e-mail.
    Private Shared Sub mailer_MessageNotSent(sender As Object, e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        ' We assume field #0 is ID, field #1 is Email, etc.
        Dim email As String = e.MergeDataReaderRowValues(1).ToString()
        Console.WriteLine(String.Format("{0} FAILED", email))
    End Sub

    Shared Sub Main(args As String())
        ' By the way, you can pass the license key directly in the constructor.
        Dim mailer As New Smtp("MN100-0123456789ABCDEF-0123")

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60) and increase performance.
        ' Note that not all SMTP servers will support so many incoming connections (each thread creates its own).

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += New SmtpMessageSentEventHandler(AddressOf mailer_MessageSent)
        mailer.MessageNotSent += New SmtpMessageNotSentEventHandler(AddressOf mailer_MessageNotSent)

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.[To].AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our Oct/2013 newsletter"

        ' Setup DSN template for mail merge. In particular, this can be useful
        ' to track bounced messages which may come back from some addresses after
        ' sending bulk mail out. If the SMTP server does not support DSN, this
        ' setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "Oct2013_##ID##"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "##HTML_body##"

        ' For a change, setup plain-text body template. In other samples, we set HTML body only
        ' and let MailBee create plain-text version.
        mailer.Message.BodyPlainText = "##Plain_body##"

        ' Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8"

        ' The app will take care of plain-text version. MailBee shouldn't do it.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.Never

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "server=(local)\SQLEXPRESS;Initial Catalog=afterlogic;Integrated Security=True"

        Using conn As New SqlConnection(connParams)
            conn.Open()
            Using command As SqlCommand = conn.CreateCommand()
                ' The 'newsletter' table or query must have these fields:
                ' #0: ID (int)
                ' #1: Email (nvarchar)
                ' #2: Name (nvarchar)
                ' #3: Plain_body (nvarchar)
                ' #4; HTML_body (nvarchar)
                ' Table row example: 15, "jdoe@domain.com", "John", "Some text", "<html>Some&nbsp;text</html>".
                command.CommandText = "SELECT * FROM newsletter"

                ' Populate mail merge job to-do list with from the specified table.
                Using reader As SqlDataReader = command.ExecuteReader()
                    ' Submit the job to MailBee.
                    mailer.AddJob(Nothing, Nothing, Nothing, reader)

                    ' Run the job. The actual mail merge takes place here.
                    mailer.SendJobs()

                    Console.WriteLine()

                    ' Report results (row indices in the data table) to the console.
                    If mailer.JobsFailed.Count = 0 Then
                        Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.")
                    Else
                        If mailer.JobsSuccessful.Count = 0 Then
                            Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.")
                        Else
                            Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.")
                            Console.WriteLine()

                            Console.WriteLine("Successful rows count: " & mailer.JobsSuccessful.Count.ToString())
                            Console.WriteLine()

                            Console.WriteLine("Failed rows count: " & mailer.JobsFailed.Count.ToString())
                        End If
                        Console.WriteLine()

                        mailer.JobsSuccessful.Clear()
                        mailer.JobsFailed.Clear()
                    End If
                End Using
            End Using
        End Using
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace
SmtpRetryFailedJobs
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


Smtp.AddJob Method (String, String, Boolean, String, EmailAddressCollection)

SmtpAddJob Method (String, String, Boolean, String, EmailAddressCollection)
Puts the e-mail message stored in an .EML file onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    string msgFilename,
    bool preferXSenderXReceiver,
    string senderEmail,
    EmailAddressCollection recipients
)
Public Sub AddJob (
    tag As String,
    msgFilename As String,
    preferXSenderXReceiver As Boolean,
    senderEmail As String,
    recipients As EmailAddressCollection
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
msgFilename
Type: SystemString
The filename of the .EML file containing the e-mail message to be sent.
preferXSenderXReceiver
Type: SystemBoolean
Denotes if "X-Sender" and "X-Receiver" message headers have priority over any other method of specifying sender and recipients for this message. Has no effect if "X-Sender" and "X-Receiver" headers are not set in the message file.
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property. Ignored if preferXSenderXReceiver is true and the message includes "X-Sender" header.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists. Ignored if preferXSenderXReceiver is true and the message includes at least one "X-Receiver" header.
Remarks

This method is useful if you want to implement some kind of background mail queue. E-mails themselves can be created using other tools or with SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean) method. SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean) method can create .EML files with "X-Sender" and "X-Receiver" headers so that it's possible to implement scenarios when an e-mail needs to be sent from/to addresses different from its From/To/CC/BCC.

Note Note
This overload is different from AddJob(String, MailMessage, String, EmailAddressCollection) (it accepts MailMessage as a parameter) in the way it uses memory. The current overload (which takes just a filename of the e-mail message) does NOT internally call LoadMessage(String) to get the message in memory from the file and put it onto the waiting queue as a job. Instead, it loads the message into memory only when the job actually gets processed. Thus, if you added 100 e-mails as MailMessage objects, all 100 will consume memory before they start to get sent. However, if you added 100 e-mails as files, the job list will contain just 100 filenames, not actual messages. The messages will be loaded and processed one-by-one and memory usage will be substantially lower. Of course, if you're using multi-threaded processing jobs, multiple messages will be processed simultaneously (and thus occupy more memory) but you'll still have significant memory usage benefit if number of threads is less than the number of messages in the queue.

The note above does not apply to mail merge over database jobs. In that case, each e-mail is generated on the fly when it gets sent (not when the mail merge job is created). E-mails generated with mail merge over database do not occupy more memory than required in order to send out a single e-mail (or several e-mails in case of multi-threading).

Examples

This sample implements a very simple e-mail queue dispatcher which drops a couple of e-mail files in a folder first, and then sends out all e-mail files in a folder. E-mails are save to and then taken from "C:\Queue\Pickup" folder. For successful e-mails, .EML file is then removed, for failed e-mails - moved to "C:\Queue\Bad" folder.

Note Note
For a more advanced sample which can be used as a production level queue dispatcher, download MailBee.NET Queue from AfterLogic web site.
C#
VB
Copy
using System;
using System.IO;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports readiness to start sending an e-mail.
    static void mailer_SendingMessage(object sender, SmtpSendingMessageEventArgs e)
    {
        // Display e-mail address of the e-mail which is about to be sent.
        Console.WriteLine(e.MailMessage.Filename + " WILL BE SENT");
    }

    // Reports successful attempt of sending e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MailMessage.Filename + " SUCCEEDED");
        File.Delete(e.MailMessage.Filename);
    }

    // Reports failed attempt of sending e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MailMessage.Filename + " FAILED");
        File.Move(e.MailMessage.Filename, Path.Combine(BadFolder, Path.GetFileName(e.MailMessage.Filename)));
    }

    const string PickupFolder = @"C:\Queue\Pickup";
    const string BadFolder = @"C:\Queue\Bad";

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // For demo purposes, submit a couple of e-mails so that we would have something to send out.
        // Show diffenent cases. First message is a bit advanced, it has different From and "real From"
        // (which is usually used to send bounces to a special address). Second one is simpler.
        mailer.Message.From.AsString = "John Doe <jdoe@domain.com>";
        mailer.Message.To.AsString = "Alice <alice@server.com>";
        mailer.Message.Subject = "Subject #1";
        mailer.Message.BodyPlainText = "Text #1";
        mailer.SubmitToPickupFolder(PickupFolder, null, "bounce@domain.com", (string)null, false);

        mailer.Message.From.AsString = "John Doe <jdoe@domain.com>";
        mailer.Message.To.AsString = "Bob <bob@domain.com>, Bill Smith <bill@company.com>";
        mailer.Message.Subject = "Subject #2";
        mailer.Message.BodyPlainText = "Text #2";
        mailer.SubmitToPickupFolder(PickupFolder, false);

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support many incoming connections
        // from a single IP address (each worker thread may create its own connection).

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.SendingMessage += new SmtpSendingMessageEventHandler(mailer_SendingMessage);
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret");

        // Note that by default if a message is intended to multiple recipients
        // (message #2 in this sample) and at least one of them succeeds, the entire
        // message succeeds. To change this behavior, uncomment the line below.

        // mailer.SmtpServers[0].AllowRefusedRecipients = false;

        // Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
        // mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

        DirectoryInfo dirInfo = new DirectoryInfo(PickupFolder);
        FileInfo[] fileInfos = dirInfo.GetFiles("*.eml");
        foreach (FileInfo info in fileInfos)
        {
            // Remember the filename but don't actually load the message file at the moment.
            // If the message file overrides sender and recipients in From/To/CC/BCC by having X-Sender or
            // X-Receiver in the headers, honor this by setting preferXSenderXReceiver to true.
            mailer.AddJob(null, info.FullName, true, null, null);
        }

        // Dispatch the queue.
        mailer.SendJobs();
    }
}
Imports System.IO
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports readiness to start sending an e-mail.
    Private Shared Sub mailer_SendingMessage(ByVal sender As Object, ByVal e As SmtpSendingMessageEventArgs)
        ' Display e-mail address of the e-mail which is about to be sent.
        Console.WriteLine(Convert.ToString(e.MailMessage.Filename) & " WILL BE SENT")
    End Sub

    ' Reports successful attempt of sending e-mail.
    Private Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        Console.WriteLine(Convert.ToString(e.MailMessage.Filename) & " SUCCEEDED")
        File.Delete(e.MailMessage.Filename)
    End Sub

    ' Reports failed attempt of sending e-mail.
    Private Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        Console.WriteLine(Convert.ToString(e.MailMessage.Filename) & " FAILED")
        File.Move(e.MailMessage.Filename, Path.Combine(BadFolder, Path.GetFileName(e.MailMessage.Filename)))
    End Sub

    Const PickupFolder As String = "C:\Queue\Pickup"
    Const BadFolder As String = "C:\Queue\Bad"

    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp()

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' For demo purposes, submit a couple of e-mails so that we would have something to send out.
        ' Show diffenent cases. First message is a bit advanced, it has different From and "real From"
        ' (which is usually used to send bounces to a special address). Second one is simpler.
        mailer.Message.From.AsString = "John Doe <jdoe@domain.com>"
        mailer.Message.[To].AsString = "Alice <alice@server.com>"
        mailer.Message.Subject = "Subject #1"
        mailer.Message.BodyPlainText = "Text #1"
        mailer.SubmitToPickupFolder(PickupFolder, Nothing, "bounce@domain.com", _
         DirectCast(Nothing, String), False)

        mailer.Message.From.AsString = "John Doe <jdoe@domain.com>"
        mailer.Message.[To].AsString = "Bob <bob@domain.com>, Bill Smith <bill@company.com>"
        mailer.Message.Subject = "Subject #2"
        mailer.Message.BodyPlainText = "Text #2"
        mailer.SubmitToPickupFolder(PickupFolder, False)

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support many incoming connections
        ' from a single IP address (each worker thread may create its own connection).

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.SendingMessage, New SmtpSendingMessageEventHandler(AddressOf mailer_SendingMessage)
        AddHandler mailer.MessageSent, New SmtpMessageSentEventHandler(AddressOf mailer_MessageSent)
        AddHandler mailer.MessageNotSent, New SmtpMessageNotSentEventHandler(AddressOf mailer_MessageNotSent)

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret")

        ' Note that by default if a message is intended to multiple recipients
        ' (message #2 in this sample) and at least one of them succeeds, the entire
        ' message succeeds. To change this behavior, uncomment the line below.

        ' mailer.SmtpServers(0).AllowRefusedRecipients = false

        ' Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
        ' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

        Dim dirInfo As New DirectoryInfo(PickupFolder)
        Dim fileInfos As FileInfo() = dirInfo.GetFiles("*.eml")
        For Each info As FileInfo In fileInfos
            ' Remember the filename but don't actually load the message file at the moment.
            ' If the message file overrides sender and recipients in From/To/CC/BCC by having X-Sender or
            ' X-Receiver in the headers, honor this by setting preferXSenderXReceiver to true.
            mailer.AddJob(Nothing, info.FullName, True, Nothing, Nothing)
        Next

        ' Dispatch the queue.
        mailer.SendJobs()
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace


Smtp.AddJob Method (String, String, EmailAddressCollection, IDataReader, Boolean, Boolean)

SmtpAddJob Method (String, String, EmailAddressCollection, IDataReader, Boolean, Boolean)
Puts a "mail merge over data reader" job onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    IDataReader mergeDataReader,
    bool keepProducedJobs,
    bool keepMergedData
)
Public Sub AddJob (
    tag As String,
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeDataReader As IDataReader,
    keepProducedJobs As Boolean,
    keepMergedData As Boolean
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The e-mail address template of the recipients list. If it's a null reference (Nothing in Visual Basic), the recipients list will be constructed via merge of To, Cc, and Bcc patterns with actual values from the data source.
mergeDataReader
Type: System.DataIDataReader
The data source for mail merge.
keepProducedJobs
Type: SystemBoolean
Indicates whether MailBee should create separate SendMailJob object for every e-mail message produced during mail merge. If true, JobsSuccessful and JobsFailed collections will end up with the same number of jobs as the number of e-mail messages generated; otherwise, only SendMailJob object originally added by this method will end up in JobsSuccessful or JobsFailed collections.
keepMergedData
Type: SystemBoolean
Indicates whether MailBee should retain merged messages after they have been processed. If true, MailBee will not clear MergedXXX properties of SendMailJob object after the e-mail message associated with this object has been processed; otherwise, MailBee will clear memory occupied by the merged message so that MergedXXX properties start returning null once the message has been processed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | mergeDataReader is a null reference (Nothing in Visual Basic).
Remarks

This method is IDataReader version of AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) overload (which uses DataTable).

The specifics of IDataReader version is that there is no row indices to pass (the entire data reader is processed) because data readers don't have an index of a data row, they are not tables at all but rather sequential readers which can just move forward. Also, in multi-threaded scenario it's not possible to access the current row of the data reader in event handlers. See the sample code below on how to process only certain indices when dealing with IDataReader and how to overcome its multi-threading limitations.

Note Note
This method is not available in .NET Core and UWP editions.
Examples

This console sample is similar to the sample in AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) overload topic mentioned above, with specifics of using IDataReader in multi-threaded case. Also, the sample uses MS SQL Server database (SqlDataReader) rather than MS Access.

C#
VB
Copy
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    static ArrayList failedIds = new ArrayList();
    static int i = 0;

    // We use it to check if the data row with certain ID must be processed or not.
    static void mailer_MergingMessage(object sender, SmtpMergingMessageEventArgs e)
    {
        // If this is 2nd run (retrying failed indices) and the index is not in failed list, skip it.
        int rowID = (int)e.MergeDataReaderRowValues[0];
        if (i > 0 && failedIds.IndexOf(rowID) < 0)
        {
            e.MergeIt = false;
        }
    }

    // Reports successful attempt of sending e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        // Demonstrate getting column by name.
        string email = e.MergeDataReaderRowValues[Array.IndexOf(e.MergeDataReaderColumnNames, "Email")].ToString();
        Console.WriteLine(string.Format("{0} of '{1}' job SUCCEEDED", email, e.Tag));
    }

    // Reports failed attempt of sending e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        // Demonstrate getting column by index (we assume field #0 is ID, field #1 is Email, etc).
        string email = e.MergeDataReaderRowValues[1].ToString();
        Console.WriteLine(string.Format("{0} of '{1}' job FAILED", email, e.Tag));

        // On the first run, remember failed id so that we'd be able to retry them on second run.
        if (i == 0)
        {
            failedIds.Add(e.MergeDataReaderRowValues[0]);
        }
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60) and increase performance.
        // Note that not all SMTP servers will support so many incoming connections (each thread creates its own).

        // mailer.MaxThreadCount = -1;

        // Subscribe to the event which lets us implement retrying failed indices on 2nd run.
        mailer.MergingMessage += new SmtpMergingMessageEventHandler(mailer_MergingMessage);

        // Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our Oct/2013 newsletter";

        // Setup DSN template for mail merge. In particular, this can be useful
        // to track bounced messages which may come back from some addresses after
        // sending bulk mail out. If the SMTP server does not support DSN, this
        // setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "Oct2013_##ID##";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Setup template for adding file attachments upon the specified path.
        // In this sample, the path to attachment files will be constructed as
        // "C:\Temp\" + DatabaseRecordField("Doc_path").
        mailer.Message.Merge.AddAttachmentPattern(@"C:\Temp\##Doc_path##");

        // Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8";

        // Tell MailBee to generate alternative plain-text version
        // of each e-mail automatically.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfHtml;

        // Specify database connection string (it may be different in your case).
        string connParams = @"server=(local)\SQLEXPRESS;Initial Catalog=afterlogic;Integrated Security=True";

        // Connect to the database.
        SqlDataReader reader = null;
        SqlConnection conn = new SqlConnection(connParams);
        conn.Open();
        SqlCommand command = conn.CreateCommand();

        // The 'mailing_list' table must have these fields:
        // #0: ID (int)
        // #1: Email (nvarchar)
        // #2: Name (nvarchar)
        // #3: Body (nvarchar)
        // #4; Doc_path (nvarchar). Can be null if attachment not required. Files are taken from C:\Temp.
        // Table row example: 196, "jdoe@domain.com", "John", "Some text", "file.dat".
        command.CommandText = "SELECT * FROM mailing_list";

        // Make two runs of mail merge. If e-mails created from some data rows fail,
        // we'll attempt to resend them on the second run.
        for (i = 0; i < 2; i++)
        {
            // Populate mail merge job to-do list with from the specified table.
            reader = command.ExecuteReader();

            // Create a job which is the following task for MailBee: perform mail merge over
            // the specified data table and send out each resulting e-mail to
            // the recipients which appear in the resulting messages. "bounce@domain.com"
            // address will be used as Return-Path (i.e. sender e-mail address).
            //
            // keepProducedJobs is true to let us check mailer.JobsSuccessful.Count and
            // mailer.JobsFailed.Count at the end of the loop. In real apps, you can count successful
            // and failed sendings by incrementing variables in mailer_MessageSent or mailer_MessageNotSent
            // event handlers (this will save memory as produced jobs won't increase memory usage over time).
            // Just be sure to synchronize access to that counter variables (such as with lock or VB's SyncLock
            // statement if you're using multi-threading), unless you're in WinForms application which processes
            // events sequentially so that two event handlers could never execute simultaneously.
            mailer.AddJob("My", "bounce@domain.com", null, reader, true, false);

            // Run the job. The actual mail merge takes place here.
            mailer.SendJobs();

            reader.Close();
            reader = null;

            Console.WriteLine();

            // Report results (row indices in the data table) to the console.
            if (mailer.JobsFailed.Count == 0)
            {
                Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.");
                break;
            }
            else
            {
                if (mailer.JobsSuccessful.Count == 0)
                {
                    Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.");
                }
                else
                {
                    Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.");
                    Console.WriteLine();

                    Console.WriteLine("Successful rows count: " + mailer.JobsSuccessful.Count.ToString());
                    Console.WriteLine();

                    Console.WriteLine("Failed rows count: " + mailer.JobsFailed.Count.ToString());
                }
                Console.WriteLine();

                mailer.JobsSuccessful.Clear();
                mailer.JobsFailed.Clear();
            }
        }

        // In real apps, the statements below should be in 'finally' section to make sure
        // they execute even in case of exception.
        command.Dispose();
        conn.Close();
    }
}
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    Shared failedIds As New ArrayList()
    Shared i As Integer = 0

    ' We use it to check if the data row with certain ID must be processed or not.
    Private Shared Sub mailer_MergingMessage(sender As Object, e As SmtpMergingMessageEventArgs)
        ' If this is 2nd run (retrying failed indices) and the index is not in failed list, skip it.
        Dim rowID As Integer = CInt(e.MergeDataReaderRowValues(0))
        If i > 0 AndAlso failedIds.IndexOf(rowID) < 0 Then
            e.MergeIt = False
        End If
    End Sub

    ' Reports successful attempt of sending e-mail.
    Private Shared Sub mailer_MessageSent(sender As Object, e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        ' Demonstrate getting column by name.
        Dim email As String = e.MergeDataReaderRowValues( _
            Array.IndexOf(e.MergeDataReaderColumnNames, "Email")).ToString()
        Console.WriteLine(String.Format("{0} of '{1}' job SUCCEEDED", email, e.Tag))
    End Sub

    ' Reports failed attempt of sending e-mail.
    Private Shared Sub mailer_MessageNotSent(sender As Object, e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        ' Demonstrate getting column by index (we assume field #0 is ID, field #1 is Email, etc).
        Dim email As String = e.MergeDataReaderRowValues(1).ToString()
        Console.WriteLine(String.Format("{0} of '{1}' job FAILED", email, e.Tag))

        ' On the first run, remember failed id so that we'd be able to retry them on second run.
        If i = 0 Then
            failedIds.Add(e.MergeDataReaderRowValues(0))
        End If
    End Sub

    Shared Sub Main(args As String())
        Dim mailer As New Smtp()

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60) and increase performance.
        ' Note that not all SMTP servers will support so many incoming connections (each thread creates its own).

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to the event which lets us implement retrying failed indices on 2nd run.
        AddHandler mailer.MergingMessage, New SmtpMergingMessageEventHandler(AddressOf mailer_MergingMessage)

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.MessageSent, New SmtpMessageSentEventHandler(AddressOf mailer_MessageSent)
        AddHandler mailer.MessageNotSent, New SmtpMessageNotSentEventHandler(AddressOf mailer_MessageNotSent)

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.[To].AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our Oct/2013 newsletter"

        ' Setup DSN template for mail merge. In particular, this can be useful
        ' to track bounced messages which may come back from some addresses after
        ' sending bulk mail out. If the SMTP server does not support DSN, this
        ' setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "Oct2013_##ID##"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Setup template for adding file attachments upon the specified path.
        ' In this sample, the path to attachment files will be constructed as
        ' "C:\Temp\" + DatabaseRecordField("Doc_path").
        mailer.Message.Merge.AddAttachmentPattern("C:\Temp\##Doc_path##")

        ' Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8"

        ' Tell MailBee to generate alternative plain-text version
        ' of each e-mail automatically.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfHtml

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "server=(local)\SQLEXPRESS;Initial Catalog=afterlogic;Integrated Security=True"

        ' Connect to the database.
        Dim reader As SqlDataReader = Nothing
        Dim conn As New SqlConnection(connParams)
        conn.Open()
        Dim command As SqlCommand = conn.CreateCommand()

        ' The 'mailing_list' table must have these fields:
        ' #0: ID (int)
        ' #1: Email (nvarchar)
        ' #2: Name (nvarchar)
        ' #3: Body (nvarchar)
        ' #4; Doc_path (nvarchar). Can be null if attachment not required. Files are taken from C:\Temp.
        ' Table row example: 196, "jdoe@domain.com", "John", "Some text", "file.dat".
        command.CommandText = "SELECT * FROM mailing_list"

        ' Make two runs of mail merge. If e-mails created from some data rows fail,
        ' we'll attempt to resend them on the second run.
        For i = 0 To 1
            ' Populate mail merge job to-do list with from the specified table.
            reader = command.ExecuteReader()

            ' Create a job which is the following task for MailBee: perform mail merge over
            ' the specified data table and send out each resulting e-mail to
            ' the recipients which appear in the resulting messages. "bounce@domain.com"
            ' address will be used as Return-Path (i.e. sender e-mail address).
            '
            ' keepProducedJobs is true to let us check mailer.JobsSuccessful.Count and
            ' mailer.JobsFailed.Count at the end of the loop. In real apps, you can count successful
            ' and failed sendings by incrementing variables in mailer_MessageSent or mailer_MessageNotSent
            ' event handlers (this will save memory as produced jobs won't increase memory usage over time).
            ' Just be sure to synchronize access to that counter variables (such as with lock or VB's SyncLock
            ' statement if you're using multi-threading), unless you're in WinForms application which processes
            ' events sequentially so that two event handlers could never execute simultaneously.
            mailer.AddJob("My", "bounce@domain.com", Nothing, reader, True, False)

            ' Run the job. The actual mail merge takes place here.
            mailer.SendJobs()

            reader.Close()
            reader = Nothing

            Console.WriteLine()

            ' Report results (row indices in the data table) to the console.
            If mailer.JobsFailed.Count = 0 Then
                Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.")
                Exit For
            Else
                If mailer.JobsSuccessful.Count = 0 Then
                    Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.")
                Else
                    Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.")
                    Console.WriteLine()

                    Console.WriteLine("Successful rows count: " & mailer.JobsSuccessful.Count.ToString())
                    Console.WriteLine()

                    Console.WriteLine("Failed rows count: " & mailer.JobsFailed.Count.ToString())
                End If
                Console.WriteLine()

                mailer.JobsSuccessful.Clear()
                mailer.JobsFailed.Clear()
            End If
        Next
        ' In real apps, the statements below should be in 'finally' section to make sure
        ' they execute even in case of exception.
        command.Dispose()
        conn.Close()
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


Smtp.AddJob Method (String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean)

SmtpAddJob Method (String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean)
Puts a "mail merge over database" job onto waiting list for subsequent processing in bulk mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void AddJob(
    string tag,
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    DataTable mergeTable,
    Object mergeRowIndices,
    bool keepProducedJobs,
    bool keepMergedData
)
Public Sub AddJob (
    tag As String,
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeTable As DataTable,
    mergeRowIndices As Object,
    keepProducedJobs As Boolean,
    keepMergedData As Boolean
)

Parameters

tag
Type: SystemString
Any string the developer wants to assign to Tag property of SendMailJob object created by this method. The developer can leave it a null reference (Nothing in Visual Basic).
senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The e-mail address template of the recipients list. If it's a null reference (Nothing in Visual Basic), the recipients list will be constructed via merge of To, Cc, and Bcc patterns with actual values from the data source.
mergeTable
Type: System.DataDataTable
The data source for mail merge.
mergeRowIndices
Type: SystemObject
The comma-separated list or integer array of indices of rows of mergeTable to be processed, or a null reference (Nothing in Visual Basic) if the entire mergeTable should be processed.
keepProducedJobs
Type: SystemBoolean
Indicates whether MailBee should create separate SendMailJob object for every e-mail message produced during mail merge. If true, JobsSuccessful and JobsFailed collections will end up with the same number of jobs as the number of e-mail messages generated; otherwise, only SendMailJob object originally added by this method will end up in JobsSuccessful or JobsFailed collections.
keepMergedData
Type: SystemBoolean
Indicates whether MailBee should retain merged messages after they have been processed. If true, MailBee will not clear MergedXXX properties of SendMailJob object after the e-mail message associated with this object has been processed; otherwise, MailBee will clear memory occupied by the merged message so that MergedXXX properties start returning null once the message has been processed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | mergeTable is a null reference (Nothing in Visual Basic) or mergeRowIndices is invalid value (for instance, neither string nor array of integers).
Remarks

This method allows the application to schedule mail merge over database for subsequent processing with SendJobs, BeginSendJobs(AsyncCallback, Object), or SubmitJobsToPickupFolder(String, Boolean) method.

Note Note
To perform mail merge immediately rather than schedule it, use SendMailMerge(String, EmailAddressCollection, DataTable) method.
Note Note
This method is not available in .NET Core and UWP editions.

The mail merge requirements:

  • The template of e-mail to be merged with mergeTable data must be specified in Message property. Normally, Message property specifies the e-mail message to be sent out by Smtp object. In the case of mail merge, this e-mail message is considered as a template where ##Column_Name## patterns will be replaced with the actual data from database table rows during the mail merge process.
  • Smtp.DeliveryNotification.TrackingID may also contain a pattern if desired. Thus, it's possible to automatically assign unique tracking ID to the each message sent during mail merge and then receive this ID with bounced messages.
  • mergeTable must be the data source containing all the data rows for which e-mails should be generated and sent; typically, this data source is a result of SQL query.
  • Names of columns of mergeTable must match pattern names in the e-mail template. For instance, if there is Email column in the data table and the developer wishes to make values from this column appear in resulting e-mails, then the e-mail template must contain ##Email## string in the places where the e-mail address needs to be placed. Patterns are case-sensitive! For instance, if data table column name is Email, only ##Email## pattern will be replaced with the column value. ##email## and ##EMAIL## patterns will be left intact.
  • senderEmailPattern can be left null. However, if resulting e-mails should actually be sent from another e-mail address (for instance, resulting e-mails have newsletter@domain.com in "From:" field while you wish to send them from "bounces@domain.com"), then it's required to specify senderEmailPattern. It can contain a pattern (e.g. ##Something##) or refer to the actual value (e.g. from@company.com).
  • recipientsPattern have the same meaning for specifying the actual recipients as senderEmailPattern - for the actual sender. For instance, to set the pattern which will take the 1st recipient's e-mail address from Email field of the data table while the 2nd recipient's email address is hard-coded, pass the following as recipientsPattern value: new EmailAddressCollection("##Email##, archive-copy@company.com").
  • Setting tag to non-empty value helps to distinguish the current mail merge from other jobs if there are any. This is useful if the application submits and processes multiple jobs and the developer wants to track processing of each job separately. Jobs tags also appear in the log if logging is enabled.

mergeRowIndices parameter can be used to specify which rows of mergeTable should be processed. For instance, consider the following scenario: the application initially performed the mail merge with not 100% positive results (some e-mails failed to be sent), and it's desired to run it again to try to re-send initially failed e-mails. This can be done with RetryFailedJobs method but this requires calling RetryFailedJobs in the same application instance that was used to run the initial mail merge. If the initial instance of the application shuts down after performing mail merge, the application should save failed data row indices in a persistent storage (database, file, etc) on exit, and then load these data row indices back when another instance of the application starts. See the example below for details.

keepProducedJobs parameter controls what to do with SendMailJob objects created during mail merge process. When a mail merge job is submitted to JobsPending collection, this job represents the entire mail merge task. Once processing of this job starts, MailBee "bites" a single data row index from this job and creates new SendMailJob object for the e-mail template and this data row. The original mail merge job is moved into JobsRunning (and then into JobsSuccessful or JobsFailed) only when a single data row remains in it. Thus, MailBee splits large mail merge job into many smaller jobs (each processes a single data row) during processing. This allows the developer to easily monitor the status of each e-mail produced by mail merge process and otherwise manage mail merge processing on per e-mail level. However, if the application does not need this, it may set keepProducedJobs to false to automatically remove SendMailJob objects created during processing mail merge when they are no longer needed. This way, only the original SendMailMerge(String, EmailAddressCollection, DataTable) object will be put in JobsSuccessful or JobsFailed collections once the mail merge has been finished. This object will refer to the last data row and the last e-mail message generated during mail merge process.

As you can see, when keepProducedJobs is false, the last sub-job matches so that overall number of items in all collections like JobsPending, JobsFailed, and JobsFailed won't change, the items will just be moved among these collections.

You can also manually control whether to keep jobs after processing with FinishingJob event. For instance, you can make MailBee remove even those jobs which haven't been created by mail merge process (so that total number of all items in all jobs collections upon completion will be zero). This can be useful for the optimization of memory use.

keepMergedData parameter can be set to true to tell MailBee not to clear memory occupied by e-mails generated during mail merge. However, this may cause out-of-memory issues if the size of each generated e-mail message or their number was large.

Still, if's safe to set keepMergedData to true if keepProducedJobs is false. In this case, only a single SendMailJob object will be added to JobsSuccessful or JobsFailed collections so that only a single merged e-mail message will reside in memory.

If, for some reason, you need to retain all the e-mails sent (or not sent) during mail merge, the best approach is to subscribe to MessageSent and MessageNotSent events and perform what you need in the event handlers. Even if keepMergedData is false, MailBee won't clear memory occupied by generated e-mails until MessageSent and MessageNotSent have been raised.

The above is true for keepProducedJobs parameter as well. E-mails generated during mail merge won't be discarded until MailBee has raised MessageSent and MessageNotSent (or any other events which occur before MessageSent or MessageNotSent).

If the application hasn't subscribed to any of these events (and keepProducedJobs or keepMergedData is false), MailBee will dispose objects which are no longer necessary when appropriate.

Examples

This console sample performs mail merge in two runs. On the second run, all the data rows which failed to be sent out as e-mail messages on the first run are tried again. The application may complete in a single run if all the data rows have been successfully sent as e-mails within the first run.

This sample does NOT use RetryFailedJobs method to put failed jobs back into the pending queue. Instead, it demonstrates the approach which would allow the application to terminate after the first run and then retry mail merge of failed data rows later in a separate run of the application. In this sample both runs actually occur within a single application instance but the application structure is ready for making every run occur within separate instances. The sample shows how to get the list of failed data rows into a string and then load it from a string. In a real application, this string will be saved in a file or database before the application terminates first time, and then loaded back from this file or database when the application starts again next time.

C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports successful attempt of sending e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " of '" + e.Tag + "' job SUCCEEDED");
    }

    // Reports failed attempt of sending e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " of '" + e.Tag + "' job FAILED");
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup DSN template for mail merge. In particular, this can be useful
        // to track bounced messages which may come back from some addresses after
        // sending bulk mail out. If the SMTP server does not support DSN, this
        // setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "Jan2007_##ID##";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Setup template for adding file attachments upon the specified path.
        // In this sample, the path to attachment files will be constructed as
        // "C:\" + DatabaseRecordField("Doc_path").
        mailer.Message.Merge.AddAttachmentPattern(@"C:\##Doc_path##");

        // Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8";

        // Tell MailBee to generate alternative plain-text version
        // of each e-mail automatically.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfHtml;

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        // Indices of the data rows which failed during the first run.
        // If null, all indices will be processed.
        string failedIndices = null;

        DataTable table = null;

        // Make two runs of mail merge. If e-mails created from some data rows fail,
        // we'll attempt to resend them on the second run.
        for (int i = 0; i < 2; i++)
        {
            // Connect to the database and populate mail merge job to-do list with
            // the data from "mailing_list" table.
            using (OleDbConnection conn = new OleDbConnection(connParams))
            {
                // Open the connection and get the data.
                OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
                conn.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter();
                table = new DataTable();
                adapter.SelectCommand = command;
                adapter.Fill(table);

                // Create a job which is the following task for MailBee: perform mail merge over
                // the specified data table and send out each resulting e-mail to
                // the recipients which appear in the resulting messages. "bounce@domain.com"
                // address will be used as Return-Path (i.e. sender e-mail address).
                mailer.AddJob("My", "bounce@domain.com", null, table, failedIndices, true, false);
            }

            // Run the job. The actual mail merge takes place here.
            mailer.SendJobs();
            Console.WriteLine();

            // Report results (row indices in the data table) to the console.
            if (mailer.JobsFailed.Count == 0)
            {
                Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.");
                break;
            }
            else
            {
                if (mailer.JobsSuccessful.Count == 0)
                {
                    Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.");
                }
                else
                {
                    Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.");
                    Console.WriteLine();

                    Console.WriteLine("Successful rows: ");
                    Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, "My"));
                    Console.WriteLine();

                    Console.WriteLine("Failed rows: ");
                    Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, "My"));
                }
                Console.WriteLine();

                // Remember failed data rows and clean-up the collections of the results.
                // Actually, we could simply call mailer.RetryFailedJobs instead. We're using
                // 'failedIndices = mailer.JobsFailed.GetIndicesAsString' to demonstrate
                // how this could be done if the application terminates after the first run and
                // then starts again for the second run (which retries processing the failed
                // data rows). In this case, we need to somehow pass the list of failed data rows
                // between two instances of the application. To accomplish this, failedIndices can
                // be written into a file in the end of the first run of the app and then read from
                // the file in the beginning of the second run.
                failedIndices = mailer.JobsFailed.GetIndicesAsString(table, "My");
                mailer.JobsSuccessful.Clear();
                mailer.JobsFailed.Clear();
            }
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports successful attempt of sending e-mail.
    Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " of '" & e.Tag & "' job SUCCEEDED")
    End Sub

    ' Reports failed attempt of sending e-mail.
    Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " of '" & e.Tag & "' job FAILED")
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.MessageSent, AddressOf mailer_MessageSent
        AddHandler mailer.MessageNotSent, AddressOf mailer_MessageNotSent

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup DSN template for mail merge. In particular, this can be useful
        ' to track bounced messages which may come back from some addresses after
        ' sending bulk mail out. If the SMTP server does not support DSN, this
        ' setting will be ignored.
        mailer.DeliveryNotification.TrackingID = "Jan2007_##ID##"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Setup template for adding file attachments upon the specified path.
        ' In this sample, the path to attachment files will be constructed as
        ' "C:\" + DatabaseRecordField("Doc_path").
        mailer.Message.Merge.AddAttachmentPattern("C:\##Doc_path##")

        ' Make outgoing e-mails UTF-8 to allow content in any language.
        mailer.Message.Charset = "UTF-8"

        ' Tell MailBee to generate alternative plain-text version
        ' of each e-mail automatically.
        mailer.Message.Builder.HtmlToPlainMode = HtmlToPlainAutoConvert.IfHtml

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        ' Indices of the data rows which failed during the first run.
        ' If null, all indices will be processed.
        Dim failedIndices As String = Nothing

        Dim table As DataTable = Nothing

        ' Make two runs of mail merge. If e-mails created from some data rows fail,
        ' we'll attempt to resend them on the second run.
        Dim i As Integer
        For i = 0 To 1
            ' Connect to the database and populate mail merge job to-do list with
            ' the data from "mailing_list" table.
            Dim conn As OleDbConnection
            Try
                conn = New OleDbConnection(connParams)

                ' Open the connection and get the data.
                Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
                conn.Open()
                Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
                table = New DataTable
                adapter.SelectCommand = command
                adapter.Fill(table)

                ' Create a job which is the following task for MailBee: perform mail merge over
                ' the specified data table and send out each resulting e-mail to
                ' the recipients which appear in the resulting messages. "bounce@domain.com"
                ' address will be used as Return-Path (i.e. sender e-mail address).
                mailer.AddJob("My", "bounce@domain.com", Nothing, table, failedIndices, True, False)
            Finally
                If Not conn Is Nothing Then
                    conn.Close()
                End If
            End Try

            ' Run the job. The actual mail merge takes place here.
            mailer.SendJobs()
            Console.WriteLine()

            ' Report results (row indices in the data table) to the console.
            If mailer.JobsFailed.Count = 0 Then
                Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.")
                Exit For
            Else
                If mailer.JobsSuccessful.Count = 0 Then
                    Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.")
                Else
                    Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.")
                    Console.WriteLine()

                    Console.WriteLine("Successful rows: ")
                    Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, "My"))
                    Console.WriteLine()

                    Console.WriteLine("Failed rows: ")
                    Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, "My"))
                End If
                Console.WriteLine()

                ' Remember failed data rows and clean-up the collections of the results.
                ' Actually, we could simply call mailer.RetryFailedJobs instead. We're using
                ' 'failedIndices = mailer.JobsFailed.GetIndicesAsString' to demonstrate
                ' how this could be done if the application terminates after the first run and
                ' then starts again for the second run (which retries processing the failed
                ' data rows). In this case, we need to somehow pass the list of failed data rows
                ' between two instances of the application. To accomplish this, failedIndices can
                ' be written into a file in the end of the first run of the app and then read from
                ' the file in the beginning of the second run.
                failedIndices = mailer.JobsFailed.GetIndicesAsString(table, "My")
                mailer.JobsSuccessful.Clear()
                mailer.JobsFailed.Clear()
            End If
        Next
    End Sub
End Class
See Also

Reference

Smtp Class
AddJob Overload
MailBee.SmtpMail Namespace
SmtpRetryFailedJobs
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


Smtp.AuthPopBeforeSmtp Method

SmtpAuthPopBeforeSmtp Method
Authenticates the user on a mail server using POP-before-SMTP authentication.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AuthPopBeforeSmtp(
    string pop3ServerName,
    int pop3ServerPort,
    string pop3AccountName,
    string pop3Password
)
Public Function AuthPopBeforeSmtp (
    pop3ServerName As String,
    pop3ServerPort As Integer,
    pop3AccountName As String,
    pop3Password As String
) As Boolean

Parameters

pop3ServerName
Type: SystemString
The host name or IP address of the POP3 server.
pop3ServerPort
Type: SystemInt32
The port on which POP3 service is running.
pop3AccountName
Type: SystemString
The user account name on the POP3 server.
pop3Password
Type: SystemString
The user account password on the POP3 server.

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method can be used to authenticate the user on the SMTP server if the SMTP server itself does not support ESMTP authentication, but can use results of POP3 authentication performed against a POP3 server which shares the users accounts database with the given SMTP server (usually, this POP3 server is running on the same host where the SMTP server is running).
Note Note
The developer can also enable automatic use of POP-before-SMTP authentication when connecting to the SMTP server by setting AuthPopBeforeSmtp property value to true. However, use of AuthPopBeforeSmtp(String, Int32, String, String) method is more flexible, since AuthPopBeforeSmtp(String, Int32, String, String) method can also be used in scenarios when the POP3 server name/account name/password is different from the corresponding parameters of the companion SMTP server.
Examples
This samples performs POP-before-SMTP authentication on pop.domain.com host prior to connecting to the SMTP server at smtp.domain.com.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("smtp.domain.com");

mailer.AuthPopBeforeSmtp("pop.domain.com", 110, "jdoe", "secret");

mailer.Connect();
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer = New Smtp
mailer.SmtpServers.Add("smtp.domain.com")

mailer.AuthPopBeforeSmtp("pop.domain.com", 110, "jdoe", "secret")

mailer.Connect()
mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpServerAuthPopBeforeSmtp


Smtp.AuthPopBeforeSmtpAsync Method

SmtpAuthPopBeforeSmtpAsync Method
async/await version of AuthPopBeforeSmtp(String, Int32, String, String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> AuthPopBeforeSmtpAsync(
    string pop3ServerName,
    int pop3ServerPort,
    string pop3AccountName,
    string pop3Password
)
Public Function AuthPopBeforeSmtpAsync (
    pop3ServerName As String,
    pop3ServerPort As Integer,
    pop3AccountName As String,
    pop3Password As String
) As Task(Of Boolean)

Parameters

pop3ServerName
Type: SystemString
The host name or IP address of the POP3 server.
pop3ServerPort
Type: SystemInt32
The port on which POP3 service is running.
pop3AccountName
Type: SystemString
The user account name on the POP3 server.
pop3Password
Type: SystemString
The user account password on the POP3 server.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.BeginAuthPopBeforeSmtp Method

SmtpBeginAuthPopBeforeSmtp Method

Note: This API is now obsolete.

Begins an asynchronous request for a POP-before-SMTP authentication on a mail server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use AuthPopBeforeSmtpAsync instead.")]
public IAsyncResult BeginAuthPopBeforeSmtp(
    string pop3ServerName,
    int pop3ServerPort,
    string pop3AccountName,
    string pop3Password,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use AuthPopBeforeSmtpAsync instead.")>
Public Function BeginAuthPopBeforeSmtp (
    pop3ServerName As String,
    pop3ServerPort As Integer,
    pop3AccountName As String,
    pop3Password As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

pop3ServerName
Type: SystemString
The host name or IP address of the POP3 server.
pop3ServerPort
Type: SystemInt32
The port on which POP3 service is running.
pop3AccountName
Type: SystemString
The user account name on the POP3 server.
pop3Password
Type: SystemString
The user account password on the POP3 server.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous POP-before-SMTP authentication.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of AuthPopBeforeSmtp(String, Int32, String, String).
Examples
This WinForms sample demonstrates how to perform POP-before-SMTP authentication asynchronously.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// Put the code below inside your class.

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Smtp mailer = new Smtp();

    // Let MailBee process events.
    mailer.RaiseEventsViaMessageLoop = false;

    mailer.SmtpServers.Add("mail.domain.com");

    // Initiate an asynchronous POP-before-SMTP authentication attempt.
    mailer.BeginAuthPopBeforeSmtp("mail.domain.com", 110, "jdoe", "secret", null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        mailer.Wait(0);
    }

    // End the POP-before-SMTP operation. If it's in progress at the moment
    // this method starts, it will wait until it's done first.
    mailer.EndAuthPopBeforeSmtp();

    // Connect to SMTP server and say Hello.
    mailer.Connect();
    mailer.Hello();

    // Can send mail here or do whatever needed.
    // ...

    // Close the connection.
    mailer.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' Put the code below inside your class.

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim mailer = New Smtp

    ' Let MailBee process events.
    mailer.RaiseEventsViaMessageLoop = False

    mailer.SmtpServers.Add("mail.domain.com")

    ' Initiate an asynchronous POP-before-SMTP authentication attempt.
    mailer.BeginAuthPopBeforeSmtp("mail.domain.com", 110, "jdoe", "secret", Nothing, Nothing)

    ' Simulate some lengthy work here...
    For i As Integer = 1 To 100
        ' Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above.
        mailer.Wait(0)
    Next

    ' End the POP-before-SMTP operation. If it's in progress at the moment
    ' this method starts, it will wait until it's done first.
    mailer.EndAuthPopBeforeSmtp()

    ' Connect to SMTP server and say Hello.
    mailer.Connect()
    mailer.Hello()

    ' Can send mail here or do whatever needed.
    ' ...

    ' Close the connection.
    mailer.Disconnect()
End Sub
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpAuthPopBeforeSmtp(String, Int32, String, String)


Smtp.BeginConnect Method

SmtpBeginConnect Method

Note: This API is now obsolete.

Begins an asynchronous request for connecting to an SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ConnectAsync instead.")]
public IAsyncResult BeginConnect(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ConnectAsync instead.")>
Public Function BeginConnect (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous POP-before-SMTP authentication.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Connect.
Examples
This console sample connects to the SMTP server asynchronously and handles Connected event. No callback function is used.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // "Connected" event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Successfully connected to the server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        mailer.SmtpServers.Add("smtp.somehost.com");

        // Subscribe to the Connected event.
        mailer.Connected += new ConnectedEventHandler(OnConnected);

        // Initiate an asynchronous connection.
        mailer.BeginConnect(null, null);

        // Simulate some lengthy work here. At the same time,
        // the connection with the server is established on another thread.
        System.Threading.Thread.Sleep(3000);

        // End the connection request.
        mailer.EndConnect();

        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' "Connected" event handler.
    Private Shared Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Successfully connected to the server.")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        mailer.SmtpServers.Add("smtp.somehost.com")

        ' Subscribe to the Connected event.
        AddHandler mailer.Connected, AddressOf OnConnected

        ' Initiate an asynchronous connection.
        mailer.BeginConnect(Nothing, Nothing)

        ' Simulate some lengthy work here. At the same time,
        ' the connection with the server is established on another thread.
        System.Threading.Thread.Sleep(3000)

        ' End the connection request.
        mailer.EndConnect()

        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpConnect


Smtp.BeginDisconnect Method

SmtpBeginDisconnect Method

Note: This API is now obsolete.

Begins an asynchronous request for a disconnection from the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DisconnectAsync instead.")]
public IAsyncResult BeginDisconnect(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use DisconnectAsync instead.")>
Public Function BeginDisconnect (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous disconnection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Disconnect.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDisconnect


Smtp.BeginExecuteCustomCommand Method

SmtpBeginExecuteCustomCommand Method

Note: This API is now obsolete.

Begins an asynchronous request for sending the specified user-defined command to the server and getting the response.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ExecuteCustomCommandAsync instead.")]
public IAsyncResult BeginExecuteCustomCommand(
    string commandString,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use ExecuteCustomCommandAsync instead.")>
Public Function BeginExecuteCustomCommand (
    commandString As String,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

commandString
Type: SystemString
User-defined command text (including line terminator).
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous user-defined command execution.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of ExecuteCustomCommand(String).
Examples
This WinForms samples verifies e-mail address syntax by sending VRFY command to the SMTP server (the SMTP server must support VRFY command). The sample gets notified of VRFY command completion by using a callback function.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// Put the code below inside your class.

// ExecuteCustomCommand callback function.
private void ExecuteCustomCommandCallback(IAsyncResult result)
{
    Smtp mailer = (Smtp)result.AsyncState;

    try
    {
        // If this method does not throw exception, VRFY command
        // is supported, and the e-mail address validation passed.
        // It's up to the server to decide whether to validate just
        // syntax or check if such e-mail address really exists.
        mailer.EndExecuteCustomCommand();
        MessageBox.Show("The e-mail address is correct");
    }
    catch (MailBeeSmtpNegativeResponseException e)
    {
        MessageBox.Show(e.ResponseString);
    }

    // Close the connection.
    mailer.Disconnect();
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Smtp mailer = new Smtp();

    mailer.SmtpServers.Add("mail.host.com");

    // Connect to SMTP server and say Hello.
    mailer.Connect();
    mailer.Hello();

    // Initiate an asynchronous e-mail address verification attempt.
    mailer.BeginExecuteCustomCommand("VRFY user@domain.com\r\n",
        new AsyncCallback(ExecuteCustomCommandCallback), mailer);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' Put the code below inside your class.

' ExecuteCustomCommand callback function.
Private Sub ExecuteCustomCommandCallback(ByVal result As IAsyncResult)
    Dim mailer As Smtp = result.AsyncState

    Try
        ' If this method does not throw exception, VRFY command
        ' is supported, and the e-mail address validation passed.
        ' It's up to the server to decide whether to validate just
        ' syntax or check if such e-mail address really exists.
        mailer.EndExecuteCustomCommand()
        MsgBox("The e-mail address is correct")
    Catch e As MailBeeSmtpNegativeResponseException
        MsgBox.Show(e.ResponseString)
    End Try

    ' Close the connection.
    mailer.Disconnect()
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim mailer As New Smtp

    mailer.SmtpServers.Add("mail.host.com")

    ' Connect to SMTP server and say Hello.
    mailer.Connect()
    mailer.Hello()

    ' Initiate an asynchronous e-mail address verification attempt.
    mailer.BeginExecuteCustomCommand("VRFY user@domain.com\r\n", _
        New AsyncCallback(AddressOf ExecuteCustomCommandCallback), mailer)
End Sub
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpExecuteCustomCommand(String)


Smtp.BeginHello Method

SmtpBeginHello Method

Note: This API is now obsolete.

Begins an asynchronous request for sending initial greeting to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use HelloAsync instead.")]
public IAsyncResult BeginHello(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use HelloAsync instead.")>
Public Function BeginHello (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous greeting.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Hello.
Examples
This console sample connects to the SMTP server, sends greeting asynchronously, and handles ErrorOccurred event to trap the warning telling that EHLO is not supported, and HELO will be tried (this warning event will be raised only if the server is not ESMTP enabled). No callback function is used.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        if (e.Reason is MailBeeSmtpOptionalCommandNotSupportedException)
        {
            Console.WriteLine(e.Reason.Message); // EHLO not supported.
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        mailer.SmtpServers.Add("mail.domain.com");

        mailer.Connect();

        // Subscribe to the ErrorOccurred event. We subcribe only for the time
        // of Hello() method execution to make sure the trapped warnings do not
        // relate to execution of any other methods.
        mailer.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Initiate an asynchronous greeting.
        mailer.BeginHello(null, null);

        // Simulate some lengthy work here. At the same time,
        // the greeting is performed on another thread.
        System.Threading.Thread.Sleep(1000);

        // End the connection request.
        mailer.EndHello();

        mailer.ErrorOccurred -= new ErrorEventHandler(OnErrorOccurred);

        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' ErrorOccurred event handler.
    Private Shared Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        If (TypeOf e.Reason Is MailBeeSmtpOptionalCommandNotSupportedException) Then
            Console.WriteLine(e.Reason.Message)' EHLO not supported.
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        mailer.SmtpServers.Add("mail.domain.com")

        mailer.Connect()

        ' Subscribe to the ErrorOccurred event. We subcribe only for the time
        ' of Hello() method execution to make sure the trapped warnings do not
        ' relate to execution of any other methods.
        AddHandler mailer.ErrorOccurred, AddressOf OnErrorOccurred

        ' Initiate an asynchronous greeting.
        mailer.BeginHello(Nothing, Nothing)

        ' Simulate some lengthy work here. At the same time,
        ' the greeting is performed on another thread.
        System.Threading.Thread.Sleep(1000)

        ' End the connection request.
        mailer.EndHello()

        RemoveHandler mailer.ErrorOccurred, AddressOf OnErrorOccurred

        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpHello


Smtp.BeginLogin Method

SmtpBeginLogin Method

Note: This API is now obsolete.

Begins an asynchronous request for authenticating the user on the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use LoginAsync instead.")]
public IAsyncResult BeginLogin(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use LoginAsync instead.")>
Public Function BeginLogin (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous authentication.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Login.
Examples
This WinForms sample demonstrates using asynchronous authentication in conjunction with a callback function.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// Put the code below inside your class.

// Login callback function.
private void LoginCallback(IAsyncResult result)
{
    Smtp mailer = (Smtp)result.AsyncState;

    mailer.EndLogin();
    MessageBox.Show("Authentication succeeded");

    // Close the connection.
    mailer.Disconnect();
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Smtp mailer = new Smtp();

    mailer.SmtpServers.Add("smtp.somehost.com", "jdoe", "secret");

    // Connect to SMTP server and say Hello.
    mailer.Connect();
    mailer.Hello();

    // Initiate an asynchronous authentication attempt.
    mailer.BeginLogin(new AsyncCallback(LoginCallback), mailer);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' Put the code below inside your class.

' Login callback function.
Private Sub LoginCallback(ByVal result As IAsyncResult)
    Dim mailer As Smtp = result.AsyncState

    mailer.EndLogin()
    MsgBox("Authentication succeeded")

    ' Close the connection.
    mailer.Disconnect()
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim mailer As New Smtp

    mailer.SmtpServers.Add("smtp.somehost.com", "jdoe", "secret")

    ' Connect to SMTP server and say Hello.
    mailer.Connect()
    mailer.Hello()

    ' Initiate an asynchronous authentication attempt.
    mailer.BeginLogin(New AsyncCallback(AddressOf LoginCallback), mailer)
End Sub
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLogin


Smtp.BeginRelayFromEmlFile Method

SmtpBeginRelayFromEmlFile Method

Note: This API is now obsolete.

Begins an asynchronous request for relaying a mail message to recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use RelayFromEmlFileAsync instead.")]
public IAsyncResult BeginRelayFromEmlFile(
    string filename,
    string senderEmail,
    EmailAddressCollection recipients,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use RelayFromEmlFileAsync instead.")>
Public Function BeginRelayFromEmlFile (
    filename As String,
    senderEmail As String,
    recipients As EmailAddressCollection,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

filename
Type: SystemString
The path to the file containing the message source in .EML (RFC2822) format.
senderEmail
Type: SystemString
The e-mail address of the sender.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous relaying the message.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of RelayFromEmlFile(String, String, EmailAddressCollection).
Examples
This console sample demonstrates asynchronous relaying the mail message using direct send approach (via DNS MX lookup). No callback function is used.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get the list of DNS servers from OS settings or the config file.
        mailer.DnsServers.Autodetect();

        // Initiate an asynchronous relay.
        mailer.BeginRelayFromEmlFile(@"C:\Temp\message.eml", "kathy@company.com",
            new EmailAddressCollection("mike@domain1.com, bob@domain2.com"), null, null);

        // Simulate some lengthy work here. At the same time,
        // the message is being sent to recipients domains on another thread.
        System.Threading.Thread.Sleep(3000);

        // End the relay request. If send mail operation is still in progress,
        // the method will wait until it's finished.
        mailer.EndRelayFromEmlFile();

        // Print the outcome.
        Console.WriteLine("Successfully sent to: " + mailer.GetAcceptedRecipients().ToString());
        Console.WriteLine("Not sent to: " + mailer.GetRefusedRecipients().ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Class Sample
    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get the list of DNS servers from OS settings or the config file.
        mailer.DnsServers.Autodetect()

        ' Initiate an asynchronous relay.
        mailer.BeginRelayFromEmlFile("C:\Temp\message.eml", "kathy@company.com", _
            New EmailAddressCollection("mike@domain1.com, bob@domain2.com"), Nothing, Nothing)

        ' Simulate some lengthy work here. At the same time,
        ' the message is being sent to recipients domains on another thread.
        System.Threading.Thread.Sleep(3000)

        ' End the relay request. If send mail operation is still in progress,
        ' the method will wait until it's finished.
        mailer.EndRelayFromEmlFile()

        ' Print the outcome.
        Console.WriteLine("Successfully sent to: " & mailer.GetAcceptedRecipients().ToString())
        Console.WriteLine("Not sent to: " & mailer.GetRefusedRecipients().ToString())
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpRelayFromEmlFile(String, String, EmailAddressCollection)


Smtp.BeginSend Method

SmtpBeginSend Method

Note: This API is now obsolete.

Begins an asynchronous request for sending a mail message to recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SendAsync instead.")]
public IAsyncResult BeginSend(
    string senderEmail,
    EmailAddressCollection recipients,
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SendAsync instead.")>
Public Function BeginSend (
    senderEmail As String,
    recipients As EmailAddressCollection,
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

senderEmail
Type: SystemString
The e-mail address of the sender.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients.
callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous sending the message.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of Send.
Examples
This WinForms sample sends a mail message asynchronously. The callback function is used to receive notification on asynchronous method completion. Events are used to track send mail progress.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.DnsMX;
using MailBee.Mime;

// Put the code below inside your class.

// MessageSubmittedToServer event handler.
private void OnMessageSubmittedToServer(object sender,
    SmtpMessageSubmittedToServerEventArgs e)
{
    // If no recipients received the message, this event won't be raised.
    // It's safe to assume AcceptedRecipients collection is not empty.
    string domain = e.AcceptedRecipients[0].GetDomain();
    MessageBox.Show("Message was sent to recipients at " + domain + " domain");
}

// MessageRecipientSubmitted event handler.
private void OnMessageRecipientSubmitted(object sender,
    SmtpMessageRecipientSubmittedEventArgs e)
{
    // If a particular recipient was refused, let the user know.
    if (!e.Result)
    {
        MessageBox.Show("For e-mail address " + e.RecipientEmail +
            ", server responded: " + e.ServerStatusMessage);
    }
}

// Send callback function.
private void SendCallback(IAsyncResult result)
{
    Smtp mailer = (Smtp)result.AsyncState;
    mailer.EndSend();
    MessageBox.Show("The e-mail was sent to: " +
        mailer.GetAcceptedRecipients().ToString());
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Smtp mailer = new Smtp();

    // Enable logging SMTP session into a file.
    mailer.Log.Enabled = true;
    mailer.Log.Filename = @"C:\Temp\log.txt";
    mailer.Log.Clear();
    mailer.Log.Format = LogFormatOptions.AddContextInfo;

    // Get the list of DNS servers for MX lookup from OS settings
    // (app.config/web.config/machine.config files are ignored).
    mailer.DnsServers.Autodetect(
        DnsAutodetectOptions.Registry | DnsAutodetectOptions.Wmi);

    // Subscribe to events.
    mailer.MessageSubmittedToServer +=
        new SmtpMessageSubmittedToServerEventHandler(OnMessageSubmittedToServer);
    mailer.MessageRecipientSubmitted +=
        new SmtpMessageRecipientSubmittedEventHandler(OnMessageRecipientSubmitted);

    mailer.From.Email = "jdoe@domain.com";
    mailer.Subject = "Important details";

    // Demonstrate different methods of adding To, CC, and BCC recipients.
    mailer.To.AsString = "kathy@domain.com, \"Bill Smith, Jr.\" <b.smith@company.com>";
    mailer.Cc.Add("Peter", "peter@domain.com");
    mailer.Cc.Add("john@domain.com");
    mailer.Bcc.AsString = "echelon@secret.com";

    // Specify HTML body.
    mailer.BodyHtmlText = "<html>Here are the details.</html>";

    // Create plain-text version.
    mailer.Message.MakePlainBodyFromHtmlBody();

    // Initiate an asynchronous send mail attempt.
    mailer.BeginSend(null, null, new AsyncCallback(SendCallback), mailer);
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.DnsMX
Imports MailBee.Mime

' Put the code below inside your class.

' MessageSubmittedToServer event handler.
Private Sub OnMessageSubmittedToServer(ByVal sender As Object, _
    ByVal e As SmtpMessageSubmittedToServerEventArgs)
    ' If no recipients received the message, this event won't be raised.
    ' It's safe to assume AcceptedRecipients collection is not empty.
    Dim domain As String = e.AcceptedRecipients(0).GetDomain()
    MsgBox("Message was sent to recipients at " & domain & " domain")
End Sub

' MessageRecipientSubmitted event handler.
Private Sub OnMessageRecipientSubmitted(ByVal sender As Object, _
    ByVal e As SmtpMessageRecipientSubmittedEventArgs)
    ' If a particular recipient was refused, let the user know.
    If (Not e.Result) Then
        MsgBox("For e-mail address " & e.RecipientEmail & _
            ", server responded: " & e.ServerStatusMessage)
    End If
End Sub

' Send callback function.
Private Sub SendCallback(ByVal result As IAsyncResult)
    Dim mailer As Smtp = result.AsyncState
    mailer.EndSend()
    MsgBox("The e-mail was sent to: " & _
        mailer.GetAcceptedRecipients().ToString())
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim mailer As New Smtp

    ' Enable logging SMTP session into a file.
    mailer.Log.Enabled = True
    mailer.Log.Filename = "C:\Temp\log.txt"
    mailer.Log.Clear()
    mailer.Log.Format = LogFormatOptions.AddContextInfo

    ' Get the list of DNS servers for MX lookup from OS settings
    ' (app.config/web.config/machine.config files are ignored).
    mailer.DnsServers.Autodetect( _
    DnsAutodetectOptions.Registry Or DnsAutodetectOptions.Wmi)

    ' Subscribe to events.
    AddHandler mailer.MessageSubmittedToServer, AddressOf OnMessageSubmittedToServer
    AddHandler mailer.MessageRecipientSubmitted, AddressOf OnMessageRecipientSubmitted

    mailer.From.Email = "jdoe@domain.com"
    mailer.Subject = "Important details"

    ' Demonstrate different methods of adding To, CC, and BCC recipients.
    mailer.To.AsString = "kathy@domain.com, ""Bill Smith, Jr."" <b.smith@company.com>"
    mailer.Cc.Add("Peter", "peter@domain.com")
    mailer.Cc.Add("john@domain.com")
    mailer.Bcc.AsString = "echelon@secret.com"

    ' Specify HTML body.
    mailer.BodyHtmlText = "<html>Here are the details.</html>"

    ' Create plain-text version.
    mailer.Message.MakePlainBodyFromHtmlBody()

    ' Initiate an asynchronous send mail attempt.
    mailer.BeginSend(Nothing, Nothing, New AsyncCallback(AddressOf SendCallback), mailer)
End Sub
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSend


Smtp.BeginSendJobs Method

SmtpBeginSendJobs Method

Note: This API is now obsolete.

Begins an asynchronous request to process the pending jobs and send out the resulting e-mails.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SendJobsAsync instead.")]
public IAsyncResult BeginSendJobs(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use SendJobsAsync instead.")>
Public Function BeginSendJobs (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references asynchronous sending e-mails accordingly the assigned pending jobs.
Remarks
This method is an asynchronous version of SendJobs method.
Examples
This console sample performs mail merge asynchronously. The sample gets notified of mail merge completion by using a callback function.
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using System.Threading;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    private static bool finished = false;

    // SendJobs callback function.
    private static void SendJobsCallback(IAsyncResult result)
    {
        Smtp mailer = (Smtp)result.AsyncState;

        mailer.EndSendJobs();

        // Report results (row indices in the data table) to the console.
        if (mailer.JobsFailed.Count == 0)
        {
            Console.WriteLine("Newsletter has been sent out without any errors.");
        }
        else
        {
            if (mailer.JobsSuccessful.Count == 0)
            {
                Console.WriteLine("All newsletter e-mails failed to be sent.");
            }
            else if (mailer.JobsFailed.Count > 0)
            {
                Console.WriteLine("Not all newsletter e-mails have been sent.");
                Console.WriteLine();

                // Obtain a reference to the DataTable used for mail merge.
                DataTable table = mailer.JobsFailed[0].MergeTable;

                Console.WriteLine("Successful rows: ");
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, null));
                Console.WriteLine();

                Console.WriteLine("Failed rows: ");
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, null));
            }
            else
            {
                Console.WriteLine("There was nothing to send.");
            }
        }

        Console.WriteLine();

        finished = true;
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our newsletter";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        // Connect to the database and populate mail merge job to-do list with
        // the data from "mailing_list" table.
        using (OleDbConnection conn = new OleDbConnection(connParams))
        {
            // Open the connection and get the data.
            OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
            conn.Open();
            DataTable table = new DataTable();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = command;
            adapter.Fill(table);

            // Create a job which is the following task for MailBee: perform mail merge
            // of a newsletter template with data rows of the specified data table and
            // send out each resulting e-mail to its intended recipients.
            mailer.AddJob(null, null, null, table);
        }

        // Start processing jobs. The actual mail merge takes place here.
        mailer.BeginSendJobs(new AsyncCallback(SendJobsCallback), mailer);

        // Can do anything else while the mail merge takes place in the background.
        while (!finished)
        {
            Thread.Sleep(1000);
        }

        Console.WriteLine("Processing jobs done.");
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Threading
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    Private Shared finished As Boolean = False

    ' SendJobs callback function.
    Private Shared Sub SendJobsCallback(ByVal result As IAsyncResult)
        Dim mailer As Smtp = CType(result.AsyncState, Smtp)

        mailer.EndSendJobs()

        ' Report results (row indices in the data table) to the console.
        If mailer.JobsFailed.Count = 0 Then
            Console.WriteLine("Newsletter has been sent out without any errors.")
        Else
            If mailer.JobsSuccessful.Count = 0 Then
                Console.WriteLine("All newsletter e-mails failed to be sent.")
            ElseIf mailer.JobsFailed.Count > 0 Then
                Console.WriteLine("Not all newsletter e-mails have been sent.")
                Console.WriteLine()

                ' Obtain a reference to the DataTable used for mail merge.
                Dim table As DataTable = mailer.JobsFailed(0).MergeTable

                Console.WriteLine("Successful rows: ")
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(table, Nothing))
                Console.WriteLine()

                Console.WriteLine("Failed rows: ")
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(table, Nothing))
            Else
                Console.WriteLine("There was nothing to send.")
            End If
        End If

        Console.WriteLine()

        finished = True
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our newsletter"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        ' Connect to the database and populate mail merge job to-do list with
        ' the data from "mailing_list" table.
        Dim conn As OleDbConnection
        Try
            conn = New OleDbConnection(connParams)

            ' Open the connection and get the data.
            Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
            conn.Open()
            Dim table As DataTable = New DataTable
            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
            adapter.SelectCommand = command
            adapter.Fill(table)

            ' Create a job which is the following task for MailBee: perform mail merge
            ' of a newsletter template with data rows of the specified data table and
            ' send out each resulting e-mail to its intended recipients.
            mailer.AddJob(Nothing, Nothing, Nothing, table)
        Finally
            If Not conn Is Nothing Then
                conn.Close()
            End If
        End Try

        ' Start processing jobs. The actual mail merge takes place here.
        mailer.BeginSendJobs(New AsyncCallback(AddressOf SendJobsCallback), mailer)

        ' Can do anything else while the mail merge takes place in the background.
        While Not finished
            Thread.Sleep(1000)
        End While

        Console.WriteLine("Processing jobs done.")
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSendJobs
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


Smtp.BeginStartTls Method

SmtpBeginStartTls Method

Note: This API is now obsolete.

Begins an asynchronous request to start TLS/SSL negotiation with the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use StartTlsAsync instead.")]
public IAsyncResult BeginStartTls(
    AsyncCallback callback,
    Object state
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+. Use StartTlsAsync instead.")>
Public Function BeginStartTls (
    callback As AsyncCallback,
    state As Object
) As IAsyncResult

Parameters

callback
Type: SystemAsyncCallback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
Type: SystemObject
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

Type: IAsyncResult
An IAsyncResult that references the asynchronous TLS/SSL negotiation.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There is already an operation in progress.
Remarks
This method is an asynchronous version of StartTls.
Examples
Asynchronous TLS/SSL negotiation with the SMTP server in WinForms application. This sample also handles TlsStarted event. Wait method is used to wait for the asynchronous method completion, since .NET's standard WaitOne(Int32, Boolean) cannot process events.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// Put the code below inside your class.

// TlsStarted event handler.
private void OnTlsStarted(object sender, TlsStartedEventArgs e)
{
    MessageBox.Show("TLS/SSL negotiation complete. Secure connection is ready.");
}

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Smtp mailer = new Smtp();

    // Let MailBee process events.
    mailer.RaiseEventsViaMessageLoop = false;

    mailer.SmtpServers.Add("smtp.domain.com");

    mailer.TlsStarted += new TlsStartedEventHandler(OnTlsStarted);

    mailer.Connect();
    mailer.Hello();

    // Initiate an asynchronous TLS/SSL negotiation.
    mailer.BeginStartTls(null, null);

    // Simulate some lengthy work here...
    for (int i = 0; i < 100; i++)
    {
        // Make a portion of the work.
        System.Threading.Thread.Sleep(10);

        // Process events which were raised during execution of the work above.
        mailer.Wait(0);
    }

    // If the connection was not established during execution of the lengthy
    // work, wait until it's established.
    mailer.Wait();

    // End the connection request.
    mailer.EndStartTls();

    // The connection is now under TLS/SSL layer!

    mailer.Hello();

    // Disconnect from the server.
    mailer.Disconnect();
}
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' Put the code below inside your class.

' TlsStarted event handler.
Private Sub OnTlsStarted(ByVal sender As Object, ByVal e As TlsStartedEventArgs)
    MsgBox("TLS/SSL negotiation complete. Secure connection is ready.")
End Sub

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim mailer As New Smtp

    ' Let MailBee process events.
    mailer.RaiseEventsViaMessageLoop = False

    mailer.SmtpServers.Add("smtp.domain.com")

    AddHandler mailer.TlsStarted, AddressOf OnTlsStarted

    mailer.Connect()
    mailer.Hello()

    ' Initiate an asynchronous TLS/SSL negotiation.
    mailer.BeginStartTls(Nothing, Nothing)

    ' Simulate some lengthy work here...
    Dim i As Integer
    For i = 1 To 100
        ' Make a portion of the work.
        System.Threading.Thread.Sleep(10)

        ' Process events which were raised during execution of the work above.
        mailer.Wait(0)
    Next

    ' If the connection was not established during execution of the lengthy
    ' work, wait until it's established.
    mailer.Wait()

    ' End the connection request.
    mailer.EndStartTls()

    ' The connection is now under TLS/SSL layer!

    mailer.Hello()

    ' Disconnect from the server.
    mailer.Disconnect()
End Sub
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpStartTls


Smtp.Connect Method

SmtpConnect Method
Connects to an SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Connect()
Public Function Connect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

If SmtpServers collection contains only one SmtpServer instance, the component will attempt to connect to the server denoted by this SmtpServer instance only.

If SmtpServers collection contains multiple SmtpServer instances, the component will first attempt to connect to the first instance (SmtpServers[0]), then, if it fails, to the second, etc. Since SmtpServer objects are sorted accordingly their priority values (Priority, high-priority servers will be tried first. This gives the developer ability to implement reliable mail sending mechanism with support of backup servers which should be used when primary servers fail.

If the connection has already been made in the past, and that connection failed for the first server in the collection (SmtpServers[0]) but then succeeded for the second server (SmtpServers[1]) so that the current position in SmtpServers collection advanced by 1, the component will now try to connect to the second server first. Thus, the component remembers which server in SmtpServers collection is up and running, so that subsequent connection attempts could try this server first. If now this server fails, the next server in SmtpServers collection is tried, etc. If the last server in the collection fails too, the component starts back from the beginning of the collection and tries the servers which have not yet been tried during the last connection attempt. Then, if they all failed too and the component reaches the same server it already tried during the current connection attempt (in our example, it's the second server in the collection), the component will report an error.

The developer can use GetCurrentSmtpServerIndex method to learn the position (in SmtpServers collection) of the server to which the component tried to connect last time (regardless whether that connection attempt succeeded or not).

Note Note
By default, MailBee can autodetect if the mail server you're connecting to requires SSL connection (this works for well-known mail services like gmail.com or live.com). To disable SSL mode and port autodetection, set AutodetectPortAndSslMode to false.
Examples
This sample attempts to connect to the primary SMTP server, but will automatically switch to the backup server if the primary server is down. If the connection is established, the name of the server the component connected to is printed into console.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Add high-piority (0) main server and lower-priority (1) backup server.
mailer.SmtpServers.Add("main.server.com", 25, 0);
mailer.SmtpServers.Add("backup.server.com", 25, 1);

// Attempt to connect.
mailer.Connect();

// Display the host name of the server the connected was established with.
Console.WriteLine(mailer.SmtpServers[mailer.GetCurrentSmtpServerIndex()].Name);

mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer = New Smtp

' Add high-piority (0) main server and lower-priority (1) backup server.
mailer.SmtpServers.Add("main.server.com", 25, 0)
mailer.SmtpServers.Add("backup.server.com", 25, 1)

' Attempt to connect.
mailer.Connect()

' Display the host name of the server the connected was established with.
Console.WriteLine(mailer.SmtpServers(mailer.GetCurrentSmtpServerIndex()).Name)

mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpHello


Smtp.ConnectAsync Method

SmtpConnectAsync Method
async/await version of Connect.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ConnectAsync()
Public Function ConnectAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Disconnect Method

SmtpDisconnect Method
Disconnects from the SMTP server and releases any used resources.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Disconnect()
Public Function Disconnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.DisconnectAsync Method

SmtpDisconnectAsync Method
async/await version of Disconnect.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> DisconnectAsync()
Public Function DisconnectAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Dispose Method

SmtpDispose Method
Overload List
 | Name | Description
Public method | Dispose | Closes opened network connections (if any) and releases any used system resources.
Protected method | Dispose(Boolean) | When overridden in a derived class, must release unmananged and optionally managed resources used by the component.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Dispose Method

SmtpDispose Method
Closes opened network connections (if any) and releases any used system resources.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Dispose()
Public Sub Dispose

Implements

IDisposableDispose
Remarks
Usually, the developer does not need to call this method. It's recommended to call Disconnect method to close the connections and free the resources.
See Also

Reference

Smtp Class
Dispose Overload
MailBee.SmtpMail Namespace


Smtp.Dispose Method (Boolean)

SmtpDispose Method (Boolean)
When overridden in a derived class, must release unmananged and optionally managed resources used by the component.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected virtual void Dispose(
    bool disposing
)
Protected Overridable Sub Dispose (
    disposing As Boolean
)

Parameters

disposing
Type: SystemBoolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Remarks
If the derived class does not use any additional resources, this method does not need to be overridden. If, however, it's overridden, the developer must also call Dispose method of the base class.
See Also

Reference

Smtp Class
Dispose Overload
MailBee.SmtpMail Namespace


Smtp.EndAuthPopBeforeSmtp Method

SmtpEndAuthPopBeforeSmtp Method
Ends the pending asynchronous request for POP-before-SMTP authentication on a mail server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndAuthPopBeforeSmtp()
Public Function EndAuthPopBeforeSmtp As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginAuthPopBeforeSmtp(String, Int32, String, String, AsyncCallback, Object)


Smtp.EndConnect Method

SmtpEndConnect Method
Ends the pending asynchronous request for connecting to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndConnect()
Public Function EndConnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginConnect(AsyncCallback, Object)


Smtp.EndDisconnect Method

SmtpEndDisconnect Method
Ends a pending asynchronous disconnection request.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndDisconnect()
Public Function EndDisconnect As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginDisconnect(AsyncCallback, Object)


Smtp.EndExecuteCustomCommand Method

SmtpEndExecuteCustomCommand Method
Ends the pending asynchronous request for sending user-defined command to the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndExecuteCustomCommand()
Public Function EndExecuteCustomCommand As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginExecuteCustomCommand(String, AsyncCallback, Object)


Smtp.EndHello Method

SmtpEndHello Method
Ends the pending asynchronous request for sending a greeting to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndHello()
Public Function EndHello As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginHello(AsyncCallback, Object)


Smtp.EndLogin Method

SmtpEndLogin Method
Ends the pending asynchronous request for authenticating the user on the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndLogin()
Public Function EndLogin As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginLogin(AsyncCallback, Object)


Smtp.EndRelayFromEmlFile Method

SmtpEndRelayFromEmlFile Method
Ends the pending asynchronous request for relaying the message to the recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndRelayFromEmlFile()
Public Function EndRelayFromEmlFile As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginRelayFromEmlFile(String, String, EmailAddressCollection, AsyncCallback, Object)


Smtp.EndSend Method

SmtpEndSend Method
Ends the pending asynchronous request for sending the message to the recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndSend()
Public Function EndSend As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginSend(String, EmailAddressCollection, AsyncCallback, Object)


Smtp.EndSendJobs Method

SmtpEndSendJobs Method
Ends the pending asynchronous request for processing the pending jobs and sending out the resulting e-mails.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndSendJobs()
Public Function EndSendJobs As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginSendJobs(AsyncCallback, Object)


Smtp.EndStartTls Method

SmtpEndStartTls Method
Ends a pending asynchronous TLS/SSL negotiation request.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool EndStartTls()
Public Function EndStartTls As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpBeginStartTls(AsyncCallback, Object)


Smtp.ExecuteCustomCommand Method

SmtpExecuteCustomCommand Method
Sends user-defined command to the server and receives the server response to this command.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ExecuteCustomCommand(
    string commandString
)
Public Function ExecuteCustomCommand (
    commandString As String
) As Boolean

Parameters

commandString
Type: SystemString
User-defined command text (including line terminator).

Return Value

Type: Boolean
true if the command was executed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
The developer can use GetServerResponse method to obtain the response data returned by the server.
Examples
This sample connects to the SMTP server, issues HELP command, and displays the server response to this command. If HELP command is not supported by the server, MailBee will throw MailBeeSmtpNegativeResponseException. It's caught in the sample code, and the proper error message is displayed.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("smtp.host.com");
mailer.Connect();
try
{
    // Send HELP command.
    mailer.ExecuteCustomCommand("HELP\r\n");
    Console.WriteLine(mailer.GetServerResponse());
}
catch (MailBeeSmtpNegativeResponseException e)
{
    // The given SMTP server does not support HELP command.
    Console.WriteLine(e.Message);
    Console.WriteLine("Server response is: " + mailer.GetServerResponse());
}
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp
mailer.SmtpServers.Add("smtp.host.com")
mailer.Connect()
Try
    ' Send HELP command.
    mailer.ExecuteCustomCommand("HELP\r\n")
    Console.WriteLine(mailer.GetServerResponse())
Catch e As MailBeeSmtpNegativeResponseException
    ' The given SMTP server does not support HELP command.
    Console.WriteLine(e.Message)
    Console.WriteLine("Server response is: " & mailer.GetServerResponse())
End Try
mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ExecuteCustomCommandAsync Method

SmtpExecuteCustomCommandAsync Method
async/await version of ExecuteCustomCommand(String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> ExecuteCustomCommandAsync(
    string commandString
)
Public Function ExecuteCustomCommandAsync (
    commandString As String
) As Task(Of Boolean)

Parameters

commandString
Type: SystemString
User-defined command text (including line terminator).

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the command was executed successfully; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetAcceptedRecipients Method

SmtpGetAcceptedRecipients Method
Returns the list of the recipients accepted by the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection GetAcceptedRecipients()
Public Function GetAcceptedRecipients As EmailAddressCollection

Return Value

Type: EmailAddressCollection
In "send to relay SMTP server" mode, returns the list of all recipients accepted by the SMTP server; in direct send mode (performing DNS MX lookup and sending to SMTP MX servers), returns the list of all recipients who received the message.
Remarks
This method is useful when refused recipients are allowed (AllowRefusedRecipients is true or direct send mode is used).
Note Note
Sucessful submitting the recipient to the server does not mean the server will really deliver the message to the recipient. It just means the server agreed to deliver the message, but it may fail to do so.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpServerAllowRefusedRecipients


Smtp.GetCurrentSmtpServerIndex Method

SmtpGetCurrentSmtpServerIndex Method
Returns SmtpServers collection's index of the server to which the component is connected or will connect on the next connection attempt.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetCurrentSmtpServerIndex()
Public Function GetCurrentSmtpServerIndex As Integer

Return Value

Type: Int32
If already connected to the SMTP relay server, the return value is the index of this server in SmtpServers collection; if not currently connected to the server, the return value is the index of the server to which the component will connect on the next connection attempt. The default value is 0.
Remarks
This property is useful when SmtpServers collection contains more than one SMTP relay server, and the application needs to know which one is used now or will be used when the time to connect to an SMTP server comes. If SmtpServers collection contains one or zero elements, this method will return 0.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetErrorDescription Method

SmtpGetErrorDescription Method
Returns a textual description of the last error.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetErrorDescription()
Public Function GetErrorDescription As String

Return Value

Type: String
A string value containing a textual description of the last error.
Remarks
Error descriptions can be localized or edited by deriving from Resources class.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetExtension Method

SmtpGetExtension Method
Returns the name or parameters of the specified ESMTP capability.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetExtension(
    string name
)
Public Function GetExtension (
    name As String
) As String

Parameters

name
Type: SystemString
The name of the capability. This name is case-insensitive, e.g. pipelining and PIPELINING mean the same.

Return Value

Type: String
If the specified capability is parameterless, the return value is the name of the capability itself. If the capability has parameters, the return value is a string which contains the parameters list as returned by the server. If the server does not support ESMTP (see GetExtensions for more information) or the given capability is not supported, the return value is a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
In order to use this method, the connection with the SMTP server must already be established, and Hello method already called.
Note Note
If the server does not support EHLO command (i.e. the server is not ESMTP enabled), the capabilities will not be available.
Examples
This sample displays whether the server supports ESMTP pipelining.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.domain.com");
mailer.Connect();
mailer.Hello();
string ext = mailer.GetExtension("pipelining");
if (ext == null)
{
    Console.WriteLine("The given server does not support ESMTP pipelining");
}
else
{
    Console.WriteLine("ESMTP Pipelining is supported");
}
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer = New Smtp
mailer.SmtpServers.Add("mail.domain.com")
mailer.Connect()
mailer.Hello()
Dim ext As String = mailer.GetExtension("pipelining")
If ext Is Nothing Then
    Console.WriteLine("The given server does not support ESMTP pipelining")
Else
    Console.WriteLine("ESMTP Pipelining is supported")
End If
mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetExtensions Method

SmtpGetExtensions Method
Returns a reference to the key-value list of the server capabilities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public StringDictionary GetExtensions()
Public Function GetExtensions As StringDictionary

Return Value

Type: StringDictionary
The key-value list of the server capabilities, or a null reference (Nothing in Visual Basic) if the capabilities list is not available.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
In order to use this method, the connection with the SMTP server must already be established, and Hello method already called.
Note Note
If the server does not support EHLO command (i.e. the server is not ESMTP enabled), the capabilities list will not be available.

In the returned StringDictionary, each key is a capability name (always lowercase). Its value is either empty string (if the capability has no parameters) or space-delimited list of the parameters.

Examples
This sample displays the list of all capabilities supported by the server.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.domain.com");
mailer.Connect();
mailer.Hello();
System.Collections.Specialized.StringDictionary caps = mailer.GetExtensions();
if (caps == null)
{
    Console.WriteLine("The given SMTP server does not support any ESMTP extensions");
}
else
{
    foreach (string cap in caps.Keys)
    {
        string val = caps[cap];
        if (val != string.Empty)
        {
            // Print capability name and parameters.
            Console.WriteLine(cap + " " + val);
        }
        else
        {
            // For parameterless capabilities, print capability name only.
            Console.WriteLine(cap);
        }
    }
}
mailer.Disconnect();

// The output (the actual content will be different for a particular mail server)
dsn
size
auth LOGIN PLAIN
ehlo
auth=login
starttls
help
pipelining

In the output above, only "auth" capability has parameters.
Note: auth=login is a single name, while "auth LOGIN PLAIN" denotes auth
capability having two parameters (LOGIN and PLAIN).
' To use the code below, import MailBee namespaces at the top of your code

Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class).
Dim mailer = New Smtp
mailer.SmtpServers.Add("mail.domain.com")
mailer.Connect()
mailer.Hello()
Dim caps As System.Collections.Specialized.StringDictionary = mailer.GetExtensions()
If caps Is Nothing Then
    Console.WriteLine("The given SMTP server does not support any ESMTP extensions")
Else
    For Each cap As String In caps.Keys
        Dim val As String = caps(cap)
        If (val <> String.Empty) Then
            ' Print capability name and parameters.
            Console.WriteLine(cap + " " + val)
        Else
            ' For parameterless capabilities, print capability name only.
            Console.WriteLine(cap)
        End If
    Next
End If
mailer.Disconnect()

' The output (the actual content will be different for a particular mail server)
dsn
size
auth LOGIN PLAIN
ehlo
auth=login
starttls
help
pipelining

In the output above, only "auth" capability has parameters.
Note: auth=login is a single name, while "auth LOGIN PLAIN" denotes auth
capability having two parameters (LOGIN and PLAIN).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetExtensionValue Method

SmtpGetExtensionValue Method
Returns the parameters of the specified ESMTP capability, or an empty string if the capability has no parameters.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetExtensionValue(
    string name
)
Public Function GetExtensionValue (
    name As String
) As String

Parameters

name
Type: SystemString
The name of the capability. This name is case-insensitive, e.g. pipelining and PIPELINING mean the same.

Return Value

Type: String
If the specified capability is parameterless, the return value is Empty. If the capability has parameters, the return value is a string which contains the parameters list as returned by the server. If the server does not support ESMTP (see GetExtensions for more information) or the given capability is not supported, the return value is a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

In order to use this method, the connection with the SMTP server must already be established, and Hello method already called.

This method can be used to retrieve additional information about the given capability. However, if you wish to get the list of SASL authentication methods supported by the server, you may also use GetSupportedAuthMethods method for this.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetMaxMessageSize Method

SmtpGetMaxMessageSize Method
Returns the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetMaxMessageSize()
Public Function GetMaxMessageSize As Integer

Return Value

Type: Int32
If the server restricts the maximum message size and supports ESMTP SIZE extension, the return value is the maximum length of the message (in bytes) which is allowed by the SMTP server in order to accept the message from the client; otherwise, the return value is 0.
Remarks
This property value is obtained from the server capabilities list which is received from the server during initial greeting (Hello method). Thus, the application must be already connected to the server and Hello method already called in order to use GetMaxMessageSize method. Even then, this method will still return zero if ESMTP SIZE extension is not supported by the server.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetExtensions
SmtpGetExtensionValue(String)


Smtp.GetMXHosts Method

SmtpGetMXHosts Method
Retrieves the list of hosts willing to accept mail for the given domain.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GetMXHosts(
    string domain
)
Public Function GetMXHosts (
    domain As String
) As String()

Parameters

domain
Type: SystemString
The domain to get the list of MX hosts for.

Return Value

Type: String
The array of string names of hosts willing to accept mail for the given domain, or LocalSmtpMXServerName if domain is an empty string, or a null reference (Nothing in Visual Basic) if an error occurred.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | domain is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method makes DNS MX query to the servers listed in DnsServers collection regarding domain. The method will return the domain name itself if the DNS query reports the given domain contains A record only (i.e. the given domain is willing to accept mail for itself). MX records are returned accordingly their priorities (higher priority listed first).
Examples
This sample retrieves the list of DNS MX server names accepting mail for "hotmail.com" domain.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        mailer.DnsServers.Autodetect();
        string[] hosts = mailer.GetMXHosts("hotmail.com");
        foreach (string host in hosts)
        {
            Console.WriteLine(host);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp
        mailer.DnsServers.Autodetect()
        Dim hosts() As String = mailer.GetMXHosts("hotmail.com")
        Dim host As String
        For Each host In hosts
            Console.WriteLine(host)
        Next
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetTxtData(String)


Smtp.GetMXHostsAsync Method

SmtpGetMXHostsAsync Method
async/await version of GetMXHosts(String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string[]> GetMXHostsAsync(
    string domain
)
Public Function GetMXHostsAsync (
    domain As String
) As Task(Of String())

Parameters

domain
Type: SystemString
The domain to get the list of MX hosts for.

Return Value

Type: Task String
A task that represents the asynchronous operation. The value of TResult parameter is the array of string names of hosts willing to accept mail for the given domain, or LocalSmtpMXServerName if domain is an empty string, or a null reference (Nothing in Visual Basic) if an error occurred.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | domain is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetPtrData Method

SmtpGetPtrData Method
Retrieves the list of domain names for the specified IP address.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GetPtrData(
    string ipString
)
Public Function GetPtrData (
    ipString As String
) As String()

Parameters

ipString
Type: SystemString
The IP address string.

Return Value

Type: String
The array of strings taken from DNS PTR data for the specified IP address, or a null reference (Nothing in Visual Basic) if an error occurred or no PTR record found for the given domain.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | ipString is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method makes DNS PTR query (reverse DNS query) to the servers listed in DnsServers collection regarding ipString address.

Popular anti-spam check is making reverse DNS query for the IP address from which the mail message was sent. Then, the retured domain name is compared with the domain name from "From:" or "Return-Path:" address to make sure it was really sent from that domain.

Note Note
If the IP address has multiple domain names associated with it, PTR record will usually return only the domain name taken from A record. Other domain names are aliases (CNAMEs). They will not be returned as their information is not contained in PTR records.
Examples
This sample retrieves domain names associated with an IP address. Make sure to specify real IP address prior to running this sample.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        mailer.DnsServers.Autodetect();
        string[] domains = mailer.GetPtrData("123.123.123.123");
        foreach (string domain in domains)
        {
            Console.WriteLine(domain);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp
        mailer.DnsServers.Autodetect()
        Dim domains() As String = mailer.GetPtrData("123.123.123.123")
        Dim domain As String
        For Each domain In domains
            Console.WriteLine(domain)
        Next
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetMXHosts(String)
SmtpGetTxtData(String)


Smtp.GetPtrDataAsync Method

SmtpGetPtrDataAsync Method
async/await version of GetPtrData(String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string[]> GetPtrDataAsync(
    string ipString
)
Public Function GetPtrDataAsync (
    ipString As String
) As Task(Of String())

Parameters

ipString
Type: SystemString
The IP address string.

Return Value

Type: Task String
A task that represents the asynchronous operation. The value of TResult parameter is the array of strings taken from DNS PTR data for the specified IP address, or a null reference (Nothing in Visual Basic) if an error occurred or no PTR record found for the given domain.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | ipString is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetRefusedRecipients Method

SmtpGetRefusedRecipients Method
Returns the list of the recipients rejected by the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection GetRefusedRecipients()
Public Function GetRefusedRecipients As EmailAddressCollection

Return Value

Type: EmailAddressCollection
In "send to relay SMTP server" mode, returns the list of the recipients rejected by the SMTP server; in direct send mode (performing DNS MX lookup and sending to SMTP MX servers), returns the list of all recipients who did not receive the message.
Remarks
If refused recipients were not allowed in send to relay SMTP server mode (AllowRefusedRecipients is false), the component will throw an exception after the refused recipient was encountered. It means the recipients which reside in the recipients list beyond the position of the refused recipient will not appear in GetAcceptedRecipients and GetRefusedRecipients collections.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpServerAllowRefusedRecipients


Smtp.GetServerResponse Method

SmtpGetServerResponse Method
Returns the last response from the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string GetServerResponse()
Public Function GetServerResponse As String

Return Value

Type: String
A string value which contains the last response from the server, or a null reference (Nothing in Visual Basic) if not connected to the server.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetServerResponseCode Method

SmtpGetServerResponseCode Method
Returns an integer value containing the status code of the last SMTP operation.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetServerResponseCode()
Public Function GetServerResponseCode As Integer

Return Value

Type: Int32
3-digit integer value (such as 220) containing the SMTP status code taken from the last received response from the server.
Remarks
The developer can use this value for advanced use of Smtp component (such as sophisticated error handling).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetServerResponse


Smtp.GetSocket Method

SmtpGetSocket Method
Returns the underlying Socket MailBee uses for the current SMTP connection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Socket GetSocket()
Public Function GetSocket As Socket

Return Value

Type: Socket
A reference to the underlying Socket MailBee uses for the current network connection, or a null reference if there is no active connection.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
Remarks
In case of UWP edition, this method returns StreamSocket instead.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetSocketError Method

SmtpGetSocketError Method
Returns a Win32 error code of the last socket-related error.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int GetSocketError()
Public Function GetSocketError As Integer

Return Value

Type: Int32
An integer value containing the last socket-related error code, or 0 if there is no error.
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
Remarks
This error code is obtained from NativeErrorCode.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetStream Method

SmtpGetStream Method
Returns the underlying Stream MailBee uses for the current network connection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Stream GetStream()
Public Function GetStream As Stream

Return Value

Type: Stream
A reference to the underlying Stream MailBee uses for the current network connection, or a null reference (Nothing in Visual Basic) if there is no active connection.
Remarks
Typically this will be an instance of a class inherited from NetworkStream or SslStream.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.GetSupportedAuthMethods Method

SmtpGetSupportedAuthMethods Method
Returns a set of flags indicating which authentication methods are supported by the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods GetSupportedAuthMethods()
Public Function GetSupportedAuthMethods As AuthenticationMethods

Return Value

Type: AuthenticationMethods
A set of flags indicating which authentication methods are supported by the server, or None if Hello method has not yet been called or if the server does not support EHLO command (i.e. the server is not ESMTP enabled).
Exceptions
Exception | Condition
MailBeeInvalidStateException | There are multiple or non-SMTP connections being opened at the moment (IsSmtpContext is false).
Examples
This sample lists all authentication methods supported by the SMTP server. SMTP servers do not support non-SASL methods, thus only SASL methods are checked.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.domain.com");
mailer.Connect();
mailer.Hello();

AuthenticationMethods methods = mailer.GetSupportedAuthMethods();
if ( (methods & AuthenticationMethods.SaslLogin) > 0)
{
    Console.WriteLine("SASL LOGIN");
}
if ( (methods & AuthenticationMethods.SaslPlain) > 0)
{
    Console.WriteLine("SASL PLAIN");
}
if ( (methods & AuthenticationMethods.SaslCramMD5) > 0)
{
    Console.WriteLine("SASL CRAM-MD5 (secure)");
}

mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer = New Smtp
mailer.SmtpServers.Add("mail.domain.com")
mailer.Connect()
mailer.Hello()

Dim methods As AuthenticationMethods = mailer.GetSupportedAuthMethods()
If ((methods And AuthenticationMethods.SaslLogin) > 0) Then
    Console.WriteLine("SASL LOGIN")
End If
If ((methods And AuthenticationMethods.SaslPlain) > 0) Then
    Console.WriteLine("SASL PLAIN")
End If
If ((methods And AuthenticationMethods.SaslCramMD5) > 0) Then
    Console.WriteLine("SASL CRAM-MD5 (secure)")
End If

mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetExtensions


Smtp.GetTxtData Method

SmtpGetTxtData Method
Retrieves the list of TXT strings of DNS data of the specified domain.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string[] GetTxtData(
    string domain
)
Public Function GetTxtData (
    domain As String
) As String()

Parameters

domain
Type: SystemString
The domain to get the list of MX hosts for.

Return Value

Type: String
The array of strings taken from DNS TXT data of the specified domain, or a null reference (Nothing in Visual Basic) if an error occurred or no TXT record found for the given domain.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | domain is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method makes DNS TXT query to the servers listed in DnsServers collection regarding domain. The method supports multiple strings per TXT record and multiple TXT records per domain. If multiple TXT records are returned, their arrays of strings are concatenated into single array.

TXT records contain important DNS information used by various antispam techniques like SPF and DomainKeys (DKIM).

Examples
This sample retrieves TXT information for "gmail.com" domain.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        mailer.DnsServers.Autodetect();
        string[] strings = mailer.GetTxtData("gmail.com");
        foreach (string str in strings)
        {
            Console.WriteLine(str);
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp
        mailer.DnsServers.Autodetect()
        Dim strings() As String = mailer.GetTxtData("gmail.com")
        Dim str As String
        For Each str In strings
            Console.WriteLine(str)
        Next
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetMXHosts(String)
SmtpGetPtrData(String)


Smtp.GetTxtDataAsync Method

SmtpGetTxtDataAsync Method
async/await version of GetTxtData(String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string[]> GetTxtDataAsync(
    string domain
)
Public Function GetTxtDataAsync (
    domain As String
) As Task(Of String())

Parameters

domain
Type: SystemString
The domain to get the list of MX hosts for.

Return Value

Type: Task String
A task that represents the asynchronous operation. The value of TResult parameter is the array of strings taken from DNS TXT data of the specified domain, or a null reference (Nothing in Visual Basic) if an error occurred or no TXT record found for the given domain.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | domain is a null reference (Nothing in Visual Basic).
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Hello Method

SmtpHello Method
Sends initial greeting to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Hello()
Public Function Hello As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Sends EHLO or HELO command to the server. This command must be issued immediately after the connection was established.

EHLO/HELO command has a parameter which should the domain name of the host which will send mail. By default, MailBee uses either the IPv4 address of the current machine or the local host name if IPv4 address is not available. Usually, this behavior does not need to be changed. However, if the application logic requires the default behavior to be overridden, the developer can force any arbitrary string to be used as a parameter of HELO/EHLO command by setting HelloDomain property of the server which is already in SmtpServers collection, or by using Add(SmtpServer) method to add new server into the collection.

By default, the component sends EHLO command, which is an extended version of HELO command. An ESMTP-enabled server returns the list of server capabilities in reply to EHLO command. However, if the server does not support any ESMTP extensions, it will return an error. In this case, the component will try HELO command. However, the list of the server capabilities will not be available, and GetExtensions will return a null reference (Nothing in Visual Basic).

If the application knows the server it uses does not support ESMTP, it can disable EHLO (so that HELO will be used) by setting SmtpOptions to ClassicSmtpMode.

In case if you connected to port 587, MailBee will by default (if AutodetectPortAndSslMode is true) also try to switch the connection to TLS (if the server supports it). A separate StartTls call is not required.

Examples
This sample connects to the SMTP server, sends greeting, and prints the response received form the server into console.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("smtp.domain.com");
mailer.Connect();
mailer.Hello();
Console.WriteLine(mailer.GetServerResponse());
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp
mailer.SmtpServers.Add("smtp.domain.com")
mailer.Connect()
mailer.Hello()
Console.WriteLine(mailer.GetServerResponse())
mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpGetExtensions


Smtp.HelloAsync Method

SmtpHelloAsync Method
async/await version of Hello.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> HelloAsync()
Public Function HelloAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Login Method

SmtpLogin Method
Authenticates the user on the SMTP server if ESMTP authentication is enabled.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Login()
Public Function Login As Boolean

Return Value

Type: Boolean
true if the method succeeds, ESMTP authentication was disabled, or IgnoreLoginFailure is true; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

By default, this method does nothing because authentication is optional in SMTP/ESMTP.

If ESMTP auhtentication is enabled (AuthMethods is not None), this method will attempt to authenticate on the SMTP server using the best (most secure) authentication method specified in AuthMethods value and supported by the server.

If the login attempt fails, it might still be possible to send mail (with some restrictions, such as sending to local recipients only). Due to this, MailBee makes it possible to ignore authentication errors if IgnoreLoginFailure is set to true. ErrorOccurred warning event, however, will still be issued to let the application know about the problem.

Note Note
Another alternative to Login method is using POP-before-SMTP authentication. It can be used if the mail server does not support ESMTP authentication, but still requires users to authnticate themselves in order to send mail. See AuthPopBeforeSmtp(String, Int32, String, String) method documentation for more information.

For examples on using OAuth 2.0 authentication (XOAUTH2 in Gmail), see OAuth2 topic.

Examples
This sample connects to the SMTP server, sends greeting, and attempts to authenticate the user on the server. If the login fails, no exception is thrown (IgnoreLoginFailure is set to true) but the application still gets notification about the login failure through handling ErrorOccurred event).
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        if (e.Reason is IMailBeeLoginException)
        {
            Console.WriteLine(e.Reason.Message); // Login error.
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server and authentication settings.
        // This constructor also sets server.AuthMethods = AuthenticationMethods.Auto
        SmtpServer server = new SmtpServer("smtp.somedomain.com", "jdoe", "badpassword");
        server.IgnoreLoginFailure = true;
        mailer.SmtpServers.Add(server);

        // Subscribe to the ErrorOccurred event.
        mailer.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        mailer.Connect();
        mailer.Hello();

        // Authenticate the user "jdoe".
        mailer.Login();

        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' ErrorOccurred event handler.
    Private Shared Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        If (TypeOf e.Reason Is IMailBeeLoginException) Then
            Console.WriteLine(e.Reason.Message) ' Login error.
        End If
    End Sub

    ' The actual code.
    Shared Sub Main()
        Dim mailer As New Smtp

        ' Specify SMTP server and authentication settings.
        ' This constructor also sets server.AuthMethods = AuthenticationMethods.Auto
        Dim server As New SmtpServer("smtp.somedomain.com", "jdoe", "badpassword")
        server.IgnoreLoginFailure = True
        mailer.SmtpServers.Add(server)

        ' Subscribe to the ErrorOccurred event.
        AddHandler mailer.ErrorOccurred, AddressOf OnErrorOccurred

        mailer.Connect()
        mailer.Hello()

        ' Authenticate the user "jdoe".
        mailer.Login()

        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpAuthPopBeforeSmtp(String, Int32, String, String)


Smtp.LoginAsync Method

SmtpLoginAsync Method
async/await version of Login.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> LoginAsync()
Public Function LoginAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds, ESMTP authentication was disabled, or IgnoreLoginFailure is true; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Noop Method

SmtpNoop Method
Sends a NOOP command to the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Noop()
Public Function Noop As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method is useful for keeping the connection alive when there is no real activity.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.NoopAsync Method

SmtpNoopAsync Method
async/await version of Noop.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> NoopAsync()
Public Function NoopAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.OnConnected Method

SmtpOnConnected Method
Used by MailBee to raise Connected event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnConnected(
    ConnectedEventArgs args
)
Protected Sub OnConnected (
    args As ConnectedEventArgs
)

Parameters

args
Type: MailBeeConnectedEventArgs
The object containing event data.
Remarks

When RaiseEventsViaMessageLoop is true (i.e. default value), MailBee uses this method to raise Connected event. In WinForms application, the event will be raised on the message loop thread. In other applications (such as web or console applications), threading is not a concern, and the current thread MailBee is running on will be used.

You can override this method in a derived class to force MailBee execute your own code instead of raising Connected event. This may help to avoid threading issues in WinForms applications (because events may not be raised if the message loop thread is blocked for some reason, while calling overridden methods does not depend on the message loop thread state).

Another solution of this problem is setting RaiseEventsViaMessageLoop to false and using Wait method to block the message loop thread if needed. This way, you do not need to derive any descendant class from Smtp class.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpConnected
SmtpRaiseEventsViaMessageLoop


Smtp.OnDataReceived Method

SmtpOnDataReceived Method
Used by MailBee to raise DataReceived event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDataReceived
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnDataSent Method

SmtpOnDataSent Method
Used by MailBee to raise DataSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDataSent(
    DataTransferEventArgs args
)
Protected Sub OnDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDataSent
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnDisconnected Method

SmtpOnDisconnected Method
Used by MailBee to raise Disconnected event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnDisconnected(
    DisconnectedEventArgs args
)
Protected Sub OnDisconnected (
    args As DisconnectedEventArgs
)

Parameters

args
Type: MailBeeDisconnectedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDisconnected
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnErrorOccurred Method

SmtpOnErrorOccurred Method
Used by MailBee to raise ErrorOccurred event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnErrorOccurred(
    ErrorEventArgs args
)
Protected Sub OnErrorOccurred (
    args As ErrorEventArgs
)

Parameters

args
Type: MailBeeErrorEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpErrorOccurred
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnFinishingJob Method

SmtpOnFinishingJob Method
Used by MailBee to raise FinishingJob event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnFinishingJob(
    SmtpFinishingJobEventArgs args
)
Protected Sub OnFinishingJob (
    args As SmtpFinishingJobEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpFinishingJobEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpFinishingJob
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnHostResolved Method

SmtpOnHostResolved Method
Used by MailBee to raise HostResolved event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnHostResolved(
    HostResolvedEventArgs args
)
Protected Sub OnHostResolved (
    args As HostResolvedEventArgs
)

Parameters

args
Type: MailBeeHostResolvedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpHostResolved
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnLoggedIn Method

SmtpOnLoggedIn Method
Used by MailBee to raise LoggedIn event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLoggedIn(
    LoggedInEventArgs args
)
Protected Sub OnLoggedIn (
    args As LoggedInEventArgs
)

Parameters

args
Type: MailBeeLoggedInEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLoggedIn
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnLogNewEntry Method

SmtpOnLogNewEntry Method
Used by MailBee to raise LogNewEntry event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLogNewEntry(
    LogNewEntryEventArgs args
)
Protected Sub OnLogNewEntry (
    args As LogNewEntryEventArgs
)

Parameters

args
Type: MailBeeLogNewEntryEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLogNewEntry
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnLowLevelDataReceived Method

SmtpOnLowLevelDataReceived Method
Used by MailBee to raise LowLevelDataReceived event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLowLevelDataReceived(
    DataTransferEventArgs args
)
Protected Sub OnLowLevelDataReceived (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLowLevelDataReceived
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnLowLevelDataSent Method

SmtpOnLowLevelDataSent Method
Used by MailBee to raise LowLevelDataSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnLowLevelDataSent(
    DataTransferEventArgs args
)
Protected Sub OnLowLevelDataSent (
    args As DataTransferEventArgs
)

Parameters

args
Type: MailBeeDataTransferEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLowLevelDataSent
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMergingMessage Method

SmtpOnMergingMessage Method
Used by MailBee to raise MergingMessage event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMergingMessage(
    SmtpMergingMessageEventArgs args
)
Protected Sub OnMergingMessage (
    args As SmtpMergingMessageEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMergingMessageEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMergingMessage
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageDataChunkSent Method

SmtpOnMessageDataChunkSent Method
Used by MailBee to raise MessageDataChunkSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageDataChunkSent(
    SmtpMessageDataChunkSentEventArgs args
)
Protected Sub OnMessageDataChunkSent (
    args As SmtpMessageDataChunkSentEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageDataChunkSentEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageDataChunkSent
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageDirectSendDone Method

SmtpOnMessageDirectSendDone Method
Used by MailBee to raise MessageDirectSendDone event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageDirectSendDone(
    SmtpMessageDirectSendDoneEventArgs args
)
Protected Sub OnMessageDirectSendDone (
    args As SmtpMessageDirectSendDoneEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageDirectSendDoneEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageDirectSendDone
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageMXLookupDone Method

SmtpOnMessageMXLookupDone Method
Used by MailBee to raise MessageMXLookupDone event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageMXLookupDone(
    SmtpMessageMXLookupDoneEventArgs args
)
Protected Sub OnMessageMXLookupDone (
    args As SmtpMessageMXLookupDoneEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageMXLookupDoneEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageMXLookupDone
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageNotSent Method

SmtpOnMessageNotSent Method
Used by MailBee to raise MessageNotSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageNotSent(
    SmtpMessageNotSentEventArgs args
)
Protected Sub OnMessageNotSent (
    args As SmtpMessageNotSentEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageNotSentEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageNotSent
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageRecipientSubmitted Method

SmtpOnMessageRecipientSubmitted Method
Used by MailBee to raise MessageRecipientSubmitted event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageRecipientSubmitted(
    SmtpMessageRecipientSubmittedEventArgs args
)
Protected Sub OnMessageRecipientSubmitted (
    args As SmtpMessageRecipientSubmittedEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageRecipientSubmittedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageRecipientSubmitted
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageSenderSubmitted Method

SmtpOnMessageSenderSubmitted Method
Used by MailBee to raise MessageSenderSubmitted event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageSenderSubmitted(
    SmtpMessageSenderSubmittedEventArgs args
)
Protected Sub OnMessageSenderSubmitted (
    args As SmtpMessageSenderSubmittedEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageSenderSubmittedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageSenderSubmitted
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageSent Method

SmtpOnMessageSent Method
Used by MailBee to raise MessageSent event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageSent(
    SmtpMessageSentEventArgs args
)
Protected Sub OnMessageSent (
    args As SmtpMessageSentEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageSentEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageSent
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageSubmittedToPickupFolder Method

SmtpOnMessageSubmittedToPickupFolder Method
Used by MailBee to raise MessageSubmittedToPickupFolder event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageSubmittedToPickupFolder(
    SmtpMessageSubmittedToPickupFolderEventArgs args
)
Protected Sub OnMessageSubmittedToPickupFolder (
    args As SmtpMessageSubmittedToPickupFolderEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageSubmittedToPickupFolderEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageSubmittedToPickupFolder
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnMessageSubmittedToServer Method

SmtpOnMessageSubmittedToServer Method
Used by MailBee to raise MessageSubmittedToServer event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnMessageSubmittedToServer(
    SmtpMessageSubmittedToServerEventArgs args
)
Protected Sub OnMessageSubmittedToServer (
    args As SmtpMessageSubmittedToServerEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpMessageSubmittedToServerEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageSubmittedToServer
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnSendingMessage Method

SmtpOnSendingMessage Method
Used by MailBee to raise SendingMessage event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSendingMessage(
    SmtpSendingMessageEventArgs args
)
Protected Sub OnSendingMessage (
    args As SmtpSendingMessageEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpSendingMessageEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSendingMessage
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnSocketConnected Method

SmtpOnSocketConnected Method
Used by MailBee to raise SocketConnected event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSocketConnected(
    SocketConnectedEventArgs args
)
Protected Sub OnSocketConnected (
    args As SocketConnectedEventArgs
)

Parameters

args
Type: MailBeeSocketConnectedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSocketConnected
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnSocketCreating Method

SmtpOnSocketCreating Method
Used by MailBee to raise SocketCreating event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSocketCreating(
    SocketCreatingEventArgs args
)
Protected Sub OnSocketCreating (
    args As SocketCreatingEventArgs
)

Parameters

args
Type: MailBeeSocketCreatingEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSocketCreating
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnSubmittingMessageToPickupFolder Method

SmtpOnSubmittingMessageToPickupFolder Method
Used by MailBee to raise SubmittingMessageToPickupFolder event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnSubmittingMessageToPickupFolder(
    SmtpSubmittingMessageToPickupFolderEventArgs args
)
Protected Sub OnSubmittingMessageToPickupFolder (
    args As SmtpSubmittingMessageToPickupFolderEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpSubmittingMessageToPickupFolderEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSubmittingMessageToPickupFolder
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnTlsStarted Method

SmtpOnTlsStarted Method
Used by MailBee to raise TlsStarted event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnTlsStarted(
    TlsStartedEventArgs args
)
Protected Sub OnTlsStarted (
    args As TlsStartedEventArgs
)

Parameters

args
Type: MailBeeTlsStartedEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpTlsStarted
SmtpOnConnected(ConnectedEventArgs)


Smtp.OnTransientErrorOccurred Method

SmtpOnTransientErrorOccurred Method
Used by MailBee to raise TransientErrorOccurred event.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected void OnTransientErrorOccurred(
    SmtpTransientErrorOccurredEventArgs args
)
Protected Sub OnTransientErrorOccurred (
    args As SmtpTransientErrorOccurredEventArgs
)

Parameters

args
Type: MailBee.SmtpMailSmtpTransientErrorOccurredEventArgs
The object containing event data.
Remarks
See OnConnected(ConnectedEventArgs) method documentation on more information regarding OnEventName methods in MailBee.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpOnConnected(ConnectedEventArgs)


Smtp.QuickSend Method

SmtpQuickSend Method
Overload List
Name | Description
QuickSend(MailMessage) | Sends a mail message, in a single line of code.
QuickSend(String, String, String, String) | Sends a mail message, in a single line of code.
QuickSend(String, String, String, String, String, String, String) | Sends a mail message, in a single line of code.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.QuickSend Method (MailMessage)

SmtpQuickSend Method (MailMessage)
Sends a mail message, in a single line of code.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static void QuickSend(
    MailMessage message
)
Public Shared Sub QuickSend (
    message As MailMessage
)

Parameters

message
Type: MailBee.MimeMailMessage
The MailMessage object representing the mail message to be sent.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method allows the developer to send a mail message without needing to create an instance of Smtp component.

The message will be sent in direct send mode. MailBee will discover SMTP servers of recipients domains via DNS MX lookup, and then send the message directly to these SMTP MX servers. No dedicated SMTP relay server is used.

DNS servers for MX lookup are taken either from the config file (such as app.config, web.config, or machine.config) or from operating system settings if the config file contains no DNS server definitions. See Autodetect method for more information.

Note Note
Although this method is static, it still requires valid license key be assigned to the Smtp class. The developer can set the key either in the config file or in the code (by setting MailBee.Global.LicenseKey property value).

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like SendAsync(String, EmailAddressCollection).

Examples
This sample creates a simple plain-text mail message and then sends it.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

// Prepare the message.
MailMessage msg = new MailMessage();
msg.From.AsString = "John Doe <jdoe@domain.com>";
msg.To.AsString = "Kathy Smith <kathy.smith@company.com>";
msg.Subject = "Meeting request";
msg.BodyPlainText = "Hi Kathy,\r\nCan we meet tomorrow?\r\nRegards, John";

// Send it.
Smtp.QuickSend(msg);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

' Prepare the message.
Dim msg As New MailMessage
msg.From.AsString = "John Doe <jdoe@domain.com>"
msg.To.AsString = "Kathy Smith <kathy.smith@company.com>"
msg.Subject = "Meeting request"
msg.BodyPlainText = "Hi Kathy,\r\nCan we meet tomorrow?\r\nRegards, John"

' Send it.
Smtp.QuickSend(msg)
See Also

Reference

Smtp Class
QuickSend Overload
MailBee.SmtpMail Namespace
SmtpSend


Smtp.QuickSend Method (String, String, String, String)

SmtpQuickSend Method (String, String, String, String)
Sends a mail message, in a single line of code.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static void QuickSend(
    string from,
    string to,
    string subject,
    string body
)
Public Shared Sub QuickSend (
    from As String,
    to As String,
    subject As String,
    body As String
)

Parameters

from
Type: SystemString
The string containing the sender e-mail address.
to
Type: SystemString
The comma-separated list of the message recipients.
subject
Type: SystemString
The subject of the message.
body
Type: SystemString
The message body as plain-text.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method allows the developer to send a mail message without needing to create an instances of Smtp component and MailMessage class.

The message will be sent in direct send mode. MailBee will discover SMTP servers of recipients domains via DNS MX lookup, and then send the message directly to these SMTP MX servers. No dedicated SMTP relay server is used.

DNS servers for MX lookup are taken either from the config file (such as app.config, web.config, or machine.config) or from operating system settings if the config file contains no DNS server definitions. See Autodetect method for more information.

Note Note
Although this method is static, it still requires valid license key be assigned to the Smtp class. The developer can set the key either in the config file or in the code (by setting MailBee.Global.LicenseKey property value).

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like SendAsync(String, EmailAddressCollection).

Examples
This sample composes and sends a plain-text message in a single line of code.
C#
VB
Copy
MailBee.SmtpMail.Smtp.QuickSend("joe@me.com", "bill@you.com", "Hello", "Simple message");
MailBee.SmtpMail.Smtp.QuickSend("joe@me.com", "bill@you.com", "Hello", "Simple message")
See Also

Reference

Smtp Class
QuickSend Overload
MailBee.SmtpMail Namespace
SmtpSend


Smtp.QuickSend Method (String, String, String, String, String, String, String)

SmtpQuickSend Method (String, String, String, String, String, String, String)
Sends a mail message, in a single line of code.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static void QuickSend(
    string from,
    string to,
    string subject,
    string plainTextBody,
    string htmlBody,
    string charset,
    string attachmentFilename
)
Public Shared Sub QuickSend (
    from As String,
    to As String,
    subject As String,
    plainTextBody As String,
    htmlBody As String,
    charset As String,
    attachmentFilename As String
)

Parameters

from
Type: SystemString
The string containing the sender e-mail address.
to
Type: SystemString
The comma-separated list of the message recipients.
subject
Type: SystemString
The subject of the message.
plainTextBody
Type: SystemString
The plain-text version of the message body, or a null reference (Nothing in Visual Basic) if the message should not contain the plain-text body.
htmlBody
Type: SystemString
The HTML version of the message body, or a null reference (Nothing in visual Basic) if the message should not contain the HTML body.
charset
Type: SystemString
The charset the message is composed in, or a null reference (Nothing in Visual Basic) if the message should not contain any charset setting.
attachmentFilename
Type: SystemString
The full path and filename of the file to be attached to the message, or a null reference (Nothing in Visual Basic) if no attachment is required.
Exceptions
Exception | Condition
MailBeeException | An error occurred.
Remarks

This method allows the developer to send a mail message without needing to create an instances of Smtp component and MailMessage class.

The message will be sent in direct send mode. MailBee will discover SMTP servers of recipients domains via DNS MX lookup, and then send the message directly to these SMTP MX servers. No dedicated SMTP relay server is used.

DNS servers for MX lookup are taken either from the config file (such as app.config, web.config, or machine.config) or from operating system settings if the config file contains no DNS server definitions. See Autodetect method for more information.

Note Note
Although this method is static, it still requires valid license key be assigned to the Smtp class. The developer can set the key either in the config file or in the code (by setting MailBee.Global.LicenseKey property value).

This method is not async, it's recommended (and in case of UWP platform it's mandatory) to use sync methods like SendAsync(String, EmailAddressCollection).

Examples
This sample composes and sends an HTML mail message with an attachment in a single line of code.
C#
VB
Copy
MailBee.SmtpMail.Smtp.QuickSend("John Doe <jdoe@domain.com>",
    "Kathy Smith <kathy.smith@company.com>", "The requested document", null,
    "<html>Please find the report in the attached document</html>", null,
    @"C:\My Documents\report.doc");
MailBee.SmtpMail.Smtp.QuickSend("John Doe <jdoe@domain.com>", _
    "Kathy Smith <kathy.smith@company.com>", "The requested document", Nothing, _
    "<html>Please find the report in the attached document</html>", Nothing, _
    "C:\My Documents\report.doc")
See Also

Reference

Smtp Class
QuickSend Overload
MailBee.SmtpMail Namespace
SmtpSend


Smtp.RelayFromEmlFile Method

SmtpRelayFromEmlFile Method
Overload List
Name | Description
RelayFromEmlFile(String, String, EmailAddressCollection) | Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.
RelayFromEmlFile(String, String, String) | Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.RelayFromEmlFile Method (String, String, EmailAddressCollection)

SmtpRelayFromEmlFile Method (String, String, EmailAddressCollection)
Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RelayFromEmlFile(
    string filename,
    string senderEmail,
    EmailAddressCollection recipients
)
Public Function RelayFromEmlFile (
    filename As String,
    senderEmail As String,
    recipients As EmailAddressCollection
) As Boolean

Parameters

filename
Type: SystemString
The path to the file containing the message source in .EML (RFC2822) format.
senderEmail
Type: SystemString
The e-mail address of the sender.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients.

Return Value

Type: Boolean
true if relay succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method reads the message raw data from a file and then sends the message intact. Sender and recipients specified in the message itself (such as From: and To: fields) are ignored.

To save a message into an .EML file, SaveMessage(String) method of MailMessage object can be used.

Note Note
If Connect method was not called prior to RelayFromEmlFile(String, String, EmailAddressCollection), MailBee will call it automatically, or send the message in direct send mode (through DNS MX lookup) if no SMTP relay server is specified in SmtpServers collection or its Priority is lower than top priority of DNS servers available in DnsServers collection.
Examples
This sample relays the mail message from .EML file to the recipients, using the following configuration (which targets high reliability of send mail operation):
  1. Attempt to send to SMTP relay server at smtp1.domain.com first
  2. If this fails, try to send to backup SMTP relay server at smtp2.domain.com
  3. If this fails too, try direct send mode. To discover SMTP servers accepting mails for recipients domains (i.e. to perform DNS MX lookup), use DNS servers specified by the operating system
  4. If the DNS servers reported by OS are not available or down, use backup DNS server at 10.20.30.40
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

mailer.SmtpServers.Add("smtp1.domain.com", 25, 0);    // top priority.
mailer.SmtpServers.Add("smtp2.domain.com", 25, 1);    // low priority.

// Auto-detect DNS servers from OS settings or config file.
mailer.DnsServers.Autodetect();

// Add backup DNS server of low priority (priority of DNS servers
// registered in OS is usually in the range 0 to 10).
mailer.DnsServers.Add("10.20.30.40", 100);

// Send the message from the file.
mailer.RelayFromEmlFile(@"C:\Temp\message.eml", "from@domain.com",
    new EmailAddressCollection("to@company.com"));
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

mailer.SmtpServers.Add("smtp1.domain.com", 25, 0)    ' top priority.
mailer.SmtpServers.Add("smtp2.domain.com", 25, 1)    ' low priority.

' Auto-detect DNS servers from OS settings or config file.
mailer.DnsServers.Autodetect()

' Add backup DNS server of low priority (priority of DNS servers
' registered in OS is usually in the range 0 to 10).
mailer.DnsServers.Add("10.20.30.40", 100)

' Send the message from the file.
mailer.RelayFromEmlFile("C:\Temp\message.eml", "from@domain.com", _
    New EmailAddressCollection("to@company.com"))
See Also

Reference

Smtp Class
RelayFromEmlFile Overload
MailBee.SmtpMail Namespace


Smtp.RelayFromEmlFile Method (String, String, String)

SmtpRelayFromEmlFile Method (String, String, String)
Relays (sends without any modifications) the mail message previously saved as an .EML file, to the specified recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RelayFromEmlFile(
    string filename,
    string senderEmail,
    string recipientEmails
)
Public Function RelayFromEmlFile (
    filename As String,
    senderEmail As String,
    recipientEmails As String
) As Boolean

Parameters

filename
Type: SystemString
The path to the file containing the message source in .EML (RFC2822) format.
senderEmail
Type: SystemString
The e-mail address of the sender.
recipientEmails
Type: SystemString
The comma-delimited list of the message recipients.

Return Value

Type: Boolean
true if relay succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method reads the message raw data from a file and then sends the message intact. Sender and recipients specified in the message itself (such as From: and To: fields) are ignored.

To save a message into an .EML file, SaveMessage(String) method of MailMessage object can be used.

Note Note
If Connect method was not called prior to RelayFromEmlFile(String, String, EmailAddressCollection), MailBee will call it automatically, or send the message in direct send mode (through DNS MX lookup) if no SMTP relay server is specified in SmtpServers collection or its Priority is lower than top priority of DNS servers available in DnsServers collection.
Examples
This sample relays the mail message from .EML file to 3 recipients by submitting the message to the SMTP relay server. MessageRecipientSubmitted event is used to report which recipients have been accepted or refused.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    // MessageRecipientSubmitted event handler.
    private static void OnMessageRecipientSubmitted(object sender,
        SmtpMessageRecipientSubmittedEventArgs e)
    {
        if (e.Result)
        {
            Console.WriteLine(e.RecipientEmail + " accepted by the server");
        }
        else
        {
            Console.WriteLine(e.RecipientEmail + " rejected by the server");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server to use, and enable SMTP authentication.
        SmtpServer server = new SmtpServer("smtp-relay.host.com", "jdoe", "secret");
        mailer.SmtpServers.Add(server);

        // Subscribe to the MessageRecipientSubmitted event.
        mailer.MessageRecipientSubmitted +=
            new SmtpMessageRecipientSubmittedEventHandler(OnMessageRecipientSubmitted);

        // Send the message from the file to 3 recipients.
        mailer.RelayFromEmlFile(@"C:\Temp\message.eml", "jdoe@host.com",
            "client@company.com, b.smith@domain1.com, j.smith@domain2.com");
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Class Sample
    ' MessageRecipientSubmitted event handler.
    Private Shared Sub OnMessageRecipientSubmitted(ByVal sender As Object, _
        ByVal e As SmtpMessageRecipientSubmittedEventArgs)
        If (e.Result) Then
            Console.WriteLine(e.RecipientEmail + " accepted by the server")
        Else
            Console.WriteLine(e.RecipientEmail + " rejected by the server")
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Specify SMTP server to use, and enable SMTP authentication.
        Dim server As New SmtpServer("smtp-relay.host.com", "jdoe", "secret")
        mailer.SmtpServers.Add(server)

        ' Subscribe to the MessageRecipientSubmitted event.
        AddHandler mailer.MessageRecipientSubmitted, AddressOf OnMessageRecipientSubmitted

        ' Send the message from the file to 3 recipients.
        mailer.RelayFromEmlFile("C:\Temp\message.eml", "jdoe@host.com", _
            "client@company.com, b.smith@domain1.com, j.smith@domain2.com")
    End Sub
End Class
See Also

Reference

Smtp Class
RelayFromEmlFile Overload
MailBee.SmtpMail Namespace


Smtp.RelayFromEmlFileAsync Method

SmtpRelayFromEmlFileAsync Method
Overload List
 | Name | Description
Public method | RelayFromEmlFileAsync(String, String, EmailAddressCollection) | async/await version of RelayFromEmlFile(String, String, EmailAddressCollection).
Public method | RelayFromEmlFileAsync(String, String, String) | async/await version of RelayFromEmlFile(String, String, String).
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.RelayFromEmlFileAsync Method (String, String, EmailAddressCollection)

SmtpRelayFromEmlFileAsync Method (String, String, EmailAddressCollection)
async/await version of RelayFromEmlFile(String, String, EmailAddressCollection).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> RelayFromEmlFileAsync(
    string filename,
    string senderEmail,
    EmailAddressCollection recipients
)
Public Function RelayFromEmlFileAsync (
    filename As String,
    senderEmail As String,
    recipients As EmailAddressCollection
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The path to the file containing the message source in .EML (RFC2822) format.
senderEmail
Type: SystemString
The e-mail address of the sender.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is trueif the relay operation succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
RelayFromEmlFileAsync Overload
MailBee.SmtpMail Namespace


Smtp.RelayFromEmlFileAsync Method (String, String, String)

SmtpRelayFromEmlFileAsync Method (String, String, String)
async/await version of RelayFromEmlFile(String, String, String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> RelayFromEmlFileAsync(
    string filename,
    string senderEmail,
    string recipientEmails
)
Public Function RelayFromEmlFileAsync (
    filename As String,
    senderEmail As String,
    recipientEmails As String
) As Task(Of Boolean)

Parameters

filename
Type: SystemString
The path to the file containing the message source in .EML (RFC2822) format.
senderEmail
Type: SystemString
The e-mail address of the sender.
recipientEmails
Type: SystemString
The comma-delimited list of the message recipients.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the relay operation succeeded; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
RelayFromEmlFileAsync Overload
MailBee.SmtpMail Namespace


Smtp.ResetMessage Method

SmtpResetMessage Method
Resets all properties of Message object to defaults. Delivery Status Notification settings (DeliveryNotification object) are also reset.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ResetMessage()
Public Sub ResetMessage
Remarks
This method can be used if multiple messages are sent using the same instance of Smtp component, and the developer needs to clear the message properties prior to composing next message in a series.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ResetState Method

SmtpResetState Method
Resets the internal state of the component.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void ResetState()
Public Sub ResetState
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks
This method will close any opened connections, and will remove IsAborted status if Abort method was previously called. Typically, the developer may use this method to reuse the component after it went into aborted state due to Abort method call.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.RetryFailedJobs Method

SmtpRetryFailedJobs Method
Puts all failed send-mail jobs back into the queue.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void RetryFailedJobs()
Public Sub RetryFailedJobs
Remarks

This method can be used to retry processing of all failed jobs (EXCEPT when you're using IDataReader data source, see below why). For instance, there had been some kind of network failure during processing jobs and certain e-mails failed to be sent. Then, however, the network problem was fixed. In this case, the developer can issue RetryFailedJobs to put failed jobs back into the pending queue. Then, any method which processes jobs (such as SendJobs) can be called to resume processing.

RetryFailedJobs method takes all the jobs from JobsFailed collection and puts them back to JobsPending.

Note Note
This method is thread-safe. The developer may safely call it even if some jobs are already being actively processed in the current moment. This may be useful in the case if it's needed to retry failed jobs not waiting for completion of processing the remaining jobs. For instance, if SendJobs method was still running when RetryFailedJobs was called, it will then process the newly added failed jobs as well as the remaining pending jobs.

If you want to move only specific jobs (not all failed jobs) from JobsFailed into JobsPending, use methods of SendMailJobCollection class (all job collections, including JobsFailed and JobsPending, are SendMailJobCollection instances).

This method cannot be used for mail merge job over IDataReader because in general case you can't arbitrarily access IDataReader. Once processing of IDataReader has been done, you'll usually need to recreate it. If MailBee tried to access certain rows again (to retry failed indices), it would cause database error due to forward-only nature of most data reader implementations. When using IDataReader as input, you should manually manage failed ids (see AddJob(String, String, EmailAddressCollection, IDataReader, Boolean, Boolean) for example).

Examples
This console sample performs mail merge in two runs. On the second run, all the data rows which failed to be sent out as e-mail messages on the first run are tried again. The application may complete in a single run if all the data rows have been successfully sent as e-mails within the first run.
Note Note
In the case if the application terminates after the first run and wishes to retry mail merge of failed data rows later in a separate run of the application, it needs to somehow save the list of data rows which failed on the first run (e.g. save this list in a file or database) and then pass this list to the second instance of the application (which is executed later). See GetIndicesAsString(DataTable, String) topic for details.
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports successful attempt of sending e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " SUCCEEDED");
    }

    // Reports failed attempt of sending e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " FAILED");
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Email##";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        // Make two runs of mail merge. If e-mails created from some data rows fail,
        // we'll attempt to resend them on the second run.
        for (int i = 0; i < 2; i++)
        {
            // Initial run.
            if (i == 0)
            {
                // Connect to the database and populate mail merge job to-do list with
                // the data from "mailing_list" table.
                using (OleDbConnection conn = new OleDbConnection(connParams))
                {
                    // Open the connection and get the data.
                    OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
                    conn.Open();
                    OleDbDataAdapter adapter = new OleDbDataAdapter();
                    DataTable table = new DataTable();
                    adapter.SelectCommand = command;
                    adapter.Fill(table);

                    // Create a job which is the following task for MailBee: perform mail merge over
                    // the specified data table and then send out each resulting e-mail to
                    // the recipients which appear in the resulting messages. "bounce@domain.com"
                    // address will be used as Return-Path (i.e. sender e-mail address).
                    mailer.AddJob(null, "bounce@domain.com", null, table);
                }
            }

            // Run the job. The actual mail merge takes place here.
            mailer.SendJobs();
            Console.WriteLine();

            // Report results (row indices in the data table) to the console.
            if (mailer.JobsFailed.Count == 0)
            {
                Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.");
                break;
            }
            else
            {
                if (mailer.JobsSuccessful.Count == 0)
                {
                    Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.");
                }
                else
                {
                    Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.");
                    Console.WriteLine();

                    Console.WriteLine("Successful rows: ");
                    Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(null, null));
                    Console.WriteLine();

                    Console.WriteLine("Failed rows: ");
                    Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(null, null));
                }
                Console.WriteLine();

                // Put failed data rows from mailer.JobsFailed back into the pending queue (mailer.JobsPending).
                mailer.RetryFailedJobs();

                // Clear the list of successful rows because we already displayed all successful
                // results of the first run. Next time, we want to display only those successful
                // results which had been achieved on the second run only.
                mailer.JobsSuccessful.Clear();
            }
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports successful attempt of sending e-mail.
    Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " SUCCEEDED")
    End Sub

    ' Reports failed attempt of sending e-mail.
    Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " FAILED")
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.MessageSent, AddressOf mailer_MessageSent
        AddHandler mailer.MessageNotSent, AddressOf mailer_MessageNotSent

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Email##"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        ' Make two runs of mail merge. If e-mails created from some data rows fail,
        ' we'll attempt to resend them on the second run.
        Dim i As Integer
        For i = 0 To 1
            ' Initial run.
            If i = 0 Then
                ' Connect to the database and populate mail merge job to-do list with
                ' the data from "mailing_list" table.
                Dim conn As OleDbConnection
                Try
                    conn = New OleDbConnection(connParams)

                    ' Open the connection and get the data.
                    Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
                    conn.Open()
                    Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
                    Dim table As DataTable = New DataTable
                    adapter.SelectCommand = command
                    adapter.Fill(table)

                    ' Create a job which is the following task for MailBee: perform mail merge over
                    ' the specified data table and then send out each resulting e-mail to
                    ' the recipients which appear in the resulting messages. "bounce@domain.com"
                    ' address will be used as Return-Path (i.e. sender e-mail address).
                    mailer.AddJob(Nothing, "bounce@domain.com", Nothing, table)
                Finally
                    If Not conn Is Nothing Then
                        conn.Close()
                    End If
                End Try
            End If

            ' Run the job. The actual mail merge takes place here.
            mailer.SendJobs()
            Console.WriteLine()

            ' Report results (row indices in the data table) to the console.
            If mailer.JobsFailed.Count = 0 Then
                Console.WriteLine("All of the rows of the table have been processed and sent as e-mails.")
                Exit For
            Else
                If mailer.JobsSuccessful.Count = 0 Then
                    Console.WriteLine("None of the rows of the table has been processed and sent as e-mail.")
                Else
                    Console.WriteLine("Not all rows of the table have been processed and sent as e-mails.")
                    Console.WriteLine()

                    Console.WriteLine("Successful rows: ")
                    Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(Nothing, Nothing))
                    Console.WriteLine()

                    Console.WriteLine("Failed rows: ")
                    Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(Nothing, Nothing))
                End If
                Console.WriteLine()

                ' Put failed data rows from mailer.JobsFailed back into the pending queue (mailer.JobsPending).
                mailer.RetryFailedJobs()

                ' Clear the list of successful rows because we already displayed all successful
                ' results of the first run. Next time, we want to display only those successful
                ' results which had been achieved on the second run only.
                mailer.JobsSuccessful.Clear()
            End If
        Next
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSendJobs
SmtpSubmitJobsToPickupFolder(String, Boolean)


Smtp.Send Method

SmtpSend Method
Overload List
Name | Description
Send | Sends the mail message to the recipients specified in the message.
Send(String, EmailAddressCollection) | Sends the mail message to the specified recipients.
Send(String, String) | Sends the mail message to the specified recipients e-mail addresses.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Send Method

SmtpSend Method
Sends the mail message to the recipients specified in the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Send()
Public Function Send As Boolean

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
PlatformNotSupportedException | In .NET Core, multi-threaded sending is supported with async methods only. Use SendAsync instead.
Remarks

QuickSend(MailMessage) method can be used to send a mail message with a single line of code.

SendMailMerge(String, EmailAddressCollection, DataTable) or SendJobs methods perform sending of large volumes of e-mails including mail merge over database.

Message property represents the mail message to be sent.

Log object can be used to enable logging SMTP session into a file or memory buffer.

Delivery status notifications can be enabled and configured by setting DeliveryNotification properties.

UploadMessage(MailMessage, String, SystemMessageFlags) method can be used to upload the sent message into IMAP4 folder such as "Sent items".

To sign the outgoing e-mail with DomainKeys/DKIM signature, call mailer.Message.DomainKeysSign prior to calling Send (it's assumed mailer is Smtp instance).

The operation progress can be monitored through subscribing to Smtp class events or by deriving a new class from Smtp and overriding OnEventName methods.

If Connect method was previously called and the connection with the SMTP relay server was established, Send method will send the message to this server.

If Connect method was not called, Send method will automatically connect to the server specified in SmtpServers collection, send the message, and then disconnect.

If SmtpServers collection contains more than one server, Connect method will try to send the message to the top priority server (see Priority). If it fails, other servers will be tried accordingly their priority values.

If SmtpServers collection is empty or the priority of the most preferred SMTP relay server in SmtpServers collection is less than than the priority of the most preferred DNS server in DnsServers collection, the message will be sent in direct send mode. In this mode, MailBee performs DNS MX lookup for all recipients domains to discover which hosts accept mail for these domains (such hosts are called SMTP MX servers), and then sends the message directly to these servers. In other words, MailBee itself will act as a relay SMTP server. However, it's recommended sending host have assigned DNS MX or A record. Systems which actively send mail but don't have any DNS records assigned are typically used by spammers, thus many SMTP MX servers will not accept mail from such host and may even blacklist its IP address.

If both SmtpServers and DnsServers collections are non-empty, the collection having higher priority server will be tried first (if top priority servers of both collections have the same priority, SmtpServers is preferred). If sending to some or all recipients fails due to failure of some servers, another collection will be used to send the message to the failed recipients. Thus, sending to both SMTP relay servers and servers discovered via DNS MX lookup can be performed in a single Send method call, providing high level of reliability of send mail operation.

Note Note
SMTP and DNS server priority values are zero-based. 0 is the highest priority while 999 is the lowest priority.

In direct send mode, it's possible to send the message to all SMTP MX servers simultaneously. This may greatly improve performance when sending to multiple recipients. The developer can enable multi-threading by setting MaxThreadCount property value to -1 (unlimited number of thread) or to the maximum number of threads the application is allowed to use.

Examples

This sample sends an HTML mail to several recipients. The mail is submitted to a single SMTP relay server.

For this sample, setting license key in the config file (such as app.config) is not required since the license key is set directly in the code. However, in real code, it's recommended to set the license key in the config file.

C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

MailBee.Global.LicenseKey = "Trial or permanent key";
Smtp mailer = new Smtp();

// Specify SMTP server and enable authentication. Remove last 2 parameters if SMTP
// authentication is not required in order to send mail through your SMTP server.
mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

// Set sender.
mailer.From.DisplayName = "John Doe";
mailer.From.Email = "jdoe@domain.com";

// Demonstrate various methods to specify recipients.
mailer.To.AsString = "no-display-name@website.com, \"Bill Smith, Jr.\" <bill.smith@company.com>";
mailer.To.AddFromString("Kathy Smith <k.smith@domain.com>");
mailer.To.AddFromString("email@address.com");
mailer.To.Add("Mike Jackson, Sales Manager", "mike@company.com", "Sales Department");

mailer.Subject = "Report";
mailer.BodyHtmlText = "<html>This is the report.</html>";

Console.WriteLine("Will send to: " + mailer.Message.GetAllRecipients());

// In case of timeouts, uncomment the next line. ESMTP CHUNKING sometimes causes problems (usually, with MS Exchange).
// mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

mailer.Send();

Console.WriteLine("Sent to: " + mailer.GetAcceptedRecipients());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

MailBee.Global.LicenseKey = "Trial or permanent key"
Dim mailer As New Smtp

' Specify SMTP server and enable authentication. Remove last 2 parameters if SMTP
' authentication is not required in order to send mail through your SMTP server.
mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

' Set sender.
mailer.From.DisplayName = "John Doe"
mailer.From.Email = "jdoe@domain.com"

' Demonstrate various methods to specify recipients.
mailer.To.AsString = "no-display-name@website.com, ""Bill Smith, Jr."" <bill.smith@company.com>"
mailer.To.AddFromString("Kathy Smith <k.smith@domain.com>")
mailer.To.AddFromString("email@address.com")
mailer.To.Add("Mike Jackson, Sales Manager", "mike@company.com", "Sales Department")

mailer.Subject = "Report"
mailer.BodyHtmlText = "<html>This is the report.</html>"

Console.WriteLine("Will send to: " & mailer.Message.GetAllRecipients().ToString())

' In case of timeouts, uncomment the next line. ESMTP CHUNKING sometimes causes problems (usually, with MS Exchange).
' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

mailer.Send()

Console.WriteLine("Sent to: " & mailer.GetAcceptedRecipients().ToString())
Examples
This sample sends a mail message with attachment, HTML and plain-text body parts to the SMTP server. If sending to the SMTP server fails (server is down), direct send to SMTP MX servers of the recipients domains is automatically performed. DNS servers are auto-detected from operating system settings. Logging SMTP session into a file is enabled.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Enable logging SMTP session into a file.
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.Log.Clear();

// Specify SMTP server to use, and enable SMTP authentication. Remove
// last 2 parameters if authentication is not required by your server.
// If your server requires authentication and expects e-mail address to
// be specified as login name, use "jdoe@domain.com" instead of "jdoe".
mailer.SmtpServers.Add("smtp.domain.com", "jdoe", "secret");

// Get the list of DNS servers from OS settings or the config file.
mailer.DnsServers.Autodetect();

// Set sender.
mailer.From.DisplayName = "John Doe";
mailer.From.Email = "jdoe@domain.com";

// Set To and CC recipients.
mailer.To.Add("Sales Department", "sales@company.com");
mailer.Cc.Add("Conversation archive", "collect@domain.com");

// Set subject.
mailer.Subject = "My order";

// Set that message is high priority. Because Importance property
// has no Smtp.Importance shortcut, use fully qualified form. The
// same applies to Priority property.
mailer.Message.Importance = MailPriority.Highest;
mailer.Message.Priority = MailPriority.Highest;

// Set plain-text and HTML versions of the body.
mailer.BodyPlainText = "Hi!\r\n\r\nAny news on my order status?\r\n" +
    "Order info attached.\r\n\r\nThanks, J.D.";
mailer.BodyHtmlText = "<html>Hi!<p>Any news on my order status?<br>" +
    "Order info attached.</p>Thanks, <i>J.D.</i></html>";

// Attach a file.
mailer.AddAttachment(@"C:\My Documents\order.doc");

// Send the message!
mailer.Send();

// Print the outcome.
Console.WriteLine("Successfully sent to: " + mailer.GetAcceptedRecipients().ToString());
Console.WriteLine("Not sent to: " + mailer.GetRefusedRecipients().ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Enable logging SMTP session into a file.
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.Log.Clear()

' Specify SMTP server to use, and enable SMTP authentication. Remove
' last 2 parameters if authentication is not required by your server.
' If your server requires authentication and expects e-mail address to
' be specified as login name, use "jdoe@domain.com" instead of "jdoe".
mailer.SmtpServers.Add("smtp.domain.com", "jdoe", "secret")

' Get the list of DNS servers from OS settings or the config file.
mailer.DnsServers.Autodetect()

' Set sender.
mailer.From.DisplayName = "John Doe"
mailer.From.Email = "jdoe@domain.com"

' Set To and CC recipients.
mailer.To.Add("Sales Department", "sales@company.com")
mailer.Cc.Add("Conversation archive", "collect@domain.com")

' Set subject.
mailer.Subject = "My order"

' Set that message is high priority. Because Importance property
' has no Smtp.Importance shortcut, use fully qualified form. The
' same applies to Priority property.
mailer.Message.Importance = MailPriority.Highest
mailer.Message.Priority = MailPriority.Highest

' Set plain-text and HTML versions of the body.
mailer.BodyPlainText = "Hi!\r\n\r\nAny news on my order status?\r\n" & _
    "Order info attached.\r\n\r\nThanks, J.D."
mailer.BodyHtmlText = "<html>Hi!<p>Any news on my order status?<br>" & _
    "Order info attached.</p>Thanks, <i>J.D.</i></html>"

' Attach a file.
mailer.AddAttachment("C:\My Documents\order.doc")

' Send the message!
mailer.Send()

' Print the outcome.
Console.WriteLine("Successfully sent to: " + mailer.GetAcceptedRecipients().ToString())
Console.WriteLine("Not sent to: " + mailer.GetRefusedRecipients().ToString())
Examples

This sample sends multiple messages using mail merge. Messages are submitted to the primary SMTP server. If it fails, backup SMTP server is used. MessageSent event is used to track submission of each message. Each message is sent to a single recipient. If MailBee throws an exception telling that sending a message failed because the server rejected it (but not because both servers are down), this exception is caught, and mailing continues.

To use this sample, you need to create "C:\sample.mdb" database, and put "mailing_list" table into this database. "mailing_list" table should look like the following:

ID | Email | Name | Filename
1 | jdoe@hisdomain.com | John Doe | order_234.doc
2 | k.smith@herdomain.com | Katy Smith | order_345.doc
3 | techsupport@ourdomain.com | TechSupport | order_555.doc
It's assumed "C:\Docs" folder contains the following files: order_234.doc, order_345.doc, order_555.doc.

C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    // MessageSent event handler.
    private static void OnMessageSent(
        object sender, SmtpMessageSentEventArgs e)
    {
        // Show all recipients to which the message was successfully sent.
        // However, since we send each message to a single recipient, the
        // code below will execute only once per message.
        foreach (EmailAddress address in e.SuccessfulRecipients)
        {
            Console.WriteLine("Message sent to " + address.Email);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Enable logging of send mail session into a file.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Add primary server (SMTP AUTH is not used).
        // Default priority is 0 (top priority).
        mailer.SmtpServers.Add("smtp.domain.com");

        // Add backup server (SMTP AUTH is used). Assume ISP's SMTP relay
        // server should be used if company's internal server fails.
        SmtpServer backupServer = new SmtpServer("mail.isp.com", "jdoe", "secret");
        backupServer.Priority = 1;
        mailer.SmtpServers.Add(backupServer);

        // Create a message which will be used as a source for mail merge.
        // In this message, we define merge patterns. After applying merge,
        // new message having patterns replaced with actual values will be
        // constructed and placed into msg.Merge.MergedMessage property.
        MailMessage msg = new MailMessage();

        // Set sender (the same value for all messages).
        msg.From.AsString = @"""John Doe, Sales Manager"" <jdoe@company.com>";

        // Set recipient pattern.
        msg.To.AsString = @"""!#DISPLAY_NAME#!"" <!#EMAIL_ADDRESS#!>";

        // Subject is the same for all messages.
        msg.Subject = "Order details";

        // Set body pattern.
        msg.BodyPlainText = @"Dear !#DISPLAY_NAME#!,
Please find your order details in the attached document.

Thanks,
John Doe, Sales Manager";

        // Set attachment pattern (assume all documents reside in C:\Docs folder).
        msg.Merge.AddAttachmentPattern(@"C:\Docs\!#ORDER#!");

        // Subscribe to the MessageSent event.
        mailer.MessageSent += new SmtpMessageSentEventHandler(OnMessageSent);

        // Specify connection string (assume .mdb file resides in C:\ folder).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\sample.mdb;";

        // Prepare DataTable for mail merge.
        OleDbConnection conn = new OleDbConnection(connParams);
        OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        DataTable table = new DataTable();
        adapter.SelectCommand = command;
        adapter.Fill(table);

        // Connect to the SMTP server.
        mailer.Connect();
        for (int i = 0; i < table.Rows.Count; i++)
        {
            try
            {
                // Start mail merge iteration and replace patterns with actual values.
                msg.Merge.Replace(@"!#DISPLAY_NAME#!", table.Rows[i]["Name"].ToString());
                msg.Merge.Replace(@"!#EMAIL_ADDRESS#!", table.Rows[i]["Email"].ToString());
                msg.Merge.Replace(@"!#ORDER#!", table.Rows[i]["Filename"].ToString());

                // Specify that mailer should send the mail message
                // which is the result of mail merge.
                mailer.Message = msg.Merge.MergedMessage;

                // Send it!
                mailer.Send();

                // Report the result.
                Console.WriteLine("The message has been set to " +
                    table.Rows[i]["Email"].ToString());
            }
            catch (MailBeeException e)
            {
                if (e is IMailBeeSmtpSendException)
                {
                    Console.WriteLine("Message has not been sent to " +
                        table.Rows[i]["Email"].ToString() + ", error is: " + e.Message);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                // Clear merged message and prepare for the next mail merge iteration.
                msg.Merge.Reset();
            }
        }

        // Finish.
        mailer.Disconnect();
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Class Sample
    ' MessageSent event handler
    Private Shared Sub OnMessageSent( _
        ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Show all recipients to which the message was successfully sent.
        ' However, since we send each message to a single recipient, the
        ' code below will execute only once per message.
        For Each address As EmailAddress In e.SuccessfulRecipients
            Console.WriteLine("Message sent to " & address.Email)
        Next
    End Sub

    ' The actual code.
    Shared Sub Main()
        Dim mailer As New Smtp

        ' Enable logging of send mail session into a file.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Add primary server (SMTP AUTH is not used).
        ' Default priority is 0 (top priority).
        mailer.SmtpServers.Add("smtp.domain.com")

        ' Add backup server (SMTP AUTH is used). Assume ISP's SMTP relay
        ' server should be used if company's internal server fails.
        Dim backupServer As New SmtpServer("mail.isp.com", "jdoe", "secret")
        backupServer.Priority = 1
        mailer.SmtpServers.Add(backupServer)

        ' Create a message which will be used as a source for mail merge.
        ' In this message, we define merge patterns. After applying merge,
        ' new message having patterns replaced with actual values will be
        ' constructed and placed into msg.Merge.MergedMessage property.
        Dim msg As New MailMessage

        ' Set sender (the same value for all messages).
        msg.From.AsString = """John Doe, Sales Manager"" <jdoe@company.com>"

        ' Set recipient pattern.
        msg.To.AsString = """!#DISPLAY_NAME#!"" <!#EMAIL_ADDRESS#!>"

        ' Subject is the same for all messages.
        msg.Subject = "Order details"

        ' Set body pattern.
        msg.BodyPlainText = "Dear !#DISPLAY_NAME#!," & VbCrLf & _
               "Please find your order details in the attached document." & VbCrLf & _
               VbCrLf & _
               "Thanks," & VbCrLf & _
               "John Doe, Sales Manager"

        ' Set attachment pattern (assume all documents reside in C:\Docs folder).
        msg.Merge.AddAttachmentPattern("C:\Docs\!#ORDER#!")

        ' Subscribe to the MessageSent event.
        AddHandler mailer.MessageSent, AddressOf OnMessageSent

        ' Specify connection string (assume .mdb file resides in C:\ folder).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\sample.mdb;"

        ' Prepare DataTable for mail merge.
        Dim conn As New OleDbConnection(connParams)
        Dim command As New OleDbCommand("SELECT * FROM mailing_list", conn)
        Dim adapter As New OleDbDataAdapter
        Dim table As New DataTable
        adapter.SelectCommand = command
        adapter.Fill(table)

        ' Connect to the SMTP server.
        mailer.Connect()
        For i As Integer = 1 To table.Rows.Count - 1
            Try
                ' Start mail merge iteration and replace patterns with actual values.
                msg.Merge.Replace("!#DISPLAY_NAME#!", table.Rows(i)("Name").ToString())
                msg.Merge.Replace("!#EMAIL_ADDRESS#!", table.Rows(i)("Email").ToString())
                msg.Merge.Replace("!#ORDER#!", table.Rows(i)("Filename").ToString())

                ' Specify that mailer should send the mail message
                ' which is the result of mail merge.
                mailer.Message = msg.Merge.MergedMessage

                ' Send it!
                mailer.Send()

                ' Report the result.
                Console.WriteLine("The message has been set to " & _
                    table.Rows(i)("Email").ToString())
            Catch e As MailBeeException
                If (TypeOf e Is IMailBeeSmtpSendException) Then
                    Console.WriteLine("Message has not been sent to " & _
                        table.Rows(i)("Email").ToString() & ", error is: " & e.Message)
                Else
                    Throw
                End If
            Finally
                ' Clear merged message and prepare for the next mail merge iteration.
                msg.Merge.Reset()
            End Try
        Next

        ' Finish.
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
Send Overload
MailBee.SmtpMail Namespace
SmtpConnect


Smtp.Send Method (String, EmailAddressCollection)

SmtpSend Method (String, EmailAddressCollection)
Sends the mail message to the specified recipients.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Send(
    string senderEmail,
    EmailAddressCollection recipients
)
Public Function Send (
    senderEmail As String,
    recipients As EmailAddressCollection
) As Boolean

Parameters

senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property. If it's an empty string, no sender will be specified (MailBee will issue "MAIL FROM: <>" command to the server).
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
PlatformNotSupportedException | In .NET Core, multi-threaded sending is supported with async methods only. Use SendAsync(String, EmailAddressCollection) instead.
Remarks

SendMailMerge(String, EmailAddressCollection, DataTable) or SendJobs methods perform sending of large volumes of e-mails including mail merge over database.

To specify international e-mail addresses (IDN domains), call EscapeIdnDomain(String) for senderEmail string and ToIdnAddress for recipients collection to convert e-mail addresses from human-readable into SMTP-safe format.

Message property represents the mail message to be sent.

Log object can be used to enable logging SMTP session into a file or memory buffer.

Delivery status notifications can be enabled and configured by setting DeliveryNotification properties.

UploadMessage(MailMessage, String, SystemMessageFlags) method can be used to upload the sent message into IMAP4 folder such as "Sent items".

The operation progress can be monitored through subscribing to Smtp class events or by deriving a new class from Smtp and overriding OnEventName methods.

If Connect method was previously called and the connection with the SMTP relay server was established, Send method will send the message to this server.

If Connect method was not called, Send method will automatically connect to the server specified in SmtpServers collection, send the message, and then disconnect.

If SmtpServers collection contains more than one server, Connect method will try to send the message to the top priority server (see Priority). If it fails, other servers will be tried accordingly their priority values.

If SmtpServers collection is empty or the priority of the most preferred SMTP relay server in SmtpServers collection is less than than the priority of the most preferred DNS server in DnsServers collection, the message will be sent in direct send mode. In this mode, MailBee performs DNS MX lookup for all recipients domains to discover which hosts accept mail for these domains (such hosts are called SMTP MX servers), and then sends the message directly to these servers. In other words, MailBee itself will act as a relay SMTP server. However, it's recommended sending host have assigned DNS MX or A record. Systems which actively send mail but don't have any DNS records assigned are typically used by spammers, thus many SMTP MX servers will not accept mail from such host and may even blacklist its IP address.

If both SmtpServers and DnsServers collections are non-empty, the collection having higher priority server will be tried first (if top priority servers of both collections have the same priority, SmtpServers is preferred). If sending to some or all recipients fails due to failure of some servers, another collection will be used to send the message to the failed recipients. Thus, sending to both SMTP relay servers and servers discovered via DNS MX lookup can be performed in a single Send method call, providing high level of reliability of send mail operation.

Note Note
SMTP and DNS server priority values are zero-based. 0 is the highest priority while 999 is the lowest priority.

In direct send mode, it's possible to send the message to all SMTP MX servers simultaneously. This may greatly improve performance when sending to multiple recipients. The developer can enable multi-threading by setting MaxThreadCount property value to -1 (unlimited number of thread) or to the maximum number of threads the application is allowed to use.

Examples
This sample gets a message from the POP3 server and then sends it to other recipients. From: and To: fields in the original messages are not altered.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.Pop3Mail;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
Pop3 pop = new Pop3();

// Download first message from POP3 inbox.
pop.Connect("pop.domain.com");
pop.Login("jdoe", "secret");
mailer.Message = pop.DownloadEntireMessage(1);
pop.Disconnect();

// Specify SMTP server to use, and enable SMTP authentication. Remove
// last 2 parameters if authentication is not required by your server.
// If your server requires authentication and expects e-mail address to
// be specified as login name, use "jdoe@domain.com" instead of "jdoe".
mailer.SmtpServers.Add("smtp.domain.com", "jdoe", "secret");

// Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
// mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

// Specify some recipients to relay the message to.
EmailAddressCollection recipients = new EmailAddressCollection();
recipients.Add("user1@domain1.com");
recipients.Add("user2@domain2.com");
recipients.Add("user3@domain3.com");

// Note: some servers do not allow sending from address different
// from From: address specified in the message. In this case, adding
// Resent-From: custom header often helps. However, the message will
// be altered in this case. Uncomment the next line to add Resent-From:
// header to the message.

// mailer.Message.Headers["Resent-From"] = mailer.Message.From.Email;

// Relay the message.
mailer.Send("jdoe@domain.com", recipients);

Console.WriteLine("Sent to: " + mailer.GetAcceptedRecipients().ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.Pop3Mail
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp
Dim pop As New Pop3

' Download first message from POP3 inbox.
pop.Connect("pop.domain.com")
pop.Login("jdoe", "secret")
mailer.Message = pop.DownloadEntireMessage(1)
pop.Disconnect()

' Specify SMTP server to use, and enable SMTP authentication. Remove
' last 2 parameters if authentication is not required by your server.
' If your server requires authentication and expects e-mail address to
' be specified as login name, use "jdoe@domain.com" instead of "jdoe".
mailer.SmtpServers.Add("smtp.domain.com", "jdoe", "secret")

' Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

' Specify some recipients to relay the message to
Dim recipients As New EmailAddressCollection
recipients.Add("user1@domain1.com")
recipients.Add("user2@domain2.com")
recipients.Add("user3@domain3.com")

' Note: some servers do not allow sending from address different
' from From: address specified in the message. In this case, adding
' Resent-From: custom header often helps. However, the message will
' be altered in this case. Uncomment the next line to add Resent-From:
' header to the message.

' mailer.Message.Headers("Resent-From") = mailer.Message.From.Email

' Relay the message.
mailer.Send("jdoe@domain.com", recipients)

Console.WriteLine("Sent to: " & mailer.GetAcceptedRecipients().ToString())
See Also

Reference

Smtp Class
Send Overload
MailBee.SmtpMail Namespace
SmtpRelayFromEmlFile(String, String, EmailAddressCollection)


Smtp.Send Method (String, String)

SmtpSend Method (String, String)
Sends the mail message to the specified recipients e-mail addresses.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Send(
    string senderEmail,
    string recipientEmails
)
Public Function Send (
    senderEmail As String,
    recipientEmails As String
) As Boolean

Parameters

senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipientEmails
Type: SystemString
The comma-separted list of the recipients e-mail addresses. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
PlatformNotSupportedException | In .NET Core, multi-threaded sending is supported with async methods only. Use SendAsync(String, String) instead.
Remarks

QuickSend(MailMessage) method can be used to send a mail message with a single line of code.

SendMailMerge(String, EmailAddressCollection, DataTable) or SendJobs methods perform sending of large volumes of e-mails including mail merge over database.

To specify international e-mail addresses (IDN domains), call EscapeIdnDomain(String) for senderEmail string and for each individual value in recipientEmails to convert e-mail addresses from human-readable into SMTP-safe format.

Message property represents the mail message to be sent.

Log object can be used to enable logging SMTP session into a file or memory buffer.

Delivery status notifications can be enabled and configured by setting DeliveryNotification properties.

UploadMessage(MailMessage, String, SystemMessageFlags) method can be used to upload the sent message into IMAP4 folder such as "Sent items".

The operation progress can be monitored through subscribing to Smtp class events or by deriving a new class from Smtp and overriding OnEventName methods.

If Connect method was previously called and the connection with the SMTP relay server was established, Send method will send the message to this server.

If Connect method was not called, Send method will automatically connect to the server specified in SmtpServers collection, send the message, and then disconnect.

If SmtpServers collection contains more than one server, Connect method will try to send the message to the top priority server (see Priority). If it fails, other servers will be tried accordingly their priority values.

If SmtpServers collection is empty or the priority of the most preferred SMTP relay server in SmtpServers collection is less than than the priority of the most preferred DNS server in DnsServers collection, the message will be sent in direct send mode. In this mode, MailBee performs DNS MX lookup for all recipients domains to discover which hosts accept mail for these domains (such hosts are called SMTP MX servers), and then sends the message directly to these servers. In other words, MailBee itself will act as a relay SMTP server. However, it's recommended sending host have assigned DNS MX or A record. Systems which actively send mail but don't have any DNS records assigned are typically used by spammers, thus many SMTP MX servers will not accept mail from such host and may even blacklist its IP address.

If both SmtpServers and DnsServers collections are non-empty, the collection having higher priority server will be tried first (if top priority servers of both collections have the same priority, SmtpServers is preferred). If sending to some or all recipients fails due to failure of some servers, another collection will be used to send the message to the failed recipients. Thus, sending to both SMTP relay servers and servers discovered via DNS MX lookup can be performed in a single Send method call, providing high level of reliability of send mail operation.

Note Note
SMTP and DNS server priority values are zero-based. 0 is the highest priority while 999 is the lowest priority.

In direct send mode, it's possible to send the message to all SMTP MX servers simultaneously. This may greatly improve performance when sending to multiple recipients. The developer can enable multi-threading by setting MaxThreadCount property value to -1 (unlimited number of thread) or to the maximum number of threads the application is allowed to use.

Examples
This sample sends a message from address different from From: address specified in the message. This is useful when bounced messages should be processed and the developer wants to redirect bounced messages to another address. In this sample, From: is jdoe@domain.com while real sender's address (which will appear in Return-Path header value and where bounces will arrive to) is bounce@domain.com.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Specify SMTP server to use, and enable SMTP authentication. Remove
// last 2 parameters if authentication is not required by your server.
// If your server requires authentication and expects e-mail address to
// be specified as login name, use "bounce@domain.com" instead of "bounce".
mailer.SmtpServers.Add("smtp.domain.com", "bounce", "password");

// Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
// mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

// Specify From: field.
mailer.From.AsString = "John Doe <jdoe@domain.com>";

// Set recipients
mailer.To.AsString = "Bill Smith <bill@company.com>;, kathy@anothercompany.com";

mailer.Subject = "Report";
mailer.BodyPlainText = "This is the report.";

// Send from bounce@domain.com rather than jdoe@domain.com.
// bounce@domain.com will appear in Return-Path header.
// We set recipientEmails=null to send to addresses specified in the message.
mailer.Send("bounce@domain.com", (string)null);

Console.WriteLine("Sent to: " + mailer.GetAcceptedRecipients().ToString());
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Specify SMTP server to use, and enable SMTP authentication. Remove
' last 2 parameters if authentication is not required by your server.
' If your server requires authentication and expects e-mail address to
' be specified as login name, use "bounce@domain.com" instead of "bounce".
mailer.SmtpServers.Add("smtp.domain.com", "bounce", "password")

' Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

' Specify From: field
mailer.From.AsString = "John Doe <jdoe@domain.com>"

' Set recipients.
mailer.To.AsString = "Bill Smith <bill@company.com>;, kathy@anothercompany.com"

mailer.Subject = "Report"
mailer.BodyPlainText = "This is the report."

' Send from bounce@domain.com rather than jdoe@domain.com.
' bounce@domain.com will appear in Return-Path header.
' We set recipientEmails=null to send to addresses specified in the message.
mailer.Send("bounce@domain.com", CStr(Nothing))

Console.WriteLine("Sent to: " & mailer.GetAcceptedRecipients().ToString())
See Also

Reference

Smtp Class
Send Overload
MailBee.SmtpMail Namespace
SmtpRelayFromEmlFile(String, String, EmailAddressCollection)


Smtp.SendAsync Method

SmtpSendAsync Method
Overload List
 | Name | Description
Public method | SendAsync | async/await version of Send.
Public method | SendAsync(String, EmailAddressCollection) | async/await version of Send(String, EmailAddressCollection).
Public method | SendAsync(String, String) | async/await version of Send(String, String).
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SendAsync Method

SmtpSendAsync Method
async/await version of Send.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendAsync()
Public Function SendAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SendAsync Overload
MailBee.SmtpMail Namespace


Smtp.SendAsync Method (String, EmailAddressCollection)

SmtpSendAsync Method (String, EmailAddressCollection)
async/await version of Send(String, EmailAddressCollection).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendAsync(
    string senderEmail,
    EmailAddressCollection recipients
)
Public Function SendAsync (
    senderEmail As String,
    recipients As EmailAddressCollection
) As Task(Of Boolean)

Parameters

senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SendAsync Overload
MailBee.SmtpMail Namespace


Smtp.SendAsync Method (String, String)

SmtpSendAsync Method (String, String)
async/await version of Send(String, String).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendAsync(
    string senderEmail,
    string recipientEmails
)
Public Function SendAsync (
    senderEmail As String,
    recipientEmails As String
) As Task(Of Boolean)

Parameters

senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipientEmails
Type: SystemString
The comma-separted list of the recipients e-mail addresses. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the method succeeds; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SendAsync Overload
MailBee.SmtpMail Namespace


Smtp.SendJobs Method

SmtpSendJobs Method
Sends out all e-mails in the pending jobs queue (including e-mails generated via mail merge).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SendJobs()
Public Function SendJobs As Boolean

Return Value

Type: Boolean
true if the entire queue of the pending jobs had been processed; false if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method takes JobsPending collection as an input and processes all the jobs in it. For jobs consisting of sending a single e-mail message, this e-mail gets sent. For mail merge jobs, mail merge is performed so that the original mail merge job is split into smaller jobs (for mail merge of N data rows, N jobs generated) and the resulting e-mail messages are sent.

To place mail merge job into the queue, use AddJob(string, string, EmailAddressCollection, DataTable) or AddJob(string, string, EmailAddressCollection, IDataReader) overloads. To queue sending of a single e-mail message, use AddJob(String, String, EmailAddressCollection) overload.

To sign each outgoing e-mail with DomainKeys/DKIM signature, subscribe to SendingMessage event and call e.MailMessage.DomainKeysSign in the event handler (assuming e is SmtpSendingMessageEventArgs parameter of the event handler).

While SendJobs method is running, it takes the jobs one by one from JobsPending collection into JobsRunning. Once certain job completes successfully, it's moved into JobsSuccessful. If, however, it failed, it's moved into JobsFailed. For more information on how jobs are processed, see AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) overload and SendMailMerge(String, EmailAddressCollection, DataTable) method topics.

RetryFailedJobs method can be used to put failed jobs back into the pending queue (except of the jobs created from IDataReader). This can be used to try to re-send failed messages again.

By default, jobs are processed in a single-thread mode. The developer may achieve better performance enabling multi-thread mode (see MaxThreadCount property for details).

MaxThreadCount must be set BEFORE SendJobs gets called.

If large amount of e-mails is sent to an SMTP relay server, it might be efficient to tune some properties of SmtpServer object representing this server in SmtpServers collection. For instance, tuning MaxConnectionCount, MaxSendPerSessionCount, and PauseInterval property values can improve sending performance or overcome issues caused by various restictions implied by the SMTP server (such as limitation of maximum number of e-mails per second from a single IP address).

If you need to submit e-mails directly to the pickup folder for subsequent delivery with MailBee.NET Queue or IIS SMTP service, use SubmitJobsToPickupFolder(String, Boolean) method instead.

Note Note
SendJobs will never stop on failures and always succeed if StopJobsOnError is false.
Examples
This sample processes 2 jobs ("mail merge" job and "single e-mail" job) and reports the results to the console.
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports successful attempt of sending mail merge e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Ignore notification e-mail (it's not mail merge).
        if (e.MergeTable != null)
        {
            // Display e-mail address of the successful e-mail.
            Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " SUCCEEDED");
        }
    }

    // Reports failed attempt of sending mail merge e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Ignore notification e-mail (it's not mail merge).
        if (e.MergeTable != null)
        {
            // Display e-mail address of the failed e-mail.
            Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " FAILED");
        }
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Email##";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup plain-text body template.
        mailer.Message.BodyPlainText = "##Body##";

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        // Connect to the database and populate mail merge job to-do list with
        // the data from "mailing_list" table.
        using (OleDbConnection conn = new OleDbConnection(connParams))
        {
            // Open the connection and get the data.
            OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            DataTable table = new DataTable();
            adapter.SelectCommand = command;
            adapter.Fill(table);

            // Create a job which is the following task for MailBee: perform mail merge over
            // the specified data table and then send out each resulting e-mail to
            // the recipients which appear in the resulting messages. "bounce@domain.com"
            // address will be used as Return-Path (i.e. sender e-mail address).
            mailer.AddJob("1", "bounce@domain.com", null, table);
        }

        // Create a job which is a task of sending a notification e-mail to the originator
        // of the newsletter regarding completion of bulk mailing.
        mailer.Message.To.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.Subject = "Status: Our Jan/2007 newsletter";
        mailer.Message.BodyPlainText = "Newsletter sent out";
        mailer.AddJob("2", null, null);

        // In case of timeouts, uncomment the next line. ESMTP CHUNKING sometimes causes problems (usually, with MS Exchange).
        // mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

        // Run both jobs. The actual mail merge (job #1) and
        // sending a single e-mail (job #2) takes place here.
        mailer.SendJobs();
        Console.WriteLine();

        // Report results to the console.
        if (mailer.JobsFailed.Count == 0)
        {
            Console.WriteLine("All e-mails have been sent.");
        }
        else
        {
            if (mailer.JobsSuccessful.Count == 0)
            {
                Console.WriteLine("No e-mails have been sent.");
            }
            else
            {
                Console.WriteLine("Some e-mails have not been sent.");
                Console.WriteLine();

                // Report mail merge results (job #1).
                Console.WriteLine("Successful mail merge data rows: ");
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(null, "1"));
                Console.WriteLine();
                Console.WriteLine("Failed mail merge data rows: ");
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(null, "1"));
                Console.WriteLine();

                // Report notification e-mail results (job #2).
                if (mailer.JobsFailed.GetIndicesAsString(null, "2") == string.Empty)
                {
                    Console.WriteLine("Notification e-mail has been sent.");
                }
                else
                {
                    Console.WriteLine("Notification e-mail has not been sent.");
                }
            }
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports successful attempt of sending mail merge e-mail.
    Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Ignore notification e-mail (it's not mail merge).
        If Not e.MergeTable Is Nothing Then
            ' Display e-mail address of the successful e-mail.
            Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " SUCCEEDED")
        End If
    End Sub

    ' Reports failed attempt of sending mail merge e-mail.
    Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        ' Ignore notification e-mail (it's not mail merge).
        If Not e.MergeTable Is Nothing Then
            ' Display e-mail address of the failed e-mail.
            Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " FAILED")
        End If
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.MessageSent, AddressOf mailer_MessageSent
        AddHandler mailer.MessageNotSent, AddressOf mailer_MessageNotSent

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Email##"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup plain-text body template.
        mailer.Message.BodyPlainText = "##Body##"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        ' Connect to the database and populate mail merge job to-do list with
        ' the data from "mailing_list" table.
        Dim conn As OleDbConnection
        Try
            conn = New OleDbConnection(connParams)

            ' Open the connection and get the data.
            Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
            conn.Open()
            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
            Dim table As DataTable = New DataTable
            adapter.SelectCommand = command
            adapter.Fill(table)

            ' Create a job which is the following task for MailBee: perform mail merge over
            ' the specified data table and then send out each resulting e-mail to
            ' the recipients which appear in the resulting messages. "bounce@domain.com"
            ' address will be used as Return-Path (i.e. sender e-mail address).
            mailer.AddJob("1", "bounce@domain.com", Nothing, table)
        Finally
            If Not conn Is Nothing Then
                conn.Close()
            End If
        End Try

        ' Create a job which is a task of sending a notification e-mail to the originator
        ' of the newsletter regarding completion of bulk mailing.
        mailer.Message.To.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.Subject = "Status: Our Jan/2007 newsletter"
        mailer.Message.BodyPlainText = "Newsletter sent out"
        mailer.AddJob("2", Nothing, Nothing)

        ' In case of timeouts, uncomment the next line. ESMTP CHUNKING sometimes causes problems (usually, with MS Exchange).
        ' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

        ' Run both jobs. The actual mail merge (job #1) and
        ' sending a single e-mail (job #2) takes place here.
        mailer.SendJobs()
        Console.WriteLine()

        ' Report results to the console.
        If mailer.JobsFailed.Count = 0 Then
            Console.WriteLine("All e-mails have been sent.")
        Else
            If mailer.JobsSuccessful.Count = 0 Then
                Console.WriteLine("No e-mails have been sent.")
            Else
                Console.WriteLine("Some e-mails have not been sent.")
                Console.WriteLine()

                ' Report mail merge results (job #1).
                Console.WriteLine("Successful mail merge data rows: ")
                Console.WriteLine(mailer.JobsSuccessful.GetIndicesAsString(Nothing, "1"))
                Console.WriteLine()
                Console.WriteLine("Failed mail merge data rows: ")
                Console.WriteLine(mailer.JobsFailed.GetIndicesAsString(Nothing, "1"))
                Console.WriteLine()

                ' Report notification e-mail results (job #2).
                If mailer.JobsFailed.GetIndicesAsString(Nothing, "2") = String.Empty Then
                    Console.WriteLine("Notification e-mail has been sent.")
                Else
                    Console.WriteLine("Notification e-mail has not been sent.")
                End If
            End If
        End If
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpStopJobsOnError
SmtpSubmitJobsToPickupFolder(String, Boolean)


Smtp.SendJobsAsync Method

SmtpSendJobsAsync Method
async/await version of SendJobs.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendJobsAsync()
Public Function SendJobsAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the entire queue of the pending jobs had been processed; false if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SendMailMerge Method

SmtpSendMailMerge Method
Creates a series of e-mails based on an e-mail message template and a data source and sends these e-mails out.
Overload List
Name | Description
SendMailMerge(String, EmailAddressCollection, DataTable) | Creates a series of e-mails based on an e-mail message template and a data table and sends these e-mails out.
SendMailMerge(String, EmailAddressCollection, IDataReader) | Creates a series of e-mails based on an e-mail message template and a data reader and sends these e-mails out.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SendMailMerge Method (String, EmailAddressCollection, DataTable)

SmtpSendMailMerge Method (String, EmailAddressCollection, DataTable)
Creates a series of e-mails based on an e-mail message template and a data table and sends these e-mails out.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SendMailMerge(
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    DataTable mergeTable
)
Public Function SendMailMerge (
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeTable As DataTable
) As Boolean

Parameters

senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The pattern of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
mergeTable
Type: System.DataDataTable
The data source for mail merge.

Return Value

Type: Boolean
true if the entire mail merge has been processed; false if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

Use this method to prepare the mail merge task (job) and immediately process it. SendMailMerge(String, EmailAddressCollection, DataTable) method simply calls AddJob(String, String, EmailAddressCollection, DataTable) and then SendJobs.

Note Note
Mail merge over database is not supported in .NET Core and UWP editions yet. This method in not available these.

If JobsPending queue already contained some jobs to the moment of SendMailMerge(String, EmailAddressCollection, DataTable) call, these jobs will be processed too.

To sign each outgoing e-mail with DomainKeys/DKIM signature, subscribe to SendingMessage event and call e.MailMessage.DomainKeysSign in the event handler (assuming e is SmtpSendingMessageEventArgs parameter of the event handler).

By default, SendMailMerge(String, EmailAddressCollection, DataTable) method won't stop if any e-mail message in the mail merge series failed to be sent. Thus, the method always succeeds. The developer can use MessageSent and MessageNotSent events to keep track of successful and failed e-mails while SendMailMerge(String, EmailAddressCollection, DataTable) method is in progress, or examine JobsSuccessful and JobsFailed collections after SendMailMerge(String, EmailAddressCollection, DataTable) completes.

However, it's possible to make SendMailMerge(String, EmailAddressCollection, DataTable) method fail if any of the e-mails in the series fail to be sent. To achieve this, set StopJobsOnError to true prior to calling SendMailMerge(String, EmailAddressCollection, DataTable).

If any e-mails within the mail merge job failed to be sent, the developer can use RetryFailedJobs method to put all failed send-mail jobs back from JobsFailed into JobsPending and then call SendJobs to try sending them out again. Note that RetryFailedJobs will work for this overload which uses DataTable as input but won't work for SendMailMerge(string, EmailAddressCollection, IDataReader) version.

Re-sending failed e-mails can be repeated multiple times, and it's allowed to use different sending methods each time. For instance, the developer can change SMTP relay server, try direct sending via DNS MX lookup, or even save e-mails as files for later delivery using SubmitJobsToPickupFolder(String, Boolean) method.

In the case if the application shuts down after performing mail merge (so there is no way to call RetryFailedJobs next time when the application starts since all the data has been lost), the application should save information regarding failed e-mails in a persistent storage such as database. For mail merge, there is no need to save the entire e-mails because the only thing which differs e-mails from each other is an index of a row in the data table which was used to create an e-mail from the template. Thus, it's enough to save data row indices only and then load them next time (provided that the template and the data table will be the same). See AddJob(String, String, EmailAddressCollection, DataTable, Object, Boolean, Boolean) topic for the code sample.

Examples
This console sample sends out a newsletter. Events are used to keep track of the mailing. E-mails are sent from "Return-Path" address different from "From:" address. This makes it easier to process bounced messages because each bounced message (produced for mail merge messages which could not be delivered) is sent to "Return-Path" address rather than "From:" address. Thus, each bounced message will have ID of the failed mail merge row in its "From:" field (and this "From:" will be taken from "Return-Path" of the originating e-mails).
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports readiness to start sending an e-mail.
    static void mailer_SendingMessage(object sender, SmtpSendingMessageEventArgs e)
    {
        // Display e-mail address of the e-mail to be sent.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " IS BEING SENT");
    }

    // Reports successful attempt of sending mail merge e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " SUCCEEDED");
    }

    // Reports failed attempt of sending mail merge e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeTable.Rows[e.MergeRowIndex]["Email"] + " FAILED");
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.SendingMessage += new SmtpSendingMessageEventHandler(mailer_SendingMessage);
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
        // mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Email##";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        DataTable table = new DataTable();

        // Connect to the database and populate mail merge job to-do list with
        // the data from "mailing_list" table.
        using (OleDbConnection conn = new OleDbConnection(connParams))
        {
            // Open the connection and get the data.
            OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = command;
            adapter.Fill(table);
        }

        // Create and run a job which is the following task for MailBee: perform mail merge
        // over the specified data table and then send out each resulting e-mail to
        // the recipients which appear in the resulting messages.
        // "bounce_Jan2007_<ID>@domain.com" (where <ID> is mailing_list.ID)
        // address will be used as Return-Path (i.e. sender e-mail address).
        // If there is a wildcard mailbox "bounce_Jan2007_*@domain.com", possible bounces
        // will arrive to this mailbox and have "From:" like "bounce_Jan2007_1@domain.com",
        // "bounce_Jan2007_4908@domain.com", etc and the application can then poll this
        // wildcard mailbox to unsubscribe records #1 and #4908 from database.
        mailer.SendMailMerge("bounce_Jan2007_##ID##@domain.com", null, table);
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports readiness to start sending an e-mail.
    Shared Sub mailer_SendingMessage(ByVal sender As Object, ByVal e As SmtpSendingMessageEventArgs)
        ' Display e-mail address of the e-mail to be sent.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " IS BEING SENT")
    End Sub

    ' Reports successful attempt of sending mail merge e-mail.
    Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " SUCCEEDED")
    End Sub

    ' Reports failed attempt of sending mail merge e-mail.
    Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeTable.Rows(e.MergeRowIndex)("Email") & " FAILED")
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.SendingMessage, AddressOf mailer_SendingMessage
        AddHandler mailer.MessageSent, AddressOf mailer_MessageSent
        AddHandler mailer.MessageNotSent, AddressOf mailer_MessageNotSent

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
        ' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Email##"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        Dim table As DataTable = New DataTable

        ' Connect to the database and populate mail merge job to-do list with
        ' the data from "mailing_list" table.
        Dim conn As OleDbConnection
        Try
            conn = New OleDbConnection(connParams)
            ' Open the connection and get the data.
            Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
            conn.Open()
            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
            adapter.SelectCommand = command
            adapter.Fill(table)
        Finally
            If Not conn Is Nothing Then
                conn.Close()
            End If
        End Try

        ' Create and run a job which is the following task for MailBee: perform mail merge
        ' over the specified data table and then send out each resulting e-mail to
        ' the recipients which appear in the resulting messages.
        ' "bounce_Jan2007_<ID>@domain.com" (where <ID> is mailing_list.ID)
        ' address will be used as Return-Path (i.e. sender e-mail address).
        ' If there is a wildcard mailbox "bounce_Jan2007_*@domain.com", possible bounces
        ' will arrive to this mailbox and have "From:" like "bounce_Jan2007_1@domain.com",
        ' "bounce_Jan2007_4908@domain.com", etc and the application can then poll this
        ' wildcard mailbox to unsubscribe records #1 and #4908 from database.
        mailer.SendMailMerge("bounce_Jan2007_##ID##@domain.com", Nothing, table)
    End Sub
End Class
See Also

Reference

Smtp Class
SendMailMerge Overload
MailBee.SmtpMail Namespace
SmtpAddJob(String, String, EmailAddressCollection, DataTable)
SmtpRetryFailedJobs
SmtpSubmitJobsToPickupFolder(String, Boolean)


Smtp.SendMailMerge Method (String, EmailAddressCollection, IDataReader)

SmtpSendMailMerge Method (String, EmailAddressCollection, IDataReader)
Creates a series of e-mails based on an e-mail message template and a data reader and sends these e-mails out.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SendMailMerge(
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    IDataReader mergeDataReader
)
Public Function SendMailMerge (
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeDataReader As IDataReader
) As Boolean

Parameters

senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The pattern of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
mergeDataReader
Type: System.DataIDataReader
The data source for mail merge.

Return Value

Type: Boolean
true if the entire mail merge has been processed; false if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method is a version of SendMailMerge(string, EmailAddressCollection, DataTable) overload which accepts IDataReader rather than DataTable as input. This may be handy for dealing with large recordsets which would not fit in memory in case of DataTable.

However, such readers like SqlDataReader can represent forward-only cursors which cannot be accessed on arbitrary basis. This imposes some limitations on using this overload, for instance, you cannot use RetryFailedJobs to process the data reader another time because the reader does not remember the rows which have already been read before and needs to be re-created for that.

Multi-threaded usage of forward-only data readers is also limited but MailBee has some means to overcome this. The code sample in this topic shows how to access data from a data reader in event handlers in case if many threads are reading from the reader and the app cannot rely on the current row position.

Note Note
Mail merge over database is not supported in .NET Core and UWP editions yet. This method is not available there.
Examples
This console sample is a version of the same sample in SendMailMerge(string, EmailAddressCollection, DataTable) overload but uses SqlDataReader (and MS SQL Server database) as input.
C#
VB
Copy
using System;
using System.Data;
using System.Data.SqlClient;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Reports readiness to start sending an e-mail.
    static void mailer_SendingMessage(object sender, SmtpSendingMessageEventArgs e)
    {
        // Display e-mail address of the e-mail to be sent.
        Console.WriteLine(e.MergeDataReaderRowValues[1].ToString() + " IS BEING SENT");
    }

    // Reports successful attempt of sending mail merge e-mail.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        // Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeDataReaderRowValues[1].ToString() + " SUCCEEDED");
    }

    // Reports failed attempt of sending mail merge e-mail.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        // Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeDataReaderRowValues[1].ToString() + " FAILED");
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.SendingMessage += new SmtpSendingMessageEventHandler(mailer_SendingMessage);
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret");

        // Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
        // mailer.SmtpServers[0].SmtpOptions = ExtendedSmtpOptions.NoChunking;

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Email##";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Specify database connection string (it may be different in your case).
        string connParams = @"server=(local)\SQLEXPRESS;Initial Catalog=afterlogic;Integrated Security=True";

        using (SqlConnection conn = new SqlConnection(connParams))
        {
            conn.Open();
            using (SqlCommand command = conn.CreateCommand())
            {
                // The 'mailing_list' table or query must have these fields:
                // #0: ID (int)
                // #1: Email (nvarchar)
                // #2: Name (nvarchar)
                // #3: Body (nvarchar)
                // Table row example: 175, "jdoe@domain.com", "John", "Some text".
                command.CommandText = "SELECT * FROM mailing_list";

                // Populate mail merge job to-do list with from the specified table.
                using (SqlDataReader reader = command.ExecuteReader())
                {

                    // Create and run a job which is the following task for MailBee: perform mail merge
                    // over the specified data table and then send out each resulting e-mail to
                    // the recipients which appear in the resulting messages.
                    // "bounce_Jan2007_<ID>@domain.com" (where <ID> is mailing_list.ID)
                    // address will be used as Return-Path (i.e. sender e-mail address).
                    // If there is a wildcard mailbox "bounce_Jan2007_*@domain.com", possible bounces
                    // will arrive to this mailbox and have "From:" like "bounce_Jan2007_1@domain.com",
                    // "bounce_Jan2007_4908@domain.com", etc and the application can then poll this
                    // wildcard mailbox to unsubscribe records #1 and #4908 from database.
                    mailer.SendMailMerge("bounce_Jan2007_##ID##@domain.com", null, reader);
                }
            }
        }
    }
}
Imports System.Data
Imports System.Data.SqlClient
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Reports readiness to start sending an e-mail.
    Private Shared Sub mailer_SendingMessage(ByVal sender As Object, ByVal e As SmtpSendingMessageEventArgs)
        ' Display e-mail address of the e-mail to be sent.
        Console.WriteLine(e.MergeDataReaderRowValues(1).ToString() & " IS BEING SENT")
    End Sub

    ' Reports successful attempt of sending mail merge e-mail.
    Private Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        ' Display e-mail address of the successful e-mail.
        Console.WriteLine(e.MergeDataReaderRowValues(1).ToString() & " SUCCEEDED")
    End Sub

    ' Reports failed attempt of sending mail merge e-mail.
    Private Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        ' Display e-mail address of the failed e-mail.
        Console.WriteLine(e.MergeDataReaderRowValues(1).ToString() & " FAILED")
    End Sub

    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp()

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.SendingMessage, New SmtpSendingMessageEventHandler(AddressOf mailer_SendingMessage)
        AddHandler mailer.MessageSent, New SmtpMessageSentEventHandler(AddressOf mailer_MessageSent)
        AddHandler mailer.MessageNotSent, New SmtpMessageNotSentEventHandler(AddressOf mailer_MessageNotSent)

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe@domain.com", "secret")

        ' Uncomment next line if ESMTP CHUNKING causes problems with your server (usually, with MS Exchange).
        ' mailer.SmtpServers(0).SmtpOptions = ExtendedSmtpOptions.NoChunking

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Email##"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "server=(local)\SQLEXPRESS;Initial Catalog=afterlogic;Integrated Security=True"

        Using conn As New SqlConnection(connParams)
            conn.Open()
            Using command As SqlCommand = conn.CreateCommand()
                ' The 'mailing_list' table or query must have these fields:
                ' #0: ID (int)
                ' #1: Email (nvarchar)
                ' #2: Name (nvarchar)
                ' #3: Body (nvarchar)
                ' Table row example: 175, "jdoe@domain.com", "John", "Some text".
                command.CommandText = "SELECT * FROM mailing_list"

                ' Populate mail merge job to-do list with from the specified table.
                Using reader As SqlDataReader = command.ExecuteReader()

                    ' Create and run a job which is the following task for MailBee: perform mail merge
                    ' over the specified data table and then send out each resulting e-mail to
                    ' the recipients which appear in the resulting messages.
                    ' "bounce_Jan2007_<ID>@domain.com" (where <ID> is mailing_list.ID)
                    ' address will be used as Return-Path (i.e. sender e-mail address).
                    ' If there is a wildcard mailbox "bounce_Jan2007_*@domain.com", possible bounces
                    ' will arrive to this mailbox and have "From:" like "bounce_Jan2007_1@domain.com",
                    ' "bounce_Jan2007_4908@domain.com", etc and the application can then poll this
                    ' wildcard mailbox to unsubscribe records #1 and #4908 from database.
                    mailer.SendMailMerge("bounce_Jan2007_##ID##@domain.com", Nothing, reader)
                End Using
            End Using
        End Using
    End Sub
End Class
See Also

Reference

Smtp Class
SendMailMerge Overload
MailBee.SmtpMail Namespace
SmtpAddJob(String, String, EmailAddressCollection, IDataReader)
SmtpSubmitJobsToPickupFolder(String, Boolean)


Smtp.SendMailMergeAsync Method

SmtpSendMailMergeAsync Method
Overload List
 | Name | Description
Public method | SendMailMergeAsync(String, EmailAddressCollection, DataTable) | async/await version of SendMailMerge(String, EmailAddressCollection, DataTable).
Public method | SendMailMergeAsync(String, EmailAddressCollection, IDataReader) | async/await version of SendMailMerge(String, EmailAddressCollection, IDataReader).
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SendMailMergeAsync Method (String, EmailAddressCollection, DataTable)

SmtpSendMailMergeAsync Method (String, EmailAddressCollection, DataTable)
async/await version of SendMailMerge(String, EmailAddressCollection, DataTable).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendMailMergeAsync(
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    DataTable mergeTable
)
Public Function SendMailMergeAsync (
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeTable As DataTable
) As Task(Of Boolean)

Parameters

senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The pattern of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
mergeTable
Type: System.DataDataTable
The data source for mail merge.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the entire mail merge has been processed; false if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SendMailMergeAsync Overload
MailBee.SmtpMail Namespace


Smtp.SendMailMergeAsync Method (String, EmailAddressCollection, IDataReader)

SmtpSendMailMergeAsync Method (String, EmailAddressCollection, IDataReader)
async/await version of SendMailMerge(String, EmailAddressCollection, IDataReader).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SendMailMergeAsync(
    string senderEmailPattern,
    EmailAddressCollection recipientsPattern,
    IDataReader mergeDataReader
)
Public Function SendMailMergeAsync (
    senderEmailPattern As String,
    recipientsPattern As EmailAddressCollection,
    mergeDataReader As IDataReader
) As Task(Of Boolean)

Parameters

senderEmailPattern
Type: SystemString
The e-mail address template of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address template will be taken from From property.
recipientsPattern
Type: MailBee.MimeEmailAddressCollection
The pattern of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
mergeDataReader
Type: System.DataIDataReader
The data source for mail merge.

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if the entire mail merge has been processed; false if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SendMailMergeAsync Overload
MailBee.SmtpMail Namespace


Smtp.StartTls Method

SmtpStartTls Method
Requests the mail server to start TLS/SSL negotiation and protect the existing connection with a security layer.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool StartTls()
Public Function StartTls As Boolean

Return Value

Type: Boolean
true if TLS/SSL negotiation succeeded and the connection is now secured with TLS/SSL layer; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method lets the developer to switch the existing, already opened connection (usually, on port 25 or 587), to SSL/TLS mode. If the connection has been opened on a dedicated SSL port from the start (usually, port 465), the developer doesn't need to call this method.

The developer must call Hello method prior to calling StartTls. Also, Hello method must be called again after StartTls because TLS/SSL negotiation resets the connection.

As alternative to calling StartTls method, the developer can ask MailBee to start TLS/SSL negotiation automatically by setting SslMode property value to OnConnect or UseStartTls.

AutodetectPortAndSslMode property may cause MailBee to automatically enable TLS/SSL for some well-known hosts or ports even if SslMode property of the current connection (specified by SmtpServer object) has its default value. Be sure to always check IsSslConnection value prior to calling StartTls.

Note Note
Not all mail servers support STARTTLS functionality.
Examples
This sample attempts to establish TLS/SSL connection with the SMTP server, logs in an account on this server and sends a mail message on success.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");
mailer.Connect();
mailer.Hello();
if (!mailer.IsSslConnection)
{
    mailer.StartTls();
    mailer.Hello();
}
mailer.Login();
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("kathy@company.com");
mailer.Subject = "Report";
mailer.BodyPlainText = "The report contents";
mailer.Send();
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp
mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")
mailer.Connect()
mailer.Hello()
If Not imp.IsSslConnection Then
    mailer.StartTls()
    mailer.Hello()
End If
mailer.Login()
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("kathy@company.com")
mailer.Subject = "Report"
mailer.BodyPlainText = "The report contents"
mailer.Send()
mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpServerSslMode
SmtpServerSslProtocol


Smtp.StartTlsAsync Method

SmtpStartTlsAsync Method
async/await version of StartTls.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> StartTlsAsync()
Public Function StartTlsAsync As Task(Of Boolean)

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true if TLS/SSL negotiation succeeded and the connection is now secured with TLS/SSL layer; otherwise, false.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.StopJobs Method

SmtpStopJobs Method
Notifies MailBee to stop processing jobs, completing sending out of all messages currently being processed.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void StopJobs()
Public Sub StopJobs
Exceptions
Exception | Condition
MailBeeInvalidStateException | The operation currently in progress is not processing jobs so it cannot be stopped with this method.
Remarks

This method can be used to suspend jobs processing, if desired. Once StopJobs method is called and sending of all e-mail messages currently being processed is completed, the sending operation stops.

This method can stop submitting e-mails to the pickup folder (initiated with SubmitJobsToPickupFolder(String, Boolean) method) as well as sending e-mails out.

Because this method does not stop jobs processing immediately but simply tells MailBee to do not process new e-mails, it may take some time to complete processing e-mails currently being sent. Thus, the component will still be busy (IsBusy is true) after this method completes. To stop processing jobs immediately, the developer should rather use Abort method.

To resume the stopped process, the developer should call the same method that was originally called to start the processing (for instance, SendJobs or SubmitJobsToPickupFolder(String, Boolean) method).

If you want to make jobs processing stop automatically whenever an error occurs (i.e. any e-mail could not be sent), set StopJobsOnError property to true before starting processing jobs.

Note Note
It's not possible to use SendMailMerge(String, EmailAddressCollection, DataTable) method to resume the stopped mail-merge process. To resume the mail-merge processing initiated with SendMailMerge(String, EmailAddressCollection, DataTable) method, use SendJobs method.
Examples
This console sample sends mail merge out, stopping the entire process if number of consecutive failures to send an e-mail exceeds 10. This allows the application to skip random errors of sending e-mails to specific e-mail addresses but stop processing in the case if the error becomes permanent. It's assumed that it's unusual to get 10 bad e-mail addresses one-by-one and such situation should be treated as possible failure of the mail server itself.
Note Note
If the application is made multi-threaded (MaxThreadCount is not 1), multiple threads will access failureCount variable simultaneously. Thus, to keep failureCount value accurate, the application must synchronize access to it. However, exact value of failureCount is not important in our case (even if synchronization issues made it evaluate to, let's say, 9 or 12 instead of 10) since we only need it to determine if it's big or not. It's no big difference if the application stopped after 9 or after 10 (or 12) consecutive failures.
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    // Number of continuous failures (a series of failures occurring one-by-one).
    static int failureCount    = 0;

    // If any e-mail succeeded, reset the counter.
    static void mailer_MessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        failureCount = 0;
        Console.WriteLine("Message sent.");
    }

    // Increment the counter.
    static void mailer_MessageNotSent(object sender, SmtpMessageNotSentEventArgs e)
    {
        failureCount++;
        Console.WriteLine("Message not sent.");

        if (failureCount > 10)
        {
            // Tolerate no longer than 10 failures one-by-one.
            ((Smtp)sender).StopJobs();
            Console.WriteLine("Too many messages not sent.");
        }
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Uncomment the line below to use unlimited number of worker threads (up to 60)
        // and increase performance. Note that not all SMTP servers support this.

        // mailer.MaxThreadCount = -1;

        // Subscribe to events to track send bulk mail progress.
        mailer.MessageSent += new SmtpMessageSentEventHandler(mailer_MessageSent);
        mailer.MessageNotSent += new SmtpMessageNotSentEventHandler(mailer_MessageNotSent);

        // Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        DataTable table = new DataTable();

        // Connect to the database and populate mail merge job to-do list with
        // the data from "mailing_list" table.
        using (OleDbConnection conn = new OleDbConnection(connParams))
        {
            // Open the connection and get the data.
            OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = command;
            adapter.Fill(table);
        }

        // Run mail merge.
        mailer.SendMailMerge(null, null, table);
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    ' Number of continuous failures (a series of failures occurring one-by-one).
    Shared failureCount As Integer = 0

    ' If any e-mail succeeded, reset the counter.
    Shared Sub mailer_MessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        failureCount = 0
        Console.WriteLine("Message sent.")
    End Sub

    ' Increment the counter.
    Shared Sub mailer_MessageNotSent(ByVal sender As Object, ByVal e As SmtpMessageNotSentEventArgs)
        failureCount = failureCount + 1
        Console.WriteLine("Message not sent.")

        If failureCount > 10 Then
            ' Tolerate no longer than 10 failures one-by-one.
            CType(sender, Smtp).StopJobs()
            Console.WriteLine("Too many messages not sent.")
        End If
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Uncomment the line below to use unlimited number of worker threads (up to 60)
        ' and increase performance. Note that not all SMTP servers support this.

        ' mailer.MaxThreadCount = -1;

        ' Subscribe to events to track send bulk mail progress.
        AddHandler mailer.MessageSent, AddressOf mailer_MessageSent
        AddHandler mailer.MessageNotSent, AddressOf mailer_MessageNotSent

        ' Setup SMTP server parameters.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        Dim table As DataTable = New DataTable

        ' Connect to the database and populate mail merge job to-do list with
        ' the data from "mailing_list" table.
        Dim conn As OleDbConnection
        Try
            conn = New OleDbConnection(connParams)

            ' Open the connection and get the data.
            Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
            conn.Open()
            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
            adapter.SelectCommand = command
            adapter.Fill(table)
        Finally
            If Not conn Is Nothing Then
                conn.Close()
            End If
        End Try

        ' Run mail merge.
        mailer.SendMailMerge(Nothing, Nothing, table)
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpStopJobsOnError
SmtpAbort


Smtp.SubmitJobsToPickupFolder Method

SmtpSubmitJobsToPickupFolder Method
Saves all e-mails in the pending jobs queue (including e-mails generated via mail merge) as files in the pickup folder of MailBee.NET Queue or IIS SMTP service.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool SubmitJobsToPickupFolder(
    string pickupFolderName,
    bool doubleFirstDotAtLine
)
Public Function SubmitJobsToPickupFolder (
    pickupFolderName As String,
    doubleFirstDotAtLine As Boolean
) As Boolean

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: Boolean
true, if the entire queue of pending jobs has been processed and saved; false, if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method can be used to submit jobs directly to MailBee.NET Queue or IIS SMTP service bypassing SMTP protocol. This greatly improves performance of sending large volumes of jobs when MailBee.NET Queue or IIS SMTP server is installed on the same machine or in the same LAN as the computer running MailBee. This method neither creates nor requires network connection.

Consider setting mailer.Message.Builder.SetDateOnSend to false when submitting to the pickup folder (mailer is Smtp instance). See SetDateOnSend for details.

Note Note
Although this method saves messages into files rather than sends them out, most methods and properties affecting SendJobs method execution (such as StopJobs or StopJobsOnError) apply to SubmitJobsToPickupFolder(String, Boolean) method as well. The same applies to processing of job queues (such as JobsPending).
In the case if messages are saved to pickup folder rather than being sent out, it's recommended to set StopJobsOnError to true. This is because if any error occurs during saving files (for instance, disk is full), most probably this error will repeat for all subsequent messages and it doesn't make sense to continue processing.
Examples
This console sample performs mail merge via submitting resulting messages into IIS SMTP pickup folder. Events are used to track progress of the operation.
C#
VB
Copy
using System;
using System.Data;
using System.Data.OleDb;
using MailBee;
using MailBee.Mime;
using MailBee.SmtpMail;

class Sample
{
    static void mailer_MergingMessage(object sender, SmtpMergingMessageEventArgs e)
    {
        Console.WriteLine("Will create an e-mail from data row #" + e.MergeRowIndex);
    }

    static void mailer_SubmittingMessageToPickupFolder(object sender,
        SmtpSubmittingMessageToPickupFolderEventArgs e)
    {
        Console.WriteLine("Will queue an e-mail from data row #" + e.MergeRowIndex);
    }

    static void mailer_MessageSubmittedToPickupFolder(object sender,
        SmtpMessageSubmittedToPickupFolderEventArgs e)
    {
        Console.WriteLine("The e-mail from data row #" + e.MergeRowIndex +
            " saved as " + e.Filename);
    }

    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Enabled = true;
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Subscribe to 3 events to track send bulk mail progress.
        mailer.MergingMessage += new SmtpMergingMessageEventHandler(mailer_MergingMessage);
        mailer.SubmittingMessageToPickupFolder +=
            new SmtpSubmittingMessageToPickupFolderEventHandler(
            mailer_SubmittingMessageToPickupFolder
            );
        mailer.MessageSubmittedToPickupFolder +=
            new SmtpMessageSubmittedToPickupFolderEventHandler(
            mailer_MessageSubmittedToPickupFolder
            );

        // Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>";
        mailer.Message.To.AsString = "##Name## <##Email##>";
        mailer.Message.Subject = "Our Jan/2007 newsletter";

        // Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>";

        // Specify database connection string (it may be different in your case).
        string connParams = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;";

        // Connect to the database and populate mail merge job to-do list with
        // the data from "mailing_list" table.
        using (OleDbConnection conn = new OleDbConnection(connParams))
        {
            // Open the connection and get the data.
            OleDbCommand command = new OleDbCommand("SELECT * FROM mailing_list", conn);
            conn.Open();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            DataTable table = new DataTable();
            adapter.SelectCommand = command;
            adapter.Fill(table);

            mailer.AddJob(null, null, null, table);
        }

        // Run mail merge.
        mailer.SubmitJobsToPickupFolder(@"C:\Inetpub\mailroot\Pickup", true);
    }
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports MailBee
Imports MailBee.Mime
Imports MailBee.SmtpMail

Class Sample
    Shared Sub mailer_MergingMessage(ByVal sender As Object, ByVal e As SmtpMergingMessageEventArgs)
        Console.WriteLine("Will create an e-mail from data row #" & e.MergeRowIndex)
    End Sub

    Shared Sub mailer_SubmittingMessageToPickupFolder(ByVal sender As Object, _
            ByVal e As SmtpSubmittingMessageToPickupFolderEventArgs)
        Console.WriteLine("Will queue an e-mail from data row #" & e.MergeRowIndex)
    End Sub

    Shared Sub mailer_MessageSubmittedToPickupFolder(ByVal sender As Object, _
             ByVal e As SmtpMessageSubmittedToPickupFolderEventArgs)
        Console.WriteLine("The e-mail from data row #" & e.MergeRowIndex & " saved as " & e.Filename)
    End Sub

    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp

        ' Logging into a file is useful for troubleshooting.
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Enabled = True
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Subscribe to 3 events to track send bulk mail progress.
        AddHandler mailer.MergingMessage, AddressOf mailer_MergingMessage
        AddHandler mailer.SubmittingMessageToPickupFolder, AddressOf mailer_SubmittingMessageToPickupFolder
        AddHandler mailer.MessageSubmittedToPickupFolder, AddressOf mailer_MessageSubmittedToPickupFolder

        ' Setup e-mail message header template for mail merge.
        mailer.Message.From.AsString = "John Doe <john.doe@domain.com>"
        mailer.Message.To.AsString = "##Name## <##Email##>"
        mailer.Message.Subject = "Our Jan/2007 newsletter"

        ' Setup HTML body template.
        mailer.Message.BodyHtmlText = "<html>##Body##</html>"

        ' Specify database connection string (it may be different in your case).
        Dim connParams As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\newsletter.mdb;"

        ' Connect to the database and populate mail merge job to-do list with
        ' the data from "mailing_list" table.
        Dim conn As OleDbConnection
        Try
            conn = New OleDbConnection(connParams)

            ' Open the connection and get the data.
            Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM mailing_list", conn)
            conn.Open()
            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter
            Dim table As DataTable = New DataTable
            adapter.SelectCommand = command
            adapter.Fill(table)

            mailer.AddJob(Nothing, Nothing, Nothing, table)
        Finally
            If Not conn Is Nothing Then
                conn.Close()
            End If

        End Try

        ' Run mail merge.
        mailer.SubmitJobsToPickupFolder("C:\Inetpub\mailroot\Pickup", True)
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SubmitJobsToPickupFolderAsync Method

SmtpSubmitJobsToPickupFolderAsync Method
async/await version of SubmitJobsToPickupFolder(String, Boolean).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<bool> SubmitJobsToPickupFolderAsync(
    string pickupFolderName,
    bool doubleFirstDotAtLine
)
Public Function SubmitJobsToPickupFolderAsync (
    pickupFolderName As String,
    doubleFirstDotAtLine As Boolean
) As Task(Of Boolean)

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: Task Boolean
A task that represents the asynchronous operation. The value of TResult parameter is true, if the entire queue of pending jobs has been processed and saved; false, if the operation was stopped due to an error.
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolder Method

SmtpSubmitToPickupFolder Method
Overload List
Name | Description
SubmitToPickupFolder(String, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
SubmitToPickupFolder(String, String, String, String, Boolean) | Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolder Method (String, Boolean)

SmtpSubmitToPickupFolder Method (String, Boolean)
Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SubmitToPickupFolder(
    string pickupFolderName,
    bool doubleFirstDotAtLine
)
Public Function SubmitToPickupFolder (
    pickupFolderName As String,
    doubleFirstDotAtLine As Boolean
) As String

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: String
On success, the filename (without folder path) of the file saved in the pickup folder; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method can be used to submit messages directly to MailBee.NET Queue or IIS SMTP service bypassing SMTP protocol. This greatly improves performance of sending large volumes of e-mails when MailBee.NET Queue or IIS SMTP server is installed on the same machine or in the same LAN as the computer running MailBee. This method neither creates nor requires network connection.

Consider setting mailer.Message.Builder.SetDateOnSend to false when submitting to the pickup folder (mailer is Smtp instance). See SetDateOnSend for details.

Note Note
This method can return a null reference also if SubmittingMessageToPickupFolder even handler set SubmitIt to false.
Examples
This sample submits a mail message to IIS SMTP server by placing it in the pickup folder, and displays the full path to the stored .EML file.
Note Note
Usually, the stored message file is immediately picked up by IIS SMTP service and thus gets deleted from the pickup folder. That's normal behavior indicating IIS SMTP service is running. The same is true for MailBee.NET Queue.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("kathy@company.com");
mailer.Subject = "Report";
mailer.BodyPlainText = "The report contents";
string pickupFolderPath = @"C:\Inetpub\mailroot\Pickup";
string filename = mailer.SubmitToPickupFolder(pickupFolderPath, true);
Console.WriteLine("Saved into: " + pickupFolderPath + @"\" + filename);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("kathy@company.com")
mailer.Subject = "Report"
mailer.BodyPlainText = "The report contents"
Dim pickupFolderPath As String = "C:\Inetpub\mailroot\Pickup"
Dim filename As String = mailer.SubmitToPickupFolder(pickupFolderPath, True)
Console.WriteLine("Saved into: " & pickupFolderPath & "\" & filename)
See Also

Reference

Smtp Class
SubmitToPickupFolder Overload
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolder Method (String, String, String, EmailAddressCollection, Boolean)

SmtpSubmitToPickupFolder Method (String, String, String, EmailAddressCollection, Boolean)
Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SubmitToPickupFolder(
    string pickupFolderName,
    string filename,
    string senderEmail,
    EmailAddressCollection recipients,
    bool doubleFirstDotAtLine
)
Public Function SubmitToPickupFolder (
    pickupFolderName As String,
    filename As String,
    senderEmail As String,
    recipients As EmailAddressCollection,
    doubleFirstDotAtLine As Boolean
) As String

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
filename
Type: SystemString
The filename (without folder path) of the file to be saved, or a null reference (Nothing in Visual Basic). If latter, MailBee will automatically generate a unique filename.
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: String
On success, the filename (without folder path) of the file saved in the pickup folder; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method can be used to submit messages directly to MailBee.NET Queue or IIS SMTP service bypassing SMTP protocol. This greatly improves performance of sending large volumes of e-mails when MailBee.NET Queue or IIS SMTP server is installed on the same machine or in the same LAN as the computer running MailBee. This method neither creates nor requires network connection.

To specify international e-mail addresses (IDN domains), call EscapeIdnDomain(String) for senderEmail string and ToIdnAddress for recipients collection to convert e-mail addresses from human-readable into SMTP-safe format.

Consider setting mailer.Message.Builder.SetDateOnSend to false when submitting to the pickup folder (mailer is Smtp instance). See SetDateOnSend for details.

Note Note
This method can return a null reference also if SubmittingMessageToPickupFolder even handler set SubmitIt to false.
Examples
This sample submits a mail message to IIS SMTP server by placing it in the pickup folder. The message file will be saved as "C:\Inetpub\mailroot\Pickup\001.eml".
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("kathy@company.com");
mailer.Subject = "Report";
mailer.BodyPlainText = "The report contents";
mailer.SubmitToPickupFolder(@"C:\Inetpub\mailroot\Pickup", "001.eml", "bounce@domain.com",
    (EmailAddressCollection)null, true);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("kathy@company.com")
mailer.Subject = "Report"
mailer.BodyPlainText = "The report contents"
mailer.SubmitToPickupFolder("C:\Inetpub\mailroot\Pickup", "001.eml", "bounce@domain.com", _
    CType(Nothing, EmailAddressCollection), True)
See Also

Reference

Smtp Class
SubmitToPickupFolder Overload
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolder Method (String, String, String, String, Boolean)

SmtpSubmitToPickupFolder Method (String, String, String, String, Boolean)
Saves the mail message as a file in the pickup folder of MailBee.NET Queue or IIS SMTP service.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string SubmitToPickupFolder(
    string pickupFolderName,
    string filename,
    string senderEmail,
    string recipientEmails,
    bool doubleFirstDotAtLine
)
Public Function SubmitToPickupFolder (
    pickupFolderName As String,
    filename As String,
    senderEmail As String,
    recipientEmails As String,
    doubleFirstDotAtLine As Boolean
) As String

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
filename
Type: SystemString
The filename (without folder path) of the file to be saved, or a null reference (Nothing in Visual Basic). If latter, MailBee will automatically generate a unique filename.
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipientEmails
Type: SystemString
The comma-separted list of the recipients e-mail addresses. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: String
On success, the filename (without folder path) of the file saved in the pickup folder; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
Remarks

This method can be used to submit messages directly to MailBee.NET Queue or IIS SMTP service bypassing SMTP protocol. This greatly improves performance of sending large volumes of e-mails when MailBee.NET Queue or IIS SMTP server is installed on the same machine or in the same LAN as the computer running MailBee. This method neither creates nor requires network connection.

To specify international e-mail addresses (IDN domains), call EscapeIdnDomain(String) for senderEmail string and for each individual value in recipientEmails to convert e-mail addresses from human-readable into SMTP-safe format.

Consider setting mailer.Message.Builder.SetDateOnSend to false when submitting to the pickup folder (mailer is Smtp instance). See SetDateOnSend for details.

Note Note
This method can return a null reference also if SubmittingMessageToPickupFolder even handler set SubmitIt to false.
Examples
This sample submits a mail message to IIS SMTP server by placing it in the pickup folder. The message file will be saved as "C:\Inetpub\mailroot\Pickup\001.eml". In the message itself, no recipients specified, but the message will still be sent to "alex@company.com" and "jane@domain.com".
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("kathy@company.com");
mailer.Subject = "Report";
mailer.BodyPlainText = "The report contents";
mailer.SubmitToPickupFolder(@"C:\Inetpub\mailroot\Pickup", "001.eml", null,
    "alex@company.com,jane@domain.com", true);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class).
Dim mailer As New Smtp
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("kathy@company.com")
mailer.Subject = "Report"
mailer.BodyPlainText = "The report contents"
mailer.SubmitToPickupFolder("C:\Inetpub\mailroot\Pickup", "001.eml", Nothing, _
    "alex@company.com,jane@domain.com", True)
See Also

Reference

Smtp Class
SubmitToPickupFolder Overload
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolderAsync Method

SmtpSubmitToPickupFolderAsync Method
Overload List
 | Name | Description
Public method | SubmitToPickupFolderAsync(String, Boolean) | async/await version of SubmitToPickupFolder(String, Boolean).
Public method | SubmitToPickupFolderAsync(String, String, String, EmailAddressCollection, Boolean) | async/await version of SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean).
Public method | SubmitToPickupFolderAsync(String, String, String, String, Boolean) | async/await version of SubmitToPickupFolder(String, String, String, String, Boolean).
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolderAsync Method (String, Boolean)

SmtpSubmitToPickupFolderAsync Method (String, Boolean)
async/await version of SubmitToPickupFolder(String, Boolean).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string> SubmitToPickupFolderAsync(
    string pickupFolderName,
    bool doubleFirstDotAtLine
)
Public Function SubmitToPickupFolderAsync (
    pickupFolderName As String,
    doubleFirstDotAtLine As Boolean
) As Task(Of String)

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: Task String
A task that represents the asynchronous operation. On success, the value of TResult parameter is the filename (without folder path) of the file saved in the pickup folder; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SubmitToPickupFolderAsync Overload
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolderAsync Method (String, String, String, EmailAddressCollection, Boolean)

SmtpSubmitToPickupFolderAsync Method (String, String, String, EmailAddressCollection, Boolean)
async/await version of SubmitToPickupFolder(String, String, String, EmailAddressCollection, Boolean).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string> SubmitToPickupFolderAsync(
    string pickupFolderName,
    string filename,
    string senderEmail,
    EmailAddressCollection recipients,
    bool doubleFirstDotAtLine
)
Public Function SubmitToPickupFolderAsync (
    pickupFolderName As String,
    filename As String,
    senderEmail As String,
    recipients As EmailAddressCollection,
    doubleFirstDotAtLine As Boolean
) As Task(Of String)

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
filename
Type: SystemString
The filename (without folder path) of the file to be saved, or a null reference (Nothing in Visual Basic). If latter, MailBee will automatically generate a unique filename.
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipients
Type: MailBee.MimeEmailAddressCollection
The list of the message recipients. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: Task String
A task that represents the asynchronous operation. On success, the value of TResult parameter is the filename (without folder path) of the file saved in the pickup folder; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SubmitToPickupFolderAsync Overload
MailBee.SmtpMail Namespace


Smtp.SubmitToPickupFolderAsync Method (String, String, String, String, Boolean)

SmtpSubmitToPickupFolderAsync Method (String, String, String, String, Boolean)
async/await version of SubmitToPickupFolder(String, String, String, String, Boolean).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<string> SubmitToPickupFolderAsync(
    string pickupFolderName,
    string filename,
    string senderEmail,
    string recipientEmails,
    bool doubleFirstDotAtLine
)
Public Function SubmitToPickupFolderAsync (
    pickupFolderName As String,
    filename As String,
    senderEmail As String,
    recipientEmails As String,
    doubleFirstDotAtLine As Boolean
) As Task(Of String)

Parameters

pickupFolderName
Type: SystemString
The full physical path to MailBee.NET Queue or IIS SMTP pickup folder (such as "C:\Inetpub\mailroot\Pickup").
filename
Type: SystemString
The filename (without folder path) of the file to be saved, or a null reference (Nothing in Visual Basic). If latter, MailBee will automatically generate a unique filename.
senderEmail
Type: SystemString
The e-mail address of the sender. If it's a null reference (Nothing in Visual Basic), the e-mail address is taken from From property.
recipientEmails
Type: SystemString
The comma-separted list of the recipients e-mail addresses. If it's a null reference (Nothing in Visual Basic), the recipients list is combined from To, Cc, and Bcc lists.
doubleFirstDotAtLine
Type: SystemBoolean
You must set it to true when submitting to IIS SMTP pickup folder and to false when using MailBee.NET Queue. SMTP protocol requires the client to double the dot character (make ".." from ".") when it appears at the beginning of a line. However, unlike MailBee.NET Queue, IIS SMTP service is not capable of performing this conversion, and doubleFirstDotAtLine parameter workarounds this (when true, MailBee itself will double dots when required).

Return Value

Type: Task String
A task that represents the asynchronous operation. On success, the value of TResult parameter is the filename (without folder path) of the file saved in the pickup folder; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
Exception | Condition
MailBeeException | An error occurred and ThrowExceptions is true.
See Also

Reference

Smtp Class
SubmitToPickupFolderAsync Overload
MailBee.SmtpMail Namespace


Smtp.TestSend Method

SmtpTestSend Method
Tests sending a mail message to the recipients without actual submitting of the message data.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public TestSendResult TestSend(
    SendFailureThreshold failureThreshold
)
Public Function TestSend (
    failureThreshold As SendFailureThreshold
) As TestSendResult

Parameters

failureThreshold
Type: MailBee.SmtpMailSendFailureThreshold
Specifies whether the method should succeed if all recipients succeed, or at least one recipient succeeds (even if other recipients fail).

Return Value

Type: TestSendResult
OK if the sender and any or all (depends on failureThreshold value) recipients have been accepted by for delivery; otherwise, one of TestSendResult values specifying the error details.
Remarks

This method performs the actual attempt to connect to a mail server in order to check if the address exists. If you first need to check if the e-mail address string itself if of the correct format, use ValidateEmailAddressSyntax(String) static method.

If you need to test bulk of e-mail addresses, consider using EmailAddressValidator component.

When failureThreshold is Default, failed recipients are always allowed in direct send mode, and can be either disabled or enabled when submitting to SMTP relay server (depending on AllowRefusedRecipients property value). Other values of failureThreshold parameter allow the developer to override the default behavior for both direct send and SMTP relay send modes.

This method can be used prior to actual Send method call in order to make sure the sender and all recipients will be accepted during send mail operation. If any/all recipients fail, the method returns corresponding TestSendResult value. MailBeeException is not thrown. ErrorOccurred event is still raised, so the developer can obtain additional information about the error by handling this event.

TestSend(SendFailureThreshold) method is especially useful in direct send scenarios (discovering SMTP MX servers via DNS MX lookup rather than using predefined SMTP relay server). When no SMTP relay server is used, it's not possible to send to all recipients without fail, and cancel sending if at least one recipient fails (so that the message would be sent either to all recipients or to nobody). This is because the message may be sent to many SMTP MX servers in direct send mode, and if it was already sent to the first server and fails for the second one, it's not possible to tell the first server to rollback and cancel the recent mail submission. This is different from sending to SMTP relay server, where entire send mail operation is a single transaction. If it's cancelled, no recipients previously submitted will receive the message. When sending to an SMTP relay server, the developer can use AllowRefusedRecipients property to control whether the component should return an error if at least one recipient fails.

Note Note
The mail message submission may still fail on Send operation even if all recipients and the sender are valid. This typically occurs when the server accepts the sender and the recipients but rejects the message data (for instance, the message is too large, or the server decides the message contains spam or virus). Also, the server might be down at the moment when Send method gets called even if it was fine during TestSend(SendFailureThreshold) method call.
Examples
This sample sends a mail message in direct send mode (no SMTP relay server is used). To make sure all recipients will receive the message, TestSend(SendFailureThreshold) is called first. Extensive error checking is performed in ErrorOccurred event handler to learn why the error occurred.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.DnsMX;
using MailBee.Mime;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        if (e.Reason is MailBeeSmtpRefusedRecipientException)
        {
            MailBeeSmtpRefusedRecipientException ex =
                e.Reason as MailBeeSmtpRefusedRecipientException;
            Console.WriteLine(ex.RefusedRecipientEmail + " was refused by the server");
        }
        else if (e.Reason is MailBeeDnsNameErrorException)
        {
            MailBeeDnsNameErrorException ex = e.Reason as MailBeeDnsNameErrorException;
            Console.WriteLine(ex.HostName + " is unknown host");
        }
        else if (e.Reason is MailBeeDnsProtocolNegativeResponseException)
        {
            MailBeeDnsProtocolNegativeResponseException ex =
                e.Reason as MailBeeDnsProtocolNegativeResponseException;
            Console.WriteLine("DNS server returned error for " + ex.HostName);
        }
        else if (e.Reason is MailBeeConnectionException)
        {
            MailBeeConnectionException ex = e.Reason as MailBeeConnectionException;
            if (ex.Protocol == TopLevelProtocolType.Smtp)
            {
                Console.WriteLine("Connection problem with " +
                    ex.RemoteHostName + " SMTP MX server ");
            }
        }
        else
        {
            Console.WriteLine(e.Reason.Message);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers list from OS settings or config file
        // (like app.config).
        mailer.DnsServers.Autodetect();

        mailer.From.AsString = "John Doe <jdoe@domain.com>";

        // Specify recipients.
        mailer.To.AsString = "no-display-name@website.com, \"Bill Smith, Jr.\" &lt;bill.smith@company.com&gt;";
        mailer.To.AddFromString("Kathy Smith &lt;k.smith@domain.com&gt;");
        mailer.To.AddFromString("email@address.com");
        mailer.To.Add("Mike Jackson, Sales Manager", "mj@company.com", "Sales Department");

        mailer.Subject = "Newsletter";
        mailer.BodyPlainText = "This is our weekly newsletter.";

        // Subscribe to the ErrorOccurred event.
        mailer.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Make sure all the recipients are ok.
        if (mailer.TestSend(SendFailureThreshold.AllRecipientsFailed) != TestSendResult.OK)
        {
            Console.WriteLine("No recipients can receive the message.");
        }
        else if (mailer.GetRefusedRecipients().Count > 0)
        {
            Console.WriteLine("The following recipients failed: " +
                mailer.GetRefusedRecipients().ToString());
        }
        else
        {
            Console.WriteLine("All recipients are ok. Will send the message now.");
            mailer.Send();
            Console.WriteLine("Sent to: " + mailer.GetAcceptedRecipients().ToString());
        }
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.DnsMX
Imports MailBee.Mime

Class Sample
    ' ErrorOccurred event handler.
    Private Shared Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        If (TypeOf e.Reason Is MailBeeSmtpRefusedRecipientException) Then
            Dim ex As MailBeeSmtpRefusedRecipientException = e.Reason
            Console.WriteLine(ex.RefusedRecipientEmail & " was refused by the server")
        ElseIf (TypeOf e.Reason Is MailBeeDnsNameErrorException) Then
            Dim ex As MailBeeDnsNameErrorException = e.Reason
            Console.WriteLine(ex.HostName & " is unknown host")
        ElseIf (TypeOf e.Reason Is MailBeeDnsProtocolNegativeResponseException) Then
            Dim ex As MailBeeDnsProtocolNegativeResponseException = e.Reason
            Console.WriteLine("DNS server returned error for " + ex.HostName)
        ElseIf (TypeOf e.Reason Is MailBeeConnectionException) Then
            Dim ex As MailBeeConnectionException = e.Reason
            If (ex.Protocol = TopLevelProtocolType.Smtp) Then
                Console.WriteLine("Connection problem with " & _
                    ex.RemoteHostName & " SMTP MX server ")
            End If
        Else
            Console.WriteLine(e.Reason.Message)
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers list from OS settings or config file
        ' (like app.config).
        mailer.DnsServers.Autodetect()

        mailer.From.AsString = "John Doe <jdoe@domain.com>"

        ' Specify recipients.
        mailer.To.AsString = "no-display-name@website.com, ""Bill Smith, Jr."" <bill.smith@company.com>"
        mailer.To.AddFromString("Kathy Smith <k.smith@domain.com>")
        mailer.To.AddFromString("email@address.com")
        mailer.To.Add("Mike Jackson, Sales Manager", "mj@company.com", "Sales Department")

        mailer.Subject = "Newsletter"
        mailer.BodyPlainText = "This is our weekly newsletter."

        ' Subscribe to the ErrorOccurred event.
        AddHandler mailer.ErrorOccurred, AddressOf OnErrorOccurred

        ' Make sure all the recipients are ok.
        If (mailer.TestSend(SendFailureThreshold.AllRecipientsFailed) <> TestSendResult.OK) Then
            Console.WriteLine("No recipients can receive the message.")
        ElseIf (mailer.GetRefusedRecipients().Count > 0) Then
            Console.WriteLine("The following recipients failed: " & _
                mailer.GetRefusedRecipients().ToString())
        Else
            Console.WriteLine("All recipients are ok. Will send the message now.")
            mailer.Send()
            Console.WriteLine("Sent to: " & mailer.GetAcceptedRecipients().ToString())
        End If
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpValidateEmailAddressSyntax(String)


Smtp.TestSendAsync Method

SmtpTestSendAsync Method
async/await version of TestSend(SendFailureThreshold).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Task<TestSendResult> TestSendAsync(
    SendFailureThreshold failureThreshold
)
Public Function TestSendAsync (
    failureThreshold As SendFailureThreshold
) As Task(Of TestSendResult)

Parameters

failureThreshold
Type: MailBee.SmtpMailSendFailureThreshold
Specifies whether the method should succeed if all recipients succeed, or at least one recipient succeeds (even if other recipients fail).

Return Value

Type: Task TestSendResult
A task that represents the asynchronous operation. The value of TResult parameter is OK if the sender and any or all (depends on failureThreshold value) recipients have been accepted by for delivery; otherwise, one of TestSendResult values specifying the error details.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ValidateEmailAddressSyntax Method

SmtpValidateEmailAddressSyntax Method
Verifies if the specified string is a correctly formatted e-mail address.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static bool ValidateEmailAddressSyntax(
    string email
)
Public Shared Function ValidateEmailAddressSyntax (
    email As String
) As Boolean

Parameters

email
Type: SystemString
The e-mail address string.

Return Value

Type: Boolean
true if the syntax of the specified string is correct; otherwise, false.
Remarks
This method only checks the syntax of the e-mail address. It does NOT make any network connections and thus does NOT actually check if this address exists and you can send e-mails there. If you need further checks, you can use TestSend(SendFailureThreshold) method. To test bulk of e-mail addresses, consider using EmailAddressValidator component.
Note Note
As this method is static, you do not need to create an instance of Smtp object in order to use it.
Examples
This example returns Correct syntax as _mike.o'neil_loves_underscores@sub-domain.travel address is complex but still has valid syntax.
C#
VB
Copy
using MailBee.SmtpMail;

if (Smtp.ValidateEmailAddressSyntax("_mike.o'neil_loves_underscores@sub-domain.travel"))
{
    Console.WriteLine("Correct syntax");
}
else
{
    Console.WriteLine("Wrong syntax");
}
Imports MailBee.SmtpMail

If Smtp.ValidateEmailAddressSyntax("_mike.o'neil_loves_underscores@sub-domain.travel") Then
    Console.WriteLine("Correct syntax")
Else
    Console.WriteLine("Wrong syntax")
End If
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Wait Method

SmtpWait Method
Overload List
 | Name | Description
Public method | Wait | Obsolete. Waits until the currently running (if any) asynchronous method is finished.
Public method | Wait(Int32) | Obsolete. Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Wait Method

SmtpWait Method

Note: This API is now obsolete.

Waits until the currently running (if any) asynchronous method is finished.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+.")]
public void Wait()
<ObsoleteAttribute("This method is obsolete in .NET 4.5+.")>
Public Sub Wait
Exceptions
Exception | Condition
MailBeeInvalidStateException | RaiseEventsViaMessageLoop is true
Remarks
Note Note
.NET 4.5+ apps should use XXXAsync methods which can be awaited. The current method is suitable for BeginXXX/EndXXX methods only which are now deprecated.
This method should only be used in WinForms applications in the scenarios when the application message loop is blocked and events raised by asynchronous methods get no chance to be processed.
Caution note Caution
RaiseEventsViaMessageLoop property must be set to false prior to using this method. This is required in order to switch event marshalling mechanism from sending events to the application message loop to the internal thread-independent event processor.

Usually, when the developer uses asynchronous methods which might raise events, it's not possible to use methods like WaitOne(Int32, Boolean), since they would block the message loop and thus prevent events (which are raised on the message loop thread) from getting processed. Wait method provides an alternative approach which addresses the problem.

Another alternative (in WinForms application) to using Wait method is to never block the application message loop and use callback functions instead of waiting for asynchronous method completion.

Note Note
In many cases, it's easier not to use events at all but derive a new class from Smtp class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Smtp Class
Wait Overload
MailBee.SmtpMail Namespace


Smtp.Wait Method (Int32)

SmtpWait Method (Int32)

Note: This API is now obsolete.

Waits the completion of the currently running (if any) asynchronous method for the specified amount of time.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This method is obsolete in .NET 4.5+.")]
public bool Wait(
    int timeoutInterval
)
<ObsoleteAttribute("This method is obsolete in .NET 4.5+.")>
Public Function Wait (
    timeoutInterval As Integer
) As Boolean

Parameters

timeoutInterval
Type: SystemInt32
The amount of time (in milliseconds) the method will wait completion of the currently running asynchronous method before returning false.

Return Value

Type: Boolean
true if the asynchronous method has finished execution during the specified amount of time, false if it's still running.
Exceptions
Exception | Condition
MailBeeInvalidStateException | RaiseEventsViaMessageLoop is true
Remarks
Note Note
.NET 4.5+ apps should use XXXAsync methods which can be awaited. The current method is suitable for BeginXXX/EndXXX methods only which are now deprecated.
This method should only be used in WinForms applications in the scenarios when the application message loop is blocked and events raised by asynchronous methods get no chance to be processed.
Caution note Caution
RaiseEventsViaMessageLoop property must be set to false prior to using this method. This is required in order to switch event marshalling mechanism from sending events to the application message loop to the internal thread-independent event processor.
Usually, when the developer wants to use asynchronous methods which might raise events in a WinForm application, it's not possible to use methods like WaitOne(Int32, Boolean), since they would block the message loop and thus prevent events (which are raised on the message loop thread) from getting processed. Wait method provides an alternative approach which addresses the problem.
Note Note
The developer can also use this method with timeoutInterval set to 0 in order to process currently pending MailBee events. This is useful if some lengthy work is performed on the message loop thread, and the developer wants to periodically let MailBee events get processed and then continue the lengthy work without waiting for the completion of the asynchronous method. See BeginConnect(AsyncCallback, Object) method for examples.
Another alternative (in WinForms application) to using Wait method is to never block the application message loop and use callback functions instead of waiting for asynchronous method completion.
Note Note
In many cases, it's easier not to use events at all but derive a new class from Smtp class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Smtp Class
Wait Overload
MailBee.SmtpMail Namespace


Smtp Properties

Smtp Properties

The Smtp type exposes the following members.

Properties
 | Name | Description
 | Bcc | Gets or sets EmailAddressCollection object specifying BCC: recipients of the message.
 | BodyHtmlText | Gets or sets HTML version of the message body.
 | BodyPlainText | Gets or sets plain-text version of the message body.
 | Cc | Gets or sets EmailAddressCollection object specifying CC: recipients of the message.
 | Charset | Gets or sets charset of the message.
Public property | Conversion8BitTo7bit | Gets or sets if (and how) the component should perform 8bit-to-7bit conversion of the message data if the given SMTP server does not support transmission of 8bit data but the message does contain such data.
Public property | DeliveryNotification | Provides access to properties which control when and how ESMTP Delivery Status Notification messages will be sent to the message sender.
 | DirectSendDefaults | Provides access to the default SMTP server settings to be used when connecting to SMTP servers discovered by MailBee via DNS MX lookup.
 | DnsServers | Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.
 | From | Gets or sets EmailAddress object specifying the message sender.
Public property | IsAborted | Indicates whether Abort method has been called for the component.
Public property | IsBusy | Indicates whether the component is performing a lengthy operation.
Public property | IsConnected | Indicates whether the component is connected to the server.
Public property | IsLoggedIn | Indicates whether the component has already successfully authenticated on the server and logged in the user account.
Public property | IsSmtpContext | Indicates whether the component is currently operating in a single thread mode, and the current connection (if any) is an SMTP connection.
Public property | IsSslConnection | Indicates whether the current connection (if any) is secured with TLS/SSL layer.
Public property | JobsFailed | Gets the list of e-mail tasks failed during processing.
Public property | JobsPending | Gets the list of send-mail (sending a single message or mail-merge) tasks ready for processing.
Public property | JobsRunning | Gets the list of e-mail tasks being processed right now.
Public property | JobsSuccessful | Gets the list of successfully processed e-mail tasks.
 | JobsSyncRoot | Gets the object to be used for synchronized access to the jobs collections.
Public property | LastResult | Gets a numeric code of the last error.
 | LicenseKey | Obsolete. Assigns the license key.
 | Log | Gets the object used for logging MailBee activities into a file or memory buffer.
 | MaxThreadCount | Gets or sets the maximum number of threads MailBee may create during send mail operations.
 | Message | Gets or sets the mail message which will be sent by the component on Send method call.
Public property | RaiseEvents | Gets or sets whether the component will raise any events.
Public property | RaiseEventsViaMessageLoop | Gets or sets whether the events will be raised on the message loop of the application or not.
 | ReplyTo | Gets or sets EmailAddressCollection object specifying e-mail addresses to which the replies to this message should be sent.
Public property | RequestEncoding | Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the server.
Public property | ResponseEncoding | Gets or sets the encoding used to convert a byte data received from the server into a string.
Public property | Site | Gets or sets the object to be used as a site for the component.
 | SmtpServers | Gets the SmtpServerCollection object containing the list of SMTP relay servers to be used for sending mail.
Public property | StopJobsOnError | Gets or sets if processing of the jobs must be stopped if an error occurs.
 | Subject | Gets or sets the subject of the message.
Public property | SynchronizingObject | Gets or sets the object used to marshal the calls of the event handlers.
Public property | ThrowExceptions | Gets or sets whether the component will throw exceptions on errors.
 | To | Gets or sets EmailAddressCollection object specifying To: recipients of the message.
Public property | TrialDaysLeft | Gets the number of days left to the date of the trial license key expiration.
Public property | Version | Gets the version of the MailBee assembly.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Bcc Property

SmtpBcc Property
Gets or sets EmailAddressCollection object specifying BCC: recipients of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Bcc { get; set; }
Public Property Bcc As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
The EmailAddressCollection object representing BCC: field (blind-carbon recipients) of the message.
Remarks
This property is equivalent to Bcc property of Message object.
Note Note
By default, BCC header is not included into the message being sent. BCC recipients still receive the message, but other recipients have no way of knowing this. If required, the developer can suppress removing BCC header on mail send operation by setting Mime.MailMessage.Builder.RemoveBccOnSend property to false.
Examples
Setting BCC: recipients using different methods. Since BCC recipients do not appear in the message header, it makes no sense to include recipients display names into BCC (unless RemoveBccOnSend is false). If display name is included in BCC e-mail address, it's just ignored.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).

Smtp mailer = new Smtp();

mailer.Bcc.AsString = "<bsmith@company.com>, kathy@mail.com";
mailer.Bcc.Add("email@address.com");
mailer.Bcc.Add(new EmailAddress("user@host.com"));

Console.WriteLine(mailer.Bcc.ToString());

// The output.
<bsmith@company.com>, kathy@mail.com, email@address.com, user@host.com
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).

Dim mailer As New Smtp

mailer.Bcc.AsString = "<bsmith@company.com>, kathy@mail.com"
mailer.Bcc.Add("email@address.com")
mailer.Bcc.Add(New EmailAddress("user@host.com"))

Console.WriteLine(mailer.Bcc.ToString())

' The output.
<bsmith@company.com>, kathy@mail.com, email@address.com, user@host.com
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.BodyHtmlText Property

SmtpBodyHtmlText Property
Gets or sets HTML version of the message body.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string BodyHtmlText { get; set; }
Public Property BodyHtmlText As String
    Get
    Set

Property Value

Type: String
A string containing the message body as HTML.
Remarks

This property is equivalent to BodyHtmlText property of Message object.

The developer can import HTML content (and, optionally, linked images, style-sheets, etc) from an HTML file or a web page using LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method of Message object.

Examples
Specifying HTML body of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Specify HTML body using multi-line string constant.
mailer.BodyHtmlText = @"<html>
<head><title>Page title</title></head>
<body>The text of the message. The next word is in <b>bold</b>.</body>;
</html>";
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Specify HTML body using multi-line string constant.
mailer.BodyHtmlText = "<html>" & vbCrLf & _
    "<head><title>Page title</title></head>" & vbCrLf & _
    "<body>The text of the message. The next word is in <b>bold</b>.</body>" & vbCrLf & _
    "</html>"
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.BodyPlainText Property

SmtpBodyPlainText Property
Gets or sets plain-text version of the message body.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string BodyPlainText { get; set; }
Public Property BodyPlainText As String
    Get
    Set

Property Value

Type: String
A string containing the message body as plain-text.
Remarks

This property is equivalent to BodyPlainText property of Message object.

The developer can get plain-text version of the message body from the HTML version by either calling MakePlainBodyFromHtmlBody of Message object or by setting HtmlToPlainMode property of Builder object to IfHtml value.

By default, the message body is encoded using QuotedPrintable content transfer encoding. If required, the developer can change this using MailTransferEncodingPlain property of Message object.

Examples
Specifying plain-text body of the message.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Specify plain-text body using multi-line string constant.
mailer.BodyPlainText = @"Multi-line body text
Some more text here

Signature";
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Specify plain-text body using multi-line string constant.
mailer.BodyPlainText = "Multi-line body text" & vbCrLf & _
    "Some more text here" & vbCrLf & vbCrLf & _
    "Signature"
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Cc Property

SmtpCc Property
Gets or sets EmailAddressCollection object specifying CC: recipients of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection Cc { get; set; }
Public Property Cc As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
The EmailAddressCollection object representing CC: field (carbon recipients) of the message.
Remarks
This property is equivalent to Cc property of Message object.
Examples
Setting CC: recipients using different methods.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

mailer.Cc.AsString = "Bill Smith <bsmith@company.com>, kathy@mail.com, \"John Long, Jr.\" <jl@domain.com>";
mailer.Cc.Add("email@address.com");
mailer.Cc.Add("John Doe, Sales Manager", "jdoe@domain.com");
mailer.Cc.Add(new EmailAddress("user@host.com"));

Console.WriteLine(mailer.Cc.ToString());

// The output.
"Bill Smith" <bsmith@company.com>, kathy@mail.com, "John Long, Jr." <jl@domain.com>, email@address.com, "John Doe, Sales Manager" <jdoe@domain.com>, user@host.com
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

mailer.Cc.AsString = "Bill Smith <bsmith@company.com>, kathy@mail.com, ""John Long, Jr."" <jl@domain.com>"
mailer.Cc.Add("email@address.com")
mailer.Cc.Add("John Doe, Sales Manager", "jdoe@domain.com")
mailer.Cc.Add(New EmailAddress("user@host.com"))

Console.WriteLine(mailer.Cc.ToString())

' The output.
"Bill Smith" <bsmith@company.com>, kathy@mail.com, "John Long, Jr." <jl@domain.com>, email@address.com, "John Doe, Sales Manager" <jdoe@domain.com>, user@host.com
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Charset Property

SmtpCharset Property
Gets or sets charset of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Charset { get; set; }
Public Property Charset As String
    Get
    Set

Property Value

Type: String
The name of the character set the message is composed with. The default value is an empty string.
Remarks

This property is equivalent to Charset property of Message object.

If no charset is specified in the message, mail reader program of the message recipient will use the default system charset to display the message.

Note Note
Some mail servers add charset setting to the message if it has no charset specified. This may cause the message to be displayed incorrectly. To avoid this, always specify Charset property if the message contains non-US characters.
Examples
Setting Windows-1251 charset for the message composed in Russian.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Indicate the message uses Cyrillic charset.
mailer.Charset = "windows-1251";

// "The message subject" in Russian (note that using MailMessage.GetEncodedHeaderValue
// is not necessary, since charset is set for entire message in Charset property).
// MailMessage.GetEncodedHeaderValue is required when charset of the message
// differs from charset of the header value.
mailer.Subject = "Тема сообщения";

// "The message body" in Russian.
mailer.BodyPlainText = "Тело сообщения";
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Indicate the message uses Cyrillic charset.
mailer.Charset = "windows-1251"

' "The message subject" in Russian (note that using MailMessage.GetEncodedHeaderValue
' is not necessary, since charset is set for entire message in Charset property).
' MailMessage.GetEncodedHeaderValue is required when charset of the message
' differs from charset of the header value.
mailer.Subject = "Тема сообщения"

' "The message body" in Russian.
mailer.BodyPlainText = "Тело сообщения"
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Conversion8BitTo7bit Property

SmtpConversion8BitTo7bit Property
Gets or sets if (and how) the component should perform 8bit-to-7bit conversion of the message data if the given SMTP server does not support transmission of 8bit data but the message does contain such data.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Smtp8bitDataConversion Conversion8BitTo7bit { get; set; }
Public Property Conversion8BitTo7bit As Smtp8bitDataConversion
    Get
    Set

Property Value

Type: Smtp8bitDataConversion
A Smtp8bitDataConversion specifying how the component should perform 8bit-to-7bit conversion of the message data if the given SMTP server does not support transmitting 8bit data but the message does contain such data. The default value is DoNothing (no 8bit-to-7bit conversion will be made).
Remarks
Nowadays, most SMTP servers do not expose problems with 8bit-to-7bit conversions, and there is no practical need to change the default value of this property.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.DeliveryNotification Property

SmtpDeliveryNotification Property
Provides access to properties which control when and how ESMTP Delivery Status Notification messages will be sent to the message sender.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DeliveryNotificationOptions DeliveryNotification { get; }
Public ReadOnly Property DeliveryNotification As DeliveryNotificationOptions
    Get

Property Value

Type: DeliveryNotificationOptions
The DeliveryNotificationOptions object containing properties and methods which allow the developer to specify ESMTP Delivery Status Notification (DSN) settings.
Remarks
DSN is a better alternative to MailMessage.ConfirmReceipt since most mail servers support ESMTP DSN extension rather than Return-Receipt-To message header (which is set by MailMessage.ConfirmReceipt property).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.DirectSendDefaults Property

SmtpDirectSendDefaults Property
Provides access to the default SMTP server settings to be used when connecting to SMTP servers discovered by MailBee via DNS MX lookup.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DirectSendServerConfig DirectSendDefaults { get; }
Public ReadOnly Property DirectSendDefaults As DirectSendServerConfig
    Get

Property Value

Type: DirectSendServerConfig
The DirectSendServerConfig object containing the default SMTP server settings to be used when connecting to SMTP servers discovered via DNS MX lookup (in direct send mode).
Remarks
This property allows the developer to specify SMTP settings for SMTP servers which are discovered by MailBee via DNS MX lookup in direct send mode (they are also called SMTP MX servers, as opposed to SMTP relay servers which reside in SmtpServers collection).
Examples
The statement below demonstrates now to increase SMTP connection timeout value. This is useful if some SMTP MX servers discovered during DNS MX lookup are so slow that they do not always respond during the default timeout interval (20 seconds). In this code, the timeout value is set to 60 seconds. It's assumed mailer is an instance of Smtp class.
C#
VB
Copy
mailer.DirectSendDefaults.Timeout = 60000;
mailer.DirectSendDefaults.Timeout = 60000
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.DnsServers Property

SmtpDnsServers Property
Gets the DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public DnsServerCollection DnsServers { get; }
Public ReadOnly Property DnsServers As DnsServerCollection
    Get

Property Value

Type: DnsServerCollection
The DnsServerCollection object containing the list of DNS servers to be used for DNS MX lookup in direct send mode (without dedicated SMTP relay server).
Remarks

MailBee can auto-detect which DNS servers are available in the system. The developer can use Autodetect method to retrieve DNS settings from OS or from the config file.

If DnsServers collection is non-empty and SmtpServers collection is empty, Send method will send messages in direct send mode. For each unique domain in the list of the message recipients domains (e.g. host1, host2, host3 if the recipients are joe@host3, kate@host1, bill@host2, tanya@host3, rob@host2), the component makes a query to the DNS server to get the name of the SMTP server which accepts mail for the corresponding domain (for instance, mx.host1, smtp.host2, mx-5.large-isp for host1, host2, host3), and then sends mail directly to these servers. If more than one SMTP server accepts mail for the given domain, the highest-priority server will be tried first. If it fails, other servers will be tried accordingly their priorities.

If multiple DNS servers specified, MailBee will distribute load between the available DNS servers to improve performance. However, if some servers have lower Priority than others, they will not be tried unless primary servers fail. This allows developers to implement high-performance and reliable send mail systems.

If both DnsServers and SmtpServers collections are non-empty, MailBee compares priorities of the highest-priority DNS server and the highest-priority SMTP relay server. If top prority SMTP server has the same or higher priority than top priority DNS server, MailBee will try to send mail using SMTP relay server first. If it fails, DNS MX lookup (direct send) will be used. Thus, it's possible to easily combine both "direct send" and "send to relay SMTP server" methods to improve reliability of send mail operation even further.

Note Note
Higher priority value is actually lower integer value. I.e. 0 is top priority while 999 is the lowest priority.
Caution note Caution
Direct send is often used by spammers. Thus, many mail services do not accept mail submissions from unknown hosts. It's recommended to perform direct sending from the domain which has at least one MX record assigned. In this case, the hosts with which the application is communicating will be able to verify the sender domain and accept the message submission request.
Examples

This sample adds two primary and one backup DNS server into DnsServers collection. The mail is then sent to 3 recipients.

If the primary DNS servers are fine, they both will be used to discover SMTP servers accepting mail for the recipients domains. If primary servers fail for some reason, the backup server will be tried as well. SMTP relay server is not used.

C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Add primary servers (top priority). In this sample, they are in
// the same LAN or intranet where the computer running MailBee is located.
mailer.DnsServers.Add("192.168.0.1", 0);
mailer.DnsServers.Add("192.168.0.2", 0);

// Add backup server (low priority). The server from another sub-network
// (such as company ISP's DNS server) is used. Thus, even if LAN servers
// fail, DNS MX lookup will still work.
mailer.DnsServers.Add("11.22.33.44", 10);

// Compose the message.
mailer.From.AsString = "user@host.com";
mailer.To.AsString = "abc@company.com, 123@anothercompany.com, xyz@website.com";
mailer.Subject = "Test message";
mailer.BodyPlainText = "The message text";

// Send it.
mailer.Send();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Add primary servers (top priority). In this sample, they are in
' the same LAN or intranet where the computer running MailBee is located.
mailer.DnsServers.Add("192.168.0.1", 0)
mailer.DnsServers.Add("192.168.0.2", 0)

' Add backup server (low priority). The server from another sub-network
' (such as company ISP's DNS server) is used. Thus, even if LAN servers
' fail, DNS MX lookup will still work.
mailer.DnsServers.Add("11.22.33.44", 10)

' Compose the message.
mailer.From.AsString = "user@host.com"
mailer.To.AsString = "abc@company.com, 123@anothercompany.com, xyz@website.com"
mailer.Subject = "Test message"
mailer.BodyPlainText = "The message text"

' Send it.
mailer.Send()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
MailBee.DnsMXDnsServer
SmtpSmtpServers


Smtp.From Property

SmtpFrom Property
Gets or sets EmailAddress object specifying the message sender.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddress From { get; set; }
Public Property From As EmailAddress
    Get
    Set

Property Value

Type: EmailAddress
The EmailAddress object representing From: field of the message.
Remarks
This property is equivalent to From property of Message object.
Examples
Setting the message sender using different methods.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Method 1: Setting Display Name and E-mail separately.
mailer.From.DisplayName = "John Doe, Sales Manager";
mailer.From.Email = "jdoe@domain.com";

// Method 2: Setting From field as string.
mailer.From.AsString = "\"John Doe, Sales Manager\" <jdoe@domain.com>";

// Method 3: Setting From field as EmailAddress.
mailer.From = new EmailAddress("John Doe, Sales Manager", "jdoe@domain.com");

// Method 4: Setting From field using Headers collection.
mailer.Message.Headers["From"] = "\"John Doe, Sales Manager\" <jdoe@domain.com>";
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Method 1: Setting Display Name and E-mail separately.
mailer.From.DisplayName = "John Doe, Sales Manager"
mailer.From.Email = "jdoe@domain.com"

' Method 2: Setting From field as string.
mailer.From.AsString = """John Doe, Sales Manager"" <jdoe@domain.com>"

' Method 3: Setting From field as EmailAddress.
mailer.From = New EmailAddress("John Doe, Sales Manager", "jdoe@domain.com")

' Method 4: Setting From field using Headers collection.
mailer.Message.Headers("From") = """John Doe, Sales Manager"" <jdoe@domain.com>"
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.IsAborted Property

SmtpIsAborted Property
Indicates whether Abort method has been called for the component.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsAborted { get; }
Public ReadOnly Property IsAborted As Boolean
    Get

Property Value

Type: Boolean
true if Abort method has already been called; otherwise, false. The default value is false.
Remarks

In aborted state, the component does not raise any events, and most methods, if called, will immediately return an error or throw an exception.

ResetState method can be used to restore the component back to operational state.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.IsBusy Property

SmtpIsBusy Property
Indicates whether the component is performing a lengthy operation.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsBusy { get; }
Public ReadOnly Property IsBusy As Boolean
    Get

Property Value

Type: Boolean
A bool value indicating whether the component is busy because it's doing some work.
Remarks
When the component is busy, it's not possible to start another lengthy operation. For instance, if the component connects to the server or transfers data over the network, no other network operation can be started at this time. Any attempt to do so will result in MailBeeInvalidStateException.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.IsConnected Property

SmtpIsConnected Property
Indicates whether the component is connected to the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsConnected { get; }
Public ReadOnly Property IsConnected As Boolean
    Get

Property Value

Type: Boolean
true if the component is connected to the server; otherwise, false.
Remarks

This property only reflects the state of client side of the connection. If the server forcibly closed the connection on its side, the application won't know about this until it makes an attempt to send or receive data.

In other words, it reflectes the state of the connection at the time when the last data to the moment was received.

To check if you're still connected to the server from its point of view, issue a command to the server, such as Noop. If the method throws an exception, this means the server has closed the connection. If no exception occurred, the connection is still up.

Note Note
In multi-thread mode (MaxThreadCount is NOT 1), many threads may be executed simultaneously. While the connection may be opened on one thread, it may be already closed or not yet been established on another thread. Due to this, IsConnected property is not applicable in multi-thread mode (it returns false).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpIsSmtpContext


Smtp.IsLoggedIn Property

SmtpIsLoggedIn Property
Indicates whether the component has already successfully authenticated on the server and logged in the user account.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsLoggedIn { get; }
Public ReadOnly Property IsLoggedIn As Boolean
    Get

Property Value

Type: Boolean
true if already authenticated the user on the server (Login method has already been called and ESMTP SASL authentication successfully completed); otherwise, false.
Remarks
In multi-thread mode (MaxThreadCount is NOT 1), many threads may be executed simultaneously. While the authentication may already be completed on one thread, another thread may be just connecting to the server, etc. Due to this, IsLoggedIn property is not applicable in multi-thread mode (it returns false).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpIsSmtpContext


Smtp.IsSmtpContext Property

SmtpIsSmtpContext Property
Indicates whether the component is currently operating in a single thread mode, and the current connection (if any) is an SMTP connection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSmtpContext { get; }
Public ReadOnly Property IsSmtpContext As Boolean
    Get

Property Value

Type: Boolean
true if the current state of the component allows execution of any methods which are valid in a single SMTP connection mode only.
Remarks

The Smtp component can operate in multi-thread mode, and is capable of establishing non-SMTP connections (while performing DNS MX lookup or POP-before-SMTP authentication). However, many Smtp class methods make sense only when a single SMTP connection is used at the moment. In this case, IsSmtpContext property can be used to make sure a call of such a method is possible.

If multi-threading, DNS MX lookup and POP-before-SMTP authentication are not used, this property will always return true. By default, multi-threading is not used (MaxThreadCount is 1), and automatic POP-before-SMTP authentication is off (AuthPopBeforeSmtp is false).

DNS MX lookup can be performed in direct send mode, when the message is being sent using mail send method like Send or RelayFromEmlFile(String, String, EmailAddressCollection) without prior Connect method call (and no SMTP servers were available in SmtpServers collections, or they had lower priority than the servers in DnsServers collection). If the connection was established by calling Connect method, DNS MX lookup will never be used.

The following are examples of methods which can only be used only if IsSmtpContext is true:

  • Disconnect
  • ExecuteCustomCommand(String)
  • GetCurrentSmtpServerIndex
  • GetExtensions
  • GetMaxMessageSize
  • GetServerResponseCode
  • GetSocket
  • GetSocketError
  • GetSupportedAuthMethods
  • Noop

If the component was used in multiple-connections mode (for instance, the message was sent using MX lookup), the developer can revert it back to default mode using ResetState method.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpIsConnected
SmtpResetState


Smtp.IsSslConnection Property

SmtpIsSslConnection Property
Indicates whether the current connection (if any) is secured with TLS/SSL layer.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IsSslConnection { get; }
Public ReadOnly Property IsSslConnection As Boolean
    Get

Property Value

Type: Boolean
true if the current connection is TLS/SSL; false if the connection is not secure.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.JobsFailed Property

SmtpJobsFailed Property
Gets the list of e-mail tasks failed during processing.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SendMailJobCollection JobsFailed { get; }
Public ReadOnly Property JobsFailed As SendMailJobCollection
    Get

Property Value

Type: SendMailJobCollection
The list of jobs failed during processing.
Remarks

During jobs processing, the developer can examine this collection to early detect problems with sending e-mails (or submitting them into the pickup folder). Or, the developer can also examine this collection after the processing has been finished, to check the results of the mailing.

To put failed jobs back into the task list for processing, the developer can use RetryFailedJobs method.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpJobsPending
SmtpJobsSuccessful
SmtpRetryFailedJobs


Smtp.JobsPending Property

SmtpJobsPending Property
Gets the list of send-mail (sending a single message or mail-merge) tasks ready for processing.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SendMailJobCollection JobsPending { get; }
Public ReadOnly Property JobsPending As SendMailJobCollection
    Get

Property Value

Type: SendMailJobCollection
The list of single-message or mail-merge jobs ready for processing.
Remarks

JobsPending queue consists of items which are either jobs to process a single or multiple e-mails.

A single e-mail job can either be a task to process a completed e-mail supplied by the application or an index in a data table row and an e-mail template with which to merge this data row.

A multiple e-mails job is a task to perform mail merge over multiple data table rows with an e-mail template. Such job will be split into multiple smaller jobs (one per data row) during processing.

Once JobsPending queue has been populated (with AddJob(String, String, EmailAddressCollection) method and its overloads), the developer can start processing jobs. To send the resulting e-mails out, call SendJobs method. To make the resulting e-mails be submitted to MailBee.NET Queue or IIS SMTP pickup folder, use SubmitJobsToPickupFolder(String, Boolean) method.

Once jobs processing has been started, jobs which involve processing a single e-mail (single-message jobs) are taken from JobsPending one by one and moved into JobsRunning collection. If the particular job involves processing multiple e-mails (multi-job), MailBee "extracts" a new job from the multi-job and places the newly created job into JobsRunning collection. The multi-job remains in JobsPending collection but the data row index assigned to the newly created job is removed from the internal pending data rows list of the multi-job. This process repeats itself until only a single data row index is left in the multi-job, and this makes it a single-message job. Finally, it will be moved into JobsRunning collection just like any other simple job.

Once processing of a job is finished, it's moved from JobsRunning into JobsSuccessful or JobsFailed collections. Mail merge jobs which were split into simple jobs during processing are NOT assembled back into a single object. This allows the developer to analyze the mailing process results on per e-mail level.

If some jobs failed during the processing and ended up in JobsFailed collection, they can be added back to JobsPending queue using RetryFailedJobs method.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpRetryFailedJobs
SmtpSendJobs


Smtp.JobsRunning Property

SmtpJobsRunning Property
Gets the list of e-mail tasks being processed right now.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SendMailJobCollection JobsRunning { get; }
Public ReadOnly Property JobsRunning As SendMailJobCollection
    Get

Property Value

Type: SendMailJobCollection
The list of jobs currently being processed.
Remarks

Jobs processing starts when the application calls such methods as SendJobs, BeginSendJobs(AsyncCallback, Object), SendMailMerge(String, EmailAddressCollection, DataTable), or SubmitJobsToPickupFolder(String, Boolean).

Jobs are processed in the following order:

  • Jobs are taken one by one from JobsPending and placed into JobsRunning collection (for mail-merge jobs, see details in JobsPending topic)
  • During processing, jobs stay in JobsRunning
  • When a particular job has finished processing, it gets to JobsSuccessful if processed successfully or into JobsFailed if the e-mail message associated with this job was not sent (or not submitted to the pickup folder in the case of SubmitJobsToPickupFolder(String, Boolean) method)

By default, multi-thread mode is off (MaxThreadCount is 1), so that only 1 job is processed per moment and number of items in JobsRunning never exceeds 1.

Note Note
The application can monitor JobsRunning collection only while any method which processes jobs is running. Once job processing finishes, JobsRunning will always be empty. To monitor JobsRunning and other job collections directly during job processing (i.e. not waiting until job processing completes), subscribe to Smtp class events, or start jobs processing with BeginSendJobs(AsyncCallback, Object) method, or both. To synchronize access to these collections in multi-thread environment, use JobsSyncRoot property.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpJobsPending
SmtpJobsFailed
SmtpJobsSuccessful


Smtp.JobsSuccessful Property

SmtpJobsSuccessful Property
Gets the list of successfully processed e-mail tasks.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SendMailJobCollection JobsSuccessful { get; }
Public ReadOnly Property JobsSuccessful As SendMailJobCollection
    Get

Property Value

Type: SendMailJobCollection
The list of the jobs that were processed without any errors.
Remarks
The developer can use this property to determine which e-mails have been successfully sent or submitted to the pickup folder.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpJobsPending
SmtpJobsFailed


Smtp.JobsSyncRoot Property

SmtpJobsSyncRoot Property
Gets the object to be used for synchronized access to the jobs collections.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Object JobsSyncRoot { get; }
Public ReadOnly Property JobsSyncRoot As Object
    Get

Property Value

Type: Object
A reference to the object to be used for synchronized access to JobsPending, JobsSuccessful, and JobsFailed collections.
Remarks

Synchronization of the access to the jobs collections is required if the jobs are currently being processed and the application wishes to modify or enumerate any of the jobs collections on another thread using corresponding methods of SendMailJobCollection class. Synchronization is NOT required in single-thread mode (MaxThreadCount is 1 and no asynchronous methods used) or if the component has already finished processing jobs (IsBusy is false). Synchronization, however, may be required even if MaxThreadCount is 1 but the application uses worker threads or runs jobs in asynchronous mode (with BeginSendJobs(AsyncCallback, Object) method).

Note Note
Smtp class methods which can modify jobs collections (AddJob(String, String, EmailAddressCollection), RetryFailedJobs, SendJobs, etc) take care of synchronization automatically. The developer may need to use JobsSyncRoot only when accessing job collections directly.
Examples
This code snippet enumerates JobsFailed collection in a thread-safe way. This makes it possible to safely call this code even if JobsFailed collection is modified by working threads of MailBee at the same moment. It's assumed mailer is an Smtp instance.
C#
VB
Copy
lock (mailer.JobsSyncRoot)
{
    foreach (SendMailJob job in mailer.JobsFailed)
    {
        Console.WriteLine(job.Tag);
    }
}
SyncLock mailer.JobsSyncRoot
    For Each job As SendMailJob In mailer.JobsFailed
        Console.WriteLine(job.Tag)
    Next
End SyncLock
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.LastResult Property

SmtpLastResult Property
Gets a numeric code of the last error.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int LastResult { get; }
Public ReadOnly Property LastResult As Integer
    Get

Property Value

Type: Int32
An integer value containing a numeric code of the last error. The default value is 0.
Remarks
The error code is one of constants defined in ErrorCodes class.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.LicenseKey Property

SmtpLicenseKey Property

Note: This API is now obsolete.

Assigns the license key.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")]
public static string LicenseKey { get; set; }
<ObsoleteAttribute("This property is obsolete. Use MailBee.Global.LicenseKey instead.")>
Public Shared Property LicenseKey As String
    Get
    Set

Property Value

Type: String
A string value which contains the license key which unlocks the component. This property is write-only.
Exceptions
Exception | Condition
MailBeeLicenseException | The license key is invalid.
Remarks
This property is obsolete. Use MailBee.Global.LicenseKey instead.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Log Property

SmtpLog Property
Gets the object used for logging MailBee activities into a file or memory buffer.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Logger Log { get; }
Public ReadOnly Property Log As Logger
    Get

Property Value

Type: Logger
A reference to the object used for logging MailBee activities into a file or memory buffer.
Remarks
This property is never a null reference (Nothing in Visual Basic) even if logging is not used.
Examples
This sample sets file logging on and sets the filename of the log file.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();
mailer.Log.Enabled = true;
mailer.Log.Filename = @"C:\Temp\log.txt";
mailer.SmtpServers.Add("smtp.domain.com");
mailer.Connect();
mailer.Disconnect();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer = New Smtp
mailer.Log.Enabled = True
mailer.Log.Filename = "C:\Temp\log.txt"
mailer.SmtpServers.Add("smtp.domain.com")
mailer.Connect()
mailer.Disconnect()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MaxThreadCount Property

SmtpMaxThreadCount Property
Gets or sets the maximum number of threads MailBee may create during send mail operations.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxThreadCount { get; set; }
Public Property MaxThreadCount As Integer
    Get
    Set

Property Value

Type: Int32
An integer value specifying the maximum number of threads MailBee may create during send mail operations, or -1 which specifies the number of threads is not limited. The default value is 1 (i.e. multi-threading is off).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is zero.
Remarks
Multi-threading may greatly increase performance of send bulk mail (mail merge) and direct send operations (sending directly to recipients' SMTP servers through MX lookup). For instance, if the message is addressed to 5 recipients on the different domains (and therefore 5 SMTP connections must be made), the component can submit the message to all 5 SMTP servers simultaneously.
Caution note Caution
Some methods and properties of Smtp component cannot be used in multi-thread mode. For instance, if there are 3 simultaneous SMTP connections opened, it's not possible to determine for which SMTP connection GetServerResponse method should return the response. In multi-thread mode, the developer should use Smtp class events in order to track progress of operations. In multi-thread mode, IsSmtpContext always returns false.

The maximum number of threads MailBee can utilize is 60. Threads are taken from ThreadPool. In .NET Core and UWP, Tasks are used instead.

Note Note
If logging SMTP session into a file is enabled (Enabled property of Log object is true), it's recommended to include context information into the log when multi-thread mode is used. The developer can use AddContextInfo flag for this purpose. The sample code in the bottom of this page demonstrates how this option can be used. If context information was not added, the log file would be more difficult to read and analyze.
Examples

This sample sends message using MX lookup (no SMTP relay server is used), spawning as many threads as required (MaxThreadCount is -1). The message contains the following recipients: user1@domain-a.com, user2@domain-a.com, user1@domain-b.com, user1@domain-c.com. Thus, the message must be sent to SMTP servers of 3 domains: domain-a.com, domain-b.com, domain-c.com Since the maximum number of threads is not limited, the component will create 3 threads in this case.

The MessageSubmittedToServer event is used to track submission of the message to each of 3 domains. If the message is successfully delivered to SMTP servers of all 3 domains, this event will occur 3 times total.

C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

class Sample
{
    // MessageSubmittedToServer event handler.
    private static void OnMessageSubmittedToServer(
        object sender, SmtpMessageSubmittedToServerEventArgs e)
    {
        // Show all recipients which were accepted by SMTP server. This event
        // is raised for every recipient domain which accepted at least one
        // recipient. As for the current sample, this event will occur 3 times
        // if each domain's SMTP server accepted at least one recipient.
        foreach (EmailAddress address in e.AcceptedRecipients)
        {
            Console.WriteLine("Message sent to " + address.Email);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Enable logging of send mail session into a file.
        // Context information will be added into the log as well.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Get DNS servers for MX lookup from the config file
        // or operating system settings.
        mailer.DnsServers.Autodetect();

        // Set sender.
        mailer.From.AsString = "John Doe <jdoe@domain.com>";

        // Set recipients (we specify multiple recipient domains
        // to demonstrate effect of multi-threading).
        mailer.To.AsString = "C.J. Smith <user1@domain-a.com>, " +
            "\"Kathy Long\" <user2@domain-a.com>, " +
            "Bob <user1@domain-b.com>, user1@domain-c.com";

        // Set message body and subject.
        mailer.Subject = "Annual report";
        mailer.BodyHtmlText = "<html>That's it.</html>";

        // Allow MailBee to create as many threads as required
        // to send mail to all recipient domains simultaneously.
        mailer.MaxThreadCount = -1;

        // Subscribe to the MessageSubmittedToServer event.
        mailer.MessageSubmittedToServer +=
            new SmtpMessageSubmittedToServerEventHandler(OnMessageSubmittedToServer);

        // Send it!
        mailer.Send();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

Class Sample
    ' MessageSubmittedToServer event handler.
    Private Shared Sub OnMessageSubmittedToServer( _
        ByVal sender As Object, ByVal e As SmtpMessageSubmittedToServerEventArgs)
        ' Show all recipients which were accepted by SMTP server. This event
        ' is raised for every recipient domain which accepted at least one
        ' recipient. As for the current sample, this event will occur 3 times
        ' if each domain's SMTP server accepted at least one recipient.
        For Each address As EmailAddress In e.AcceptedRecipients
            Console.WriteLine("Message sent to " & address.Email)
        Next
    End Sub

    ' The actual code.
    Shared Sub Main()
        Dim mailer As New Smtp

        ' Enable logging of send mail session into a file.
        ' Context information will be added into the log as well.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Get DNS servers for MX lookup from the config file
        ' or operating system settings.
        mailer.DnsServers.Autodetect()

        ' Set sender.
        mailer.From.AsString = "John Doe <jdoe@domain.com>"

        ' Set recipients (we specify multiple recipient domains
        ' to demonstrate effect of multi-threading).
        mailer.To.AsString = "C.J. Smith <user1@domain-a.com>, " & _
            " ""Kathy Long"" <user2@domain-a.com>, " & _
            "Bob <user1@domain-b.com>, user1@domain-c.com"

        ' Set message body and subject.
        mailer.Subject = "Annual report"
        mailer.BodyHtmlText = "<html>That's it.</html>"

        ' Allow MailBee to create as many threads as required
        ' to send mail to all recipient domains simultaneously.
        mailer.MaxThreadCount = -1

        ' Subscribe to the MessageSubmittedToServer event.
        AddHandler mailer.MessageSubmittedToServer, AddressOf OnMessageSubmittedToServer

        ' Send it!
        mailer.Send()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSendMailMerge(String, EmailAddressCollection, DataTable)


Smtp.Message Property

SmtpMessage Property
Gets or sets the mail message which will be sent by the component on Send method call.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public MailMessage Message { get; set; }
Public Property Message As MailMessage
    Get
    Set

Property Value

Type: MailMessage
The MailMessage object representing the mail message which will be sent by the component on Send method call.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
Remarks

The developer can also use Message property to access those methods and properties of the message to be sent which are not available in Smtp class itself. For instance, LoadBodyText(String, MessageBodyType, Encoding, ImportBodyOptions) method is not available in Smtp class, and must be called as Smtp.Message.LoadBodyText(parameters).

Some most often used members of MailMessage object are available through Smtp class members. For instance, the following notations are equivalent: Smtp.Message.BodyHtmlText and Smtp.BodyHtmlText.

Examples
This sample composes the message by downloading the message body from a web page, and sends the message to a relay SMTP server (direct send mode is not used).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Specify SMTP server to use. If your server does not require authentication,
// just remove last 2 parameters.
mailer.SmtpServers.Add("smtp.domain.com", "jdoe", "secret");

// Compose the message.
mailer.From.AsString = "John Doe <jdoe@domain.com>";
mailer.To.AsString = "Support Team <support@afterlogic.com>";
mailer.Subject = "Error on your homepage";

mailer.Message.LoadBodyText("http://www.afterlogic.com", MessageBodyType.Html);

// Send it.
mailer.Send();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Specify SMTP server to use. If your server does not require authentication,
' just remove last 2 parameters.
mailer.SmtpServers.Add("smtp.domain.com", "jdoe", "secret")

' Compose the message.
mailer.From.AsString = "John Doe <jdoe@domain.com>"
mailer.To.AsString = "Support Team <support@afterlogic.com>"
mailer.Subject = "Error on your homepage"

mailer.Message.LoadBodyText("http://www.afterlogic.com", MessageBodyType.Html)

' Send it.
mailer.Send()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.RaiseEvents Property

SmtpRaiseEvents Property
Gets or sets whether the component will raise any events.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEvents { get; set; }
Public Property RaiseEvents As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will raise any events. The default value is true.
Remarks
If this propery is false, OnEventName methods will also not be called.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.RaiseEventsViaMessageLoop Property

SmtpRaiseEventsViaMessageLoop Property
Gets or sets whether the events will be raised on the message loop of the application or not.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool RaiseEventsViaMessageLoop { get; set; }
Public Property RaiseEventsViaMessageLoop As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the events will be raised on the message loop of the application or not. The default value is true.
Remarks
This property is only meaningful in WinForms applications where events and asynchronous methods are used, and the developer needs to block the message loop for some reason (usually, to wait for completion of an asynchronous method). In this case, you should set this property to false and use Wait method to wait until asynchronous MailBee method is finished. See Wait method for more information.

The above also applies to synchronous methods if they are called on worker (non-UI) threads. If, however, the application does not use asynchronous methods of MailBee (and never calls its synchronous methods on non-UI threads), it should NOT attempt to set RaiseEventsViaMessageLoop to false or use Wait method.

Note Note
If you develop non-WinForms application (such as web or console application), you do not need to set this property or use Wait method regardless if the application uses worker threads or not.
Another alternative (in WinForms application) to using Wait method is to never block the application message loop and use callback functions instead of waiting for asynchronous method completion.
Note Note
In many cases, it's easier not to use events at all but derive a new class from Smtp class and override corresponding OnEventName method in order to get the developer-supplied code executed. See OnConnected(ConnectedEventArgs) method documentation for more information.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ReplyTo Property

SmtpReplyTo Property
Gets or sets EmailAddressCollection object specifying e-mail addresses to which the replies to this message should be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection ReplyTo { get; set; }
Public Property ReplyTo As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
The EmailAddressCollection object representing Reply-To: field of the message.
Remarks

This property is equivalent to ReplyTo property of Message object.

If this property is not set, most mail programs will send replies to From: address.

Examples
Specifying 2 e-mail addresses in Reply-To field.
C#
VB
Copy
// To use the code below, import these namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

mailer.ReplyTo.AsString = "Bill Smith <bsmith@company.com>";
mailer.ReplyTo.Add("John Doe, Sales Manager", "jdoe@domain.com");

Console.WriteLine(mailer.ReplyTo.ToString());

// The output.
"Bill Smith" <bsmith@company.com>, "John Doe, Sales Manager" <jdoe@domain.com>
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

mailer.ReplyTo.AsString = "Bill Smith <bsmith@company.com>"
mailer.ReplyTo.Add("John Doe, Sales Manager", "jdoe@domain.com")

Console.WriteLine(mailer.ReplyTo.ToString())

' The output.
"Bill Smith" <bsmith@company.com>, "John Doe, Sales Manager" <jdoe@domain.com>
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.RequestEncoding Property

SmtpRequestEncoding Property
Gets or sets the encoding used to convert a string into a bytes stream which is then sent to the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding RequestEncoding { get; set; }
Public Property RequestEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert a string into a bytes stream which is then sent to the server. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ResponseEncoding Property

SmtpResponseEncoding Property
Gets or sets the encoding used to convert a byte data received from the server into a string.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public Encoding ResponseEncoding { get; set; }
Public Property ResponseEncoding As Encoding
    Get
    Set

Property Value

Type: Encoding
A reference to the encoding object used to convert a byte data received from the server into a string. The default value is DefaultEncoding.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Site Property

SmtpSite Property
Gets or sets the object to be used as a site for the component.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public virtual ISite Site { get; set; }
Public Overridable Property Site As ISite
    Get
    Set

Property Value

Type: ISite
A reference to the object to be used as a site for the component. The default value is a null reference (Nothing in Visual Basic).

Implements

IComponentSite
Remarks
The developer does not need to set this property. It's used by RAD tools such as form designers.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SmtpServers Property

SmtpSmtpServers Property
Gets the SmtpServerCollection object containing the list of SMTP relay servers to be used for sending mail.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServerCollection SmtpServers { get; }
Public ReadOnly Property SmtpServers As SmtpServerCollection
    Get

Property Value

Type: SmtpServerCollection
The SmtpServerCollection object containing the list of SMTP servers to be used for sending mail.
Remarks

In order to send mail to an SMTP server, the developer must add it to SmtpServers collection first.

SmtpServers collection can contain multiple servers, which allows the developer to implement reliable send mail solution. In this case, SmtpServer having the highest priority (i.e. the lowest Priority value) will be tried first. If it fails, other servers will be tried accordingly their priority values.

SmtpServers collection can be used in cooperation with DnsServers collection. Depending which collection's top priority server has higher priority than another collection's top priority server, MailBee will either try to send to relay SMTP servers first and use direct send (through DNS MX lookup) if SMTP relay failed, or try to send in direct mode first, and use SMTP relay as a backup. This approach can be used if the application is mission-critical, and failures are not allowed.

Examples
This sample sends a mail message to an SMTP relay server. SMTP authentication is enabled, but IgnoreLoginFailure is set to true to force MailBee to try to send even if authentication fails.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// Specify SMTP server to use, and enable SMTP authentication.
mailer.SmtpServers.Add("smtp.company.com", "john.doe@company.com", "secret");

// Tune some settings of the server just added.
mailer.SmtpServers[0].IgnoreLoginFailure = true;

// Compose the message.
mailer.Message.From.DisplayName = "John Doe";
mailer.Message.From.Email = "john.doe@company.com";
mailer.Message.To.Add("Bill Smith", "bill@i-am-bill-smith.com");
mailer.Subject = "Your order";
mailer.BodyPlainText = "Purchased item description";

// Send it.
mailer.Send();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' Specify SMTP server to use, and enable SMTP authentication.
mailer.SmtpServers.Add("smtp.company.com", "john.doe@company.com", "secret")

' Tune some settings of the server just added.
mailer.SmtpServers(0).IgnoreLoginFailure = True

' Compose the message.
mailer.Message.From.DisplayName = "John Doe"
mailer.Message.From.Email = "john.doe@company.com"
mailer.Message.To.Add("Bill Smith", "bill@i-am-bill-smith.com")
mailer.Subject = "Your order"
mailer.BodyPlainText = "Purchased item description"

' Send it.
mailer.Send()
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
MailBee.SmtpMailSmtpServer
SmtpDnsServers


Smtp.StopJobsOnError Property

SmtpStopJobsOnError Property
Gets or sets if processing of the jobs must be stopped if an error occurs.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool StopJobsOnError { get; set; }
Public Property StopJobsOnError As Boolean
    Get
    Set

Property Value

Type: Boolean
true if processing of the jobs (sending e-mails or submitting them to the pickup folder) must be stopped whenever an error which prevents an e-mail from being sent or submitted to the pickup folder occurs; false if processing of the jobs must continue regardless of any errors. The default value is false.
Remarks

This property allows the developer to control whether jobs processing should be stopped if an error occurs, or this error will be skipped and the jobs processing will be continued.

StopJobsOnError mode must be set BEFORE calling a method which would start to process jobs (such as SendJobs or SubmitJobsToPickupFolder(String, Boolean)).

Note Note
If StopJobsOnError is true, failure to send even a single e-mail will stop the entire process. The particular e-mail which could not be sent (or submitted to the pickup folder) will be returned to the pending queue. It's possible to resume the stopped process by calling SendJobs method (or SubmitJobsToPickupFolder(String, Boolean) in the case of submitting to the pickup folder).

In practice, most applications set StopJobsOnError to false when sending e-mails because it's usually normal that some messages (e.g. 5 from 10000) could not be sent. However, when submitting e-mails to the pickup folder rather than sending them, the applications usually set StopJobsOnError to true. This is because submitting to the pickup folder is much more reliable operation than sending out. Usually, if an error occurs during submitting to the pickup folder, this means the disk is full. It's required to free some space before the application can continue.

The developer can also leave StopJobsOnError set to false and stop processing jobs manually using StopJobs method. For instance, the developer can use MessageSent and MessageNotSent event to keep track of successful and failed messages and call StopJobs if number of messages failed one after another exceeded certain threshold. Thus, the application will tolerate random failures but stop sending process completely if failures become systematic.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpStopJobs


Smtp.Subject Property

SmtpSubject Property
Gets or sets the subject of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Subject { get; set; }
Public Property Subject As String
    Get
    Set

Property Value

Type: String
The string containing the subject of the message.
Remarks
This property is equivalent to Subject property of Message object.
Examples
Specifying message subject in normal way and in encoded form (useful if the subject string contains non-English characters and you don't want to use the default UTF-8 encoding for some reason).
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class)

Smtp mailer = new Smtp();

// "Hello" in English.
mailer.Subject = "Hello";

// "Hello" in Simplified Chinese (gb2312 charset).
mailer.Subject = MailMessage.GetEncodedHeaderValue("Subject", "你好",
    System.Text.Encoding.GetEncoding("gb2312"), HeaderEncodingOptions.Base64);
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class)

Dim mailer As New Smtp

' "Hello" in English.
mailer.Subject = "Hello"

' "Hello" in Simplified Chinese (gb2312 charset).
mailer.Subject = MailMessage.GetEncodedHeaderValue("Subject", "你好", _
    System.Text.Encoding.GetEncoding("gb2312"), HeaderEncodingOptions.Base64)
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SynchronizingObject Property

SmtpSynchronizingObject Property
Gets or sets the object used to marshal the calls of the event handlers.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ISynchronizeInvoke SynchronizingObject { get; set; }
Public Property SynchronizingObject As ISynchronizeInvoke
    Get
    Set

Property Value

Type: ISynchronizeInvoke
A reference to the object on whose thread the events should be raised. The default value is a null reference (Nothing in Visual Basic) which tells MailBee to determine the appropriate marshalling object automatically.
Remarks
Usually, you do not need to set this property because MailBee can automatically marshal events to proper threads.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ThrowExceptions Property

SmtpThrowExceptions Property
Gets or sets whether the component will throw exceptions on errors.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool ThrowExceptions { get; set; }
Public Property ThrowExceptions As Boolean
    Get
    Set

Property Value

Type: Boolean
A bool value indicating whether the component will throw exceptions on errors. The default value is true.
Remarks
When exceptions are disabled and an error occurs, the component methods return false (or a null reference (Nothing in Visual Basic) if the method normally returns an object). You can use LastResult, GetErrorDescription, GetServerResponse, GetSocketError members to get more information about the error.
Note Note
Even if this property is set to false, the exceptions which occur due to errors in MailBee usage will still be thrown. Typical examples of such errors are: passing invalid arguments to methods, calling methods or settings properties in illegal state (for instance, an attempt to start an asynchronous method while another asynchronous method is not yet finished), etc. Such exceptions indicate programming errors in the application being developed, and thus cannot be supressed.

ThrowExceptions property does not control whether to throw exceptions which occur due to logging errors (such as "log file cannot be written to", etc). To control whether logging exceptions should be thrown, the developer can use Log.DisableOnException property.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.To Property

SmtpTo Property
Gets or sets EmailAddressCollection object specifying To: recipients of the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EmailAddressCollection To { get; set; }
Public Property To As EmailAddressCollection
    Get
    Set

Property Value

Type: EmailAddressCollection
The EmailAddressCollection object representing To: field of the message.
Remarks
This property is equivalent to To property of Message object.
Examples
Setting To: recipients using different methods.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Mime;

// The actual code (put it into a method of your class).
Smtp mailer = new Smtp();

mailer.To.Add("email@address.com");
mailer.To.Add("John Doe, Sales Manager", "jdoe@domain.com");
mailer.To.Add(new EmailAddress("user@host.com"));
mailer.To.AsString += "Bill Smith <bsmith@company.com>, kathy@mail.com, \"John Long, Jr.\" <jl@domain.com>";

Console.WriteLine(mailer.To.ToString());

// The output.
email@address.com, "John Doe, Sales Manager" <jdoe@domain.com>, user@host.com, "Bill Smith" <bsmith@company.com>, kathy@mail.com, "John Long, Jr." <jl@domain.com>
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Mime

' The actual code (put it into a method of your class).
Dim mailer As New Smtp

mailer.To.Add("email@address.com")
mailer.To.Add("John Doe, Sales Manager", "jdoe@domain.com")
mailer.To.Add(New EmailAddress("user@host.com"))
mailer.To.AsString += "Bill Smith <bsmith@company.com>, kathy@mail.com, ""John Long, Jr."" <jl@domain.com>"

Console.WriteLine(mailer.To.ToString())

' The output.
email@address.com, "John Doe, Sales Manager" <jdoe@domain.com>, user@host.com, "Bill Smith" <bsmith@company.com>, kathy@mail.com, "John Long, Jr." <jl@domain.com>
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.TrialDaysLeft Property

SmtpTrialDaysLeft Property
Gets the number of days left to the date of the trial license key expiration.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int TrialDaysLeft { get; }
Public ReadOnly Property TrialDaysLeft As Integer
    Get

Property Value

Type: Int32
An integer value which contains the number of days left to the date of the trial license key expiration, or -1 if the permanent license key is used.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Version Property

SmtpVersion Property
Gets the version of the MailBee assembly.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Version { get; }
Public ReadOnly Property Version As String
    Get

Property Value

Type: String
A string which contains the version of the MailBee assembly in MajorVersion.MinorVersion.Revision.Build format.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp Events

Smtp Events

The Smtp type exposes the following members.

Events
 | Name | Description
 | Connected | Occurs when the connection with the server is successfully established.
 | DataReceived | Occurs when data is received from the network.
 | DataSent | Occurs when data is sent to the network.
 | Disconnected | Occurs when the connection with the server gets closed.
Public event | Disposed | Occurs after the component was disposed.
 | ErrorOccurred | Occurs when the MailBeeException is thrown.
Public event | FinishingJob | Occurs when the component is about to finish a job of sending an individual e-mail message or a mail merge series.
 | HostResolved | Occurs when the SMTP server name is successully resolved into IP address(es).
 | LoggedIn | Occurs when the component successfully authenticates the user on the SMTP server and logs in the user account.
 | LogNewEntry | Occurs when an entry is written into the log file (or into the memory buffer if Smtp.Log.MemoryLog is true).
 | LowLevelDataReceived | Occurs when data is received from the connected socket.
 | LowLevelDataSent | Occurs when data is sent to the connected socket.
 | MergingMessage | Occurs when the component is about to merge the e-mail template with a single data table row.
 | MessageDataChunkSent | Occurs on progress of sending message source data to the SMTP server.
 | MessageDirectSendDone | Occurs in direct send mode when the component finished submitting the mail message to all SMTP MX servers of recipients domains.
 | MessageMXLookupDone | Occurs in direct send mode after the component finished DNS MX lookup of SMTP MX servers of recipients domains.
 | MessageNotSent | Occurs when the message was not sent due to an error.
 | MessageRecipientSubmitted | Occurs each time the next recipient in the mail message recipients list is accepted or refused by the SMTP server.
 | MessageSenderSubmitted | Occurs after the sender of the mail message was successfully submitted to the SMTP server.
 | MessageSent | Occurs after the message was successfully sent.
 | MessageSubmittedToPickupFolder | Occurs after the current message was saved to MailBee.NET Queue or IIS SMTP pickup folder.
 | MessageSubmittedToServer | Occurs each time the message is successfully submitted to the SMTP server.
 | SendingMessage | Occurs when the message is about to be sent.
 | SocketConnected | Occurs when the SMTP server accepts the connection attempt and opens the transmission channel between the remote host (SMTP server) and the client (MailBee).
 | SocketCreating | Occurs when MailBee needs a new socket object for establishing a connection with the SMTP server.
 | SubmittingMessageToPickupFolder | Occurs when the message is about to be saved into MailBee.NET Queue or IIS SMTP pickup folder.
 | TlsStarted | Occurs when the connection with the server becomes secure.
 | TransientErrorOccurred | Occurs on a transient SMTP error which can be ignored because at least one fail-over SMTP server hasn't been tried yet.
Top
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.Connected Event

SmtpConnected Event
Occurs when the connection with the server is successfully established.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ConnectedEventHandler Connected
Public Event Connected As ConnectedEventHandler

Value

Type: MailBeeConnectedEventHandler
Remarks
This event indicates successful completion of the connection procedure, while SocketConnected event (occurs before Connected) indicates the connection request from MailBee was accepted by the server, and the SMTP connection procedure will now begin.

If POP-before-SMTP authentication is used and MailBee successfully connects to the POP3 server, this event is raised as well. The developer can examine Protocol property value to determine whether the connection was made to POP3 or SMTP server.

Examples
This sample uses Connected event to report the successful connection status into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // Connected event handler.
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        Console.WriteLine("Successfully connected to the server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        mailer.SmtpServers.Add("smtp.domain.com");

        // Subscribe to the Connected event.
        mailer.Connected += new ConnectedEventHandler(OnConnected);

        mailer.Connect();
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Connected event handler.
    Private Shared Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Console.WriteLine("Successfully connected to the server.")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        mailer.SmtpServers.Add("smtp.domain.com")

        ' Subscribe to the Connected event.
        AddHandler mailer.Connected, AddressOf OnConnected

        mailer.Connect()
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSocketConnected


Smtp.DataReceived Event

SmtpDataReceived Event
Occurs when data is received from the network.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataReceived
Public Event DataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

Usually, this event is raised when the component receives a response from an SMTP server. If direct send mode is used, DNS responses containing MX lookup results will also be returned. If POP-before-SMTP authentication is used, POP3 responses will be returned as well. The developer can use Protocol property to determine the protocol of the received response data.

Unlike LowLevelDataReceived event, occurrence of this event indicates receiving of already decrypted data. For instance, if the transmission channel is SSL-encrypted, LowLevelDataReceived event indicates receiving of encrypted data, while DataReceived will be raised later (after decrypting the data). If the transmission channel is not encrypted or otherwise scrambled, DataReceived and LowLevelDataReceived are equivalent.

Note Note
This event is also raised when zero-length data is received from the server. When a server sends zero-length data portion, it means the connection was closed.
Examples
This sample prints all the data received from the server during SMTP session into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        // Ignore DNS traffic.
        if (e.Protocol == TopLevelProtocolType.Smtp)
        {
            Console.WriteLine("[" + System.Text.Encoding.Default.GetString(e.Data) + "]");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the DataReceived event.
        mailer.DataReceived += new DataTransferEventHandler(OnDataReceived);

        // Produce some DNS and SMTP traffic by performing direct send of empty message.
        mailer.Send("sender@domain.com", "recipient@domain.com");
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' DataReceived event handler.
    Private Shared Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Ignore DNS traffic.
        If e.Protocol = TopLevelProtocolType.Smtp Then
            Console.WriteLine("[" & System.Text.Encoding.Default.GetString(e.Data) & "]")
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the DataReceived event.
        AddHandler mailer.DataReceived, AddressOf OnDataReceived

        ' Produce some DNS and SMTP traffic by performing direct send of empty message.
        mailer.Send("sender@domain.com", "recipient@domain.com")
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLowLevelDataReceived


Smtp.DataSent Event

SmtpDataSent Event
Occurs when data is sent to the network.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler DataSent
Public Event DataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

Usually, this event is raised when the component sends a request to an SMTP server. If direct send mode or POP-before-SMTP authentication is used, sending DNS queries or requests to a POP3 server will also cause this event to occur. The developer can use Protocol property to determine the protocol of the data just sent.

Unlike LowLevelDataSent event, occurrence of this event indicates sending unencrypted data only. For instance, if the transmission channel is SSL-encrypted, LowLevelDataSent event indicates sending of any portion of encrypted data, while DataSent will be raised later to indicate the entire request (which was previously sent as one or several encrypted data chunks) has been sent. If the transmission channel is not encrypted or otherwise scrambled, DataSent and LowLevelDataSent are equivalent.

Unlike MessageDataChunkSent event, DataSent will be raised when any data is sent, while MessageDataChunkSent event is raised only when message header or entire message data is sent.

Examples
This sample prints all the data sent to the server during SMTP session into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // DataSent event handler.
    private static void OnDataSent(object sender, DataTransferEventArgs e)
    {
        // Ignore POP3 traffic.
        if (e.Protocol == TopLevelProtocolType.Smtp)
        {
            Console.WriteLine("[" + System.Text.Encoding.Default.GetString(e.Data) + "]");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server and enable POP-before-SMTP authentication.
        SmtpServer server = new SmtpServer("mail.domain.com");
        server.AuthPopBeforeSmtp = true;
        server.AccountName = "jdoe";
        server.Password = "secret";
        mailer.SmtpServers.Add(server);

        // Subscribe to the DataSent event.
        mailer.DataSent += new DataTransferEventHandler(OnDataSent);

        // Produce some POP3 and SMTP traffic by connecting in POP-before-SMTP mode.
        mailer.Connect();
        mailer.Hello();
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' DataSent event handler.
    Private Shared Sub OnDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Ignore POP3 traffic.
        If e.Protocol = TopLevelProtocolType.Smtp Then
            Console.WriteLine("[" & System.Text.Encoding.Default.GetString(e.Data) & "]")
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Specify SMTP server and enable POP-before-SMTP authentication.
        Dim server As New SmtpServer
        server = New SmtpServer("mail.domain.com")
        server.AuthPopBeforeSmtp = True
        server.AccountName = "jdoe"
        server.Password = "secret"
        mailer.SmtpServers.Add(server)

        ' Subscribe to the DataSent event.
        AddHandler mailer.DataSent, AddressOf OnDataSent

        ' Produce some POP3 and SMTP traffic by connecting in POP-before-SMTP mode.
        mailer.Connect()
        mailer.Hello()
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageDataChunkSent
SmtpLowLevelDataSent


Smtp.Disconnected Event

SmtpDisconnected Event
Occurs when the connection with the server gets closed.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DisconnectedEventHandler Disconnected
Public Event Disconnected As DisconnectedEventHandler

Value

Type: MailBeeDisconnectedEventHandler
Remarks

This event is raised in all the cases when the connection gets closed, including normal shutdown and failures.

If POP-before-SMTP authentication is used and MailBee successfully disconnects from the POP3 server, this event is raised as well. The developer can examine Protocol property value to determine whether POP3 or SMTP connection was closed.

Note Note
If Abort method is called, the connection is immediately closed, but no events (including Disconnected) are raised any longer.
Examples
This sample demonstrates that Disconnected event raises even on failures (when MailBeeException is thrown). The sample connects to the SMTP server and then sends invalid data to the server. The server does not respond and the network operation times out.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // Disconnected event handler.
    private static void OnDisconnected(object sender, DisconnectedEventArgs e)
    {
        if (e.IsNormalShutdown)
        {
            // QUIT command was sent to SMTP server.
            Console.WriteLine("Normally disconnected from the server.");
        }
        else
        {
            // Rough disconnect (due to failure).
            Console.WriteLine("The connection was terminated.");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server name and timeout value.
        SmtpServer server = new SmtpServer("smtp.company.com");

        // We do not want to wait for MailBeeException too long.
        // Set 5 seconds as timeout value.
        // We cannot set it too small because otherwise even Connect() method
        // would not have a time to connect to the server. Unlike POP3, it's
        // not possible change timeout setting after the connection has already
        // been established.
        server.Timeout = 5000;

        mailer.SmtpServers.Add(server);

        // Subscribe to Disconnected event.
        mailer.Disconnected += new DisconnectedEventHandler(OnDisconnected);

        // Connect to the server first.
        mailer.Connect();

        // Simulate connection error by sending a request to which the SMTP
        // server will never respond (due to a lack of "\r\n" in the request data) so
        // that timeout will occur.
        // This will cause MailBee to terminate the connection and raise
        // Disconnected event, and then throw MailBeeException (exceptions are
        // enabled by default).
        mailer.ExecuteCustomCommand("NONSENSE");

        // This line will probably never execute (unless the server
        // suddenly responds to NONSENSE sequence of bytes)
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Connected event handler.
    Private Shared Sub OnDisconnected(ByVal sender As Object, ByVal e As DisconnectedEventArgs)
        If e.IsNormalShutdown Then
            ' QUIT command was sent to SMTP server.
            Console.WriteLine("Normally disconnected from the server.")
        Else
            ' Rough disconnect (due to failure).
            Console.WriteLine("The connection was terminated.")
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Specify SMTP server name and timeout value.
        Dim server As New SmtpServer("smtp.company.com")

        ' We do not want to wait for MailBeeException too long.
        ' Set 5 seconds as timeout value.
        ' We cannot set it too small because otherwise even Connect() method
        ' would not have a time to connect to the server. Unlike POP3, it's
        ' not possible change timeout setting after the connection has already
        ' been established.
        server.Timeout = 5000

        mailer.SmtpServers.Add(server)

        ' Subscribe to the Disconnected event.
        AddHandler mailer.Disconnected, AddressOf OnDisconnected

        ' Connect to the server first.
        mailer.Connect()

        ' Simulate connection error by sending a request to which the SMTP
        ' server will never respond (due to a lack of "\r\n" in the request data) so
        ' that timeout will occur.
        ' This will cause MailBee to terminate the connection and raise
        ' Disconnected event, and then throw MailBeeException (exceptions are
        ' enabled by default).
        mailer.ExecuteCustomCommand("NONSENSE")

        ' This line will probably never execute (unless the server
        ' suddenly responds to NONSENSE sequence of bytes)
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDisconnect


Smtp.Disposed Event

SmtpDisposed Event
Occurs after the component was disposed.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event EventHandler Disposed
Public Event Disposed As EventHandler

Value

Type: SystemEventHandler

Implements

IComponentDisposed
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.ErrorOccurred Event

SmtpErrorOccurred Event
Occurs when the MailBeeException is thrown.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event ErrorEventHandler ErrorOccurred
Public Event ErrorOccurred As ErrorEventHandler

Value

Type: MailBeeErrorEventHandler
Remarks

When MailBee encounters any error, it throws the MailBeeException. However, MailBee can trap this exception if the error was not critical. For instance, if connecting to certain SMTP server fails but another server is available in reserve, the MailBeeException will be thrown and then trapped by MailBee itself, but no exception will be thrown to the application code. Such errors are called warnings.

ErrorOccurred event allows the developer to track both warnings and critical errors because it's raised for a particular exception even if MailBee will trap this exception and do not pass it to the application code.

Examples
This sample logs all the warnings and critical errors issued during the SMTP session into the console. In this sample, the connection attempt is made twice (high priority and low priority servers are used). Connection to high-priority SMTP server fails (the server name is invalid) so ErrorOccurred event is raised, but no exception is thrown to the application code. Then, MailBee attempts to connect to the backup server. If this attempt fails too, ErrorOccurred event is raised again (now IsFinalError will be true to indicate the error is not a warning), and the exception is thrown to the application code.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // ErrorOccurred event handler.
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        // Check whether the error is critical or not.
        if (e.IsFinalError)
        {
            // Display corresponding MailBeeException.Message.
            // After OnErrorOccurred handler finishes, MailBee will
            // throw the same exception to the application code.
            Console.WriteLine("CRITICAL ERROR: " + e.Reason.Message);
        }
        else
        {
            // Display corresponding MailBeeException.Message.
            // After OnErrorOccurred handler finishes, MailBee will
            // try another methods to accomplish the current task.
            Console.WriteLine("WARNING: " + e.Reason.Message);
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify top priority server with invalid name.
        mailer.SmtpServers.Add("invalid-host");

        // Specify backup server with valid name.
        mailer.SmtpServers.Add("smtp.domain.com", 25, 1);

        // Subscribe to the ErrorOccurred event.
        mailer.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Connect to the servers.
        mailer.Connect();

        Console.WriteLine("Connected to " +
            mailer.SmtpServers[mailer.GetCurrentSmtpServerIndex()].Name);

        // Close the connection.
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' ErrorOccurred event handler.
    Private Shared Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        ' Check whether the error is critical or not.
        If e.IsFinalError Then
            ' Display corresponding MailBeeException.Message.
            ' After OnErrorOccurred handler finishes, MailBee will
            ' throw the same exception to the application code.
            Console.WriteLine("CRITICAL ERROR: " & e.Reason.Message)
        Else
            ' Display corresponding MailBeeException.Message.
            ' After OnErrorOccurred handler finishes, MailBee will
            ' try another methods to accomplish the current task.
            Console.WriteLine("WARNING: " & e.Reason.Message)
        End If
    End Sub

    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Specify top priority server with invalid name.
        mailer.SmtpServers.Add("invalid-host")

        ' Specify backup server with valid name.
        mailer.SmtpServers.Add("smtp.domain.com", 25, 1)

        ' Subscribe to the ErrorOccurred event.
        AddHandler mailer.ErrorOccurred, AddressOf OnErrorOccurred

        ' Connect to the servers.
        mailer.Connect()

        Console.WriteLine("Connected to " & _
            mailer.SmtpServers(mailer.GetCurrentSmtpServerIndex()).Name)

        ' Close the connection.
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.FinishingJob Event

SmtpFinishingJob Event
Occurs when the component is about to finish a job of sending an individual e-mail message or a mail merge series.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpFinishingJobEventHandler FinishingJob
Public Event FinishingJob As SmtpFinishingJobEventHandler

Value

Type: MailBee.SmtpMailSmtpFinishingJobEventHandler
Remarks

This event takes place after the job was finished and MailBee needs to know what to do with the finished job next. Usually, you have two choices: to keep the finished job in JobsSuccessful or JobsFailed collection where you can examine the results of bulk mail operation after it completes, or you can opt to destroy the job in case if you send many messages and need to keep memory usage small.

Unlike events like MessageSent, this event occurs in all cases: when the message was sent, not sent, or submitted to the pickup folder.

See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.HostResolved Event

SmtpHostResolved Event
Occurs when the SMTP server name is successully resolved into IP address(es).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event HostResolvedEventHandler HostResolved
Public Event HostResolved As HostResolvedEventHandler

Value

Type: MailBeeHostResolvedEventHandler
Remarks

If the SMTP server name was already specified as an IP address, this event is still raised.

When the POP3 server name is resolved into IP address (if POP-before-SMTP authentication is used), this event is raised as well.

Note Note
No checking if performed on whether the resolved IP address points to the live host.
Examples
This sample connects to the SMTP server host and prints all the IP addresses of this host into console. Most hosts, however, have only one IP address assigned.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // HostResolved event handler.
    private static void OnHostResolved(object sender, HostResolvedEventArgs e)
    {
        foreach (System.Net.IPAddress ip in e.RemoteHost.AddressList)
        {
            Console.WriteLine(ip.ToString());
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        mailer.SmtpServers.Add("smtp.domain.com");

        // Subscribe to the HostResolved event.
        mailer.HostResolved += new HostResolvedEventHandler(OnHostResolved);

        mailer.Connect();
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' HostResolved event handler.
    Private Shared Sub OnHostResolved(ByVal sender As Object, ByVal e As HostResolvedEventArgs)
        For Each ip As System.Net.IPAddress In e.RemoteHost.AddressList
            Console.WriteLine(ip.ToString())
        Next
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp
        mailer.SmtpServers.Add("smtp.domain.com")

        ' Subscribe to the HostResolved event.
        AddHandler mailer.HostResolved, AddressOf OnHostResolved

        mailer.Connect()
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSocketConnected
SmtpConnected


Smtp.LoggedIn Event

SmtpLoggedIn Event
Occurs when the component successfully authenticates the user on the SMTP server and logs in the user account.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LoggedInEventHandler LoggedIn
Public Event LoggedIn As LoggedInEventHandler

Value

Type: MailBeeLoggedInEventHandler
Remarks
This event is raised only as a result of ESMTP authentication (performed by Login method). Successful completion of POP-before-SMTP authentication does not cause this event to be raised.
Examples
This sample connects to the SMTP server, and then authenticates the user on the server.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // LoggedIn event handler.
    private static void OnLoggedIn(object sender, LoggedInEventArgs e)
    {
        Console.WriteLine("Successfully authenticated on the SMTP server");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server and enable ESMTP authentication.
        // Note, depending on your SMTP server settings, either jdoe or jdoe@domain.com
        // should be used as user account name.
        mailer.SmtpServers.Add("smtp.domain.com", "jdoe@domain.com", "secret");

        // Subscribe to the LoggedIn event.
        mailer.LoggedIn += new LoggedInEventHandler(OnLoggedIn);

        mailer.Connect();
        mailer.Hello();
        mailer.Login();
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Connected event handler.
    Private Shared Sub OnLoggedIn(ByVal sender As Object, ByVal e As LoggedInEventArgs)
        Console.WriteLine("Successfully authenticated on the SMTP server")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Specify SMTP server and enable ESMTP authentication.
        ' Note, depending on your SMTP server settings, either jdoe or jdoe@domain.com
        ' should be used as user account name.
        mailer.SmtpServers.Add("smtp.domain.com", "jdoe@domain.com", "secret")

        ' Subscribe to the LoggedIn event.
        AddHandler mailer.LoggedIn, AddressOf OnLoggedIn

        mailer.Connect()
        mailer.Hello()
        mailer.Login()
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpLogin


Smtp.LogNewEntry Event

SmtpLogNewEntry Event
Occurs when an entry is written into the log file (or into the memory buffer if Smtp.Log.MemoryLog is true).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event LogNewEntryEventHandler LogNewEntry
Public Event LogNewEntry As LogNewEntryEventHandler

Value

Type: MailBeeLogNewEntryEventHandler
Remarks

This event is raised only if logging is turned on (Enabled is true).

MailBee raises this event BEFORE adding the entry into the the log. Since many properties of NewEntry object are editable, the developer can change the data MailBee will put into the log or even cancel logging the current entry at all. This may be useful the developer wishes to log only those entires which meet certain criteria.

Note Note
Entries added by the developer (through WriteLine(String) method call) do not cause this event to be raised. Thus, it's safe to add user-defined log entries even in the LogNewEntry event handler itself. This does not cause endless recursion which would otherwise occur if WriteLine(String) method called in LogNewEntry event handler raised this event again.
Examples
This sample enables logging the SMTP session into a file, and logs only those entries which indicate any data traffic between the client (MailBee) and the server. Other entries are discarded, and user-defined log entry is added instead. The sample is written for a console application.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // LogNewEntry event handler.
    private static void OnLogNewEntry(object sender, LogNewEntryEventArgs e)
    {
        if ( !(e.NewEntry.MessageType == LogMessageType.Recv ||
            e.NewEntry.MessageType == LogMessageType.Send) )
        {
            // Do not add this entry if it does not indicate any data transfer,
            // and put our own message instead.
            e.NewEntry.AddThisEntry = false;
            ((Smtp)sender).Log.WriteLine("UNWANTED MESSAGE REMOVED");

            // Note: we could produce similar results just by writing new values
            // into MessageText and MessageComment properties of the original entry.
            // The code above uses Log.WriteLine method just to show how to add new
            // entries in the event handler itself. You may comment 2 code lines above
            // and uncomment 2 code lines below to use the alternate approach.
            //
            // e.NewEntry.MessageText = "UNWANTED MESSAGE REMOVED";
            // e.NewEntry.MessageComment = string.Empty;
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        mailer.SmtpServers.Add("smtp.domain.com");

        // Enable logging the SMTP session into a file.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Format = LogFormatOptions.AddContextInfo;
        mailer.Log.Clear();

        // Subscribe to the LogNewEntry event.
        mailer.LogNewEntry += new LogNewEntryEventHandler(OnLogNewEntry);

        // Do something which would produce some network traffic.
        mailer.Connect();
        mailer.Hello();
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' LogNewEntry event handler
    Private Shared Sub OnLogNewEntry(ByVal sender As Object, ByVal e As LogNewEntryEventArgs)
        ' Check whether the error is critical or not.
        If e.NewEntry.MessageType <> LogMessageType.Recv And e.NewEntry.MessageType <> LogMessageType.Send Then
            ' Do not add this entry if it does not indicate any data transfer,
            ' and put our own message instead.
            e.NewEntry.AddThisEntry = False
            sender.Log.WriteLine("UNWANTED MESSAGE REMOVED")

            ' Note: we could produce similar results just by writing new values
            ' into MessageText and MessageComment properties of the original entry.
            ' The code above uses Log.WriteLine method just to show how to add new
            ' entries in the event handler itself. You may comment 2 code lines above
            ' and uncomment 2 code lines below to use the alternate approach.
            '
            ' e.NewEntry.MessageText = "UNWANTED MESSAGE REMOVED"
            ' e.NewEntry.MessageComment = String.Empty
        End If
    End Sub

    ' The actual code
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        mailer.SmtpServers.Add("smtp.domain.com")

        ' Enable logging the SMTP session into a file.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Format = LogFormatOptions.AddContextInfo
        mailer.Log.Clear()

        ' Subscribe to the LogNewEntry event.
        AddHandler mailer.LogNewEntry, AddressOf OnLogNewEntry

        ' Do something which would produce some network traffic.
        mailer.Connect()
        mailer.Hello()
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.LowLevelDataReceived Event

SmtpLowLevelDataReceived Event
Occurs when data is received from the connected socket.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler LowLevelDataReceived
Public Event LowLevelDataReceived As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

If the transmission channel is encrypted, this event will be raised when any encrypted chunk of data is received. Thus, this event can be used to record the data which is actually received from the network.

The typical use of this property is to calculate the network traffic produced during the SMTP session (including POP3/DNS data if any). SSL encryption increases the length of the transmitted data blocks, thus it's more accurate to calculate traffic by counting the length of data actually transmitted over the network.

If the transmission channel is not encrypted or otherwise scrambled, this property is equivalent to DataReceived.

Examples
This sample calculates all incoming traffic from the network during sending the message in direct send mode. DNS MX lookup traffic and SMTP traffic are calculated separately, and the results are printed into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // Total bytes received counters.
    private static int _totalBytesSmtp = 0;
    private static int _totalBytesDns = 0;

    // LowLevelDataReceived event handler.
    private static void OnLowLevelDataReceived(object sender, DataTransferEventArgs e)
    {
        if (e.Protocol == TopLevelProtocolType.Smtp)
        {
            // Increment SMTP traffic counter.
            _totalBytesSmtp += e.Data.Length;
        }
        else if (e.Protocol == TopLevelProtocolType.Dns)
        {
            // Increment DNS traffic counter.
            _totalBytesDns += e.Data.Length;
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the LowLevelDataReceived event.
        mailer.LowLevelDataReceived += new DataTransferEventHandler(OnLowLevelDataReceived);

        // Produce some DNS and SMTP traffic by performing direct send of empty message.
        mailer.Send("sender@domain.com", "user1@domain1.com, user2@domain2.com");

        // Print the total number of bytes received from the network.
        Console.WriteLine(_totalBytesSmtp + " bytes received in all SMTP sessions");
        Console.WriteLine(_totalBytesDns + " bytes received in all DNS responses");
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Total bytes received counters.
    Private Shared _totalBytesSmtp = 0
    Private Shared _totalBytesDns = 0

    ' LowLevelDataReceived event handler.
    Private Shared Sub OnLowLevelDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        If e.Protocol = TopLevelProtocolType.Smtp Then
            ' Increment SMTP traffic counter
            _totalBytesSmtp += e.Data.Length
        ElseIf e.Protocol = TopLevelProtocolType.Dns Then
            ' Increment DNS traffic counter.
            _totalBytesDns += e.Data.Length
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the LowLevelDataReceived event.
        AddHandler mailer.LowLevelDataReceived, AddressOf OnLowLevelDataReceived

        ' Produce some DNS and SMTP traffic by performing direct send of empty message.
        mailer.Send("sender@domain.com", "user1@domain1.com, user2@domain2.com")

        ' Print the total number of bytes received from the network.
        Console.WriteLine(_totalBytesSmtp + " bytes received in all SMTP sessions")
        Console.WriteLine(_totalBytesDns + " bytes received in all DNS responses")
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDataReceived


Smtp.LowLevelDataSent Event

SmtpLowLevelDataSent Event
Occurs when data is sent to the connected socket.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event DataTransferEventHandler LowLevelDataSent
Public Event LowLevelDataSent As DataTransferEventHandler

Value

Type: MailBeeDataTransferEventHandler
Remarks

If the transmission channel is encrypted, this event will be raised each time an encrypted chunk of data is successfully sent. Thus, this event can be used to record the data which is actually sent to the network.

The typical use of this event is to calculate the network traffic produced during the SMTP session. SSL encryption increases the length of the transmitted data blocks, thus it's more accurate to calculate traffic by counting the length of data actually transmitted over the network.

If the transmission channel is not encrypted or otherwise scrambled, this property is equivalent to DataSent.

Examples
This sample calculates all outgoing traffic to the network during sending the message in direct send mode. DNS MX lookup traffic and SMTP traffic are calculated separately, and the results are printed into console.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // Total bytes sent counters.
    private static int _totalBytesSmtp = 0;
    private static int _totalBytesDns = 0;

    // LowLevelDataSent event handler.
    private static void OnLowLevelDataSent(object sender, DataTransferEventArgs e)
    {
        if (e.Protocol == TopLevelProtocolType.Smtp)
        {
            // Increment SMTP traffic counter.
            _totalBytesSmtp += e.Data.Length;
        }
        else if (e.Protocol == TopLevelProtocolType.Dns)
        {
            // Increment DNS traffic counter.
            _totalBytesDns += e.Data.Length;
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the LowLevelDataSent event.
        mailer.LowLevelDataSent += new DataTransferEventHandler(OnLowLevelDataSent);

        // Produce some DNS and SMTP traffic by performing direct send of empty message.
        mailer.Send("sender@domain.com", "user1@domain1.com, user2@domain2.com");

        // Print the total number of bytes sent to the network.
        Console.WriteLine(_totalBytesSmtp + " bytes sent in all SMTP sessions");
        Console.WriteLine(_totalBytesDns + " bytes sent in all DNS queries");
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Total bytes sent counters.
    Private Shared _totalBytesSmtp = 0
    Private Shared _totalBytesDns = 0

    ' LowLevelDataReceived event handler.
    Private Shared Sub OnLowLevelDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        If e.Protocol = TopLevelProtocolType.Smtp Then
            ' Increment SMTP traffic counter.
            _totalBytesSmtp += e.Data.Length
        ElseIf e.Protocol = TopLevelProtocolType.Dns Then
            ' Increment DNS traffic counter.
            _totalBytesDns += e.Data.Length
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the LowLevelDataSent event.
        AddHandler mailer.LowLevelDataSent, AddressOf OnLowLevelDataSent

        ' Produce some DNS and SMTP traffic by performing direct send of empty message.
        mailer.Send("sender@domain.com", "user1@domain1.com, user2@domain2.com")

        ' Print the total number of bytes sent to the network.
        Console.WriteLine(_totalBytesSmtp & " bytes sent in all SMTP sessions")
        Console.WriteLine(_totalBytesDns & " bytes sent in all DNS queries")
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDataSent


Smtp.MergingMessage Event

SmtpMergingMessage Event
Occurs when the component is about to merge the e-mail template with a single data table row.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMergingMessageEventHandler MergingMessage
Public Event MergingMessage As SmtpMergingMessageEventHandler

Value

Type: MailBee.SmtpMailSmtpMergingMessageEventHandler
Remarks

This event precedes any other Smtp events which occur for every e-mail message being sent. MergingMessage, however, is not raised for the e-mails which were supplied by the application rather than generated during mail merge.

For mail merge jobs, this event allows the developer to control whether to proceed mail merge of a particular data row with the template and send the resulting e-mail or skip this data row and continue.

If you need to perform some post-processing of mail messages which have already been merged (i.e. an event which occurs AFTER mail merge of a data row with the template), use SendingMessage event (if you're sending e-mails out) or SubmittingMessageToPickupFolder event (if you're submitting them to the pickup folder).

Examples
The example is available at SubmitJobsToPickupFolder(String, Boolean) topic.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpSendingMessage
SmtpSubmittingMessageToPickupFolder


Smtp.MessageDataChunkSent Event

SmtpMessageDataChunkSent Event
Occurs on progress of sending message source data to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageDataChunkSentEventHandler MessageDataChunkSent
Public Event MessageDataChunkSent As SmtpMessageDataChunkSentEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageDataChunkSentEventHandler
Remarks

This event is a special case of DataSent event. While DataSent event occurs when any data is sent, MessageDataChunkSent event indicates when message data is being sent. In other words, MessageDataChunkSent event is a filtered version of more general DataSent event.

When both DataSent and MessageDataChunkSent events are used, DataSent is raised first.

Examples
This sample submits a mail message to the SMTP server. Both DataSent and MessageDataChunkSent events are handled, and the corresponding messages are printed into console when each of these events is raised. This sample demonstrates that DataSent is raised more often than MessageDataChunkSent.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // DataSent event handler.
    private static void OnDataSent(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine(e.Data.Length + " bytes sent");
    }

    // MessageDataChunkSent event handler.
    private static void OnMessageDataChunkSent(object sender,
        SmtpMessageDataChunkSentEventArgs e)
    {
        Console.WriteLine(e.BytesJustSent + " bytes of the message " +
            e.MailMessage.MessageID + " sent");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server and enable ESMTP authentication.
        // Note, depending on your SMTP server settings, either
        // "jdoe" or "jdoe@domain.com" should be used as user account name.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret");

        // Subscribe to events.
        mailer.DataSent += new DataTransferEventHandler(OnDataSent);
        mailer.MessageDataChunkSent +=
            new SmtpMessageDataChunkSentEventHandler(OnMessageDataChunkSent);

        // Send a message (attach a big file to make the message be sent
        // in multiple data chunks).
        mailer.To.AsString = "recipient1@domain1.com, recipient2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.BodyPlainText = "The message with attachment";
        mailer.AddAttachment(@"C:\bigfile.mdb");
        mailer.Send();

        Console.WriteLine("Message sent to: " +
            mailer.GetAcceptedRecipients().ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' DataSent event handler.
    Private Shared Sub OnDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine(e.Data.Length & " bytes sent")
    End Sub

    Private Shared Sub OnMessageDataChunkSent(ByVal sender As Object, _
        ByVal e As SmtpMessageDataChunkSentEventArgs)
        Console.WriteLine(e.BytesJustSent & " bytes of the message " & _
            e.MailMessage.MessageID & " sent")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Specify SMTP server and enable ESMTP authentication.
        ' Note, depending on your SMTP server settings, either
        ' "jdoe" or "jdoe@domain.com" should be used as user account name.
        mailer.SmtpServers.Add("mail.domain.com", "jdoe", "secret")

        ' Subscribe to events.
        AddHandler mailer.DataSent, AddressOf OnDataSent
        AddHandler mailer.MessageDataChunkSent, AddressOf OnMessageDataChunkSent

        ' Send a message (attach a big file to make the message be sent
        ' in multiple data chunks).
        mailer.To.AsString = "recipient1@domain1.com, recipient2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.BodyPlainText = "The message with attachment"
        mailer.AddAttachment("C:\bigfile.mdb")
        mailer.Send()

        Console.WriteLine("Message sent to: " & _
            mailer.GetAcceptedRecipients().ToString())
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpDataSent


Smtp.MessageDirectSendDone Event

SmtpMessageDirectSendDone Event
Occurs in direct send mode when the component finished submitting the mail message to all SMTP MX servers of recipients domains.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageDirectSendDoneEventHandler MessageDirectSendDone
Public Event MessageDirectSendDone As SmtpMessageDirectSendDoneEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageDirectSendDoneEventHandler
Remarks
In direct send mode, MessageDirectSendDone event is immediately followed by MessageSent event. However, if some recipients of the message failed and SmtpServers collection contains low priority SMTP relay servers (with priority value lower than top priority DNS server in DnsServers collection), the component will attempt to send the message to the failed recipients using these low priority SMTP relay servers. In this case, MessageSent event is raised noticeably later than MessageDirectSendDone event (after the message was also sent to the backup SMTP relay servers).
Examples
This sample sends a message in direct send mode to 3 recipients on 2 domains. MessageDirectSendDone event is raised 1 time. However, a backup SMTP relay server is then used in order to send to the recipients failed during direct send. MessageDirectSendDone and MessageSent events are raised 1 time.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // MessageDirectSendDone event handler.
    private static void OnMessageDirectSendDone(object sender,
        SmtpMessageDirectSendDoneEventArgs e)
    {
        Console.WriteLine("Sent using direct send to: " +
            e.SuccessfulRecipients.ToString());
    }

    // MessageSent event handler.
    private static void OnMessageSent(object sender,
        SmtpMessageSentEventArgs e)
    {
        Console.WriteLine("In the long run, sent to: " +
            e.SuccessfulRecipients.ToString());
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Specify backup SMTP server and enable ESMTP authentication.
        // Note, depending on your SMTP server settings, either
        // "jdoe" or "jdoe@domain.com" should be used as user account name.
        SmtpServer server = new SmtpServer("mail.isp.com", "jdoe", "secret");
        server.Priority = 100; // low priority
        mailer.SmtpServers.Add(server);

        // Subscribe to events.
        mailer.MessageDirectSendDone +=
            new SmtpMessageDirectSendDoneEventHandler(OnMessageDirectSendDone);
        mailer.MessageSent += new SmtpMessageSentEventHandler(OnMessageSent);

        // Send a message to 3 recipients on 2 domains. Let's assume we send
        // from a domain which has no its own MX record, and domain1.com checks
        // this and rejects our message to user1@domain1.com. In this case,
        // the message will be delivered to user1@domain1.com using ISP's mail
        // server (we assume ISP's mail server has MX record assigned).
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.Send();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' MessageDirectSendDone event handler.
    Private Shared Sub OnMessageDirectSendDone(ByVal sender As Object, ByVal e As SmtpMessageDirectSendDoneEventArgs)
        Console.WriteLine("Sent using direct send to: " & _
            e.SuccessfulRecipients.ToString())
    End Sub

    ' MessageSent event handler.
    Private Shared Sub OnMessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        Console.WriteLine("In the long run, sent to: " & _
            e.SuccessfulRecipients.ToString())
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Specify backup SMTP server and enable ESMTP authentication.
        ' Note, depending on your SMTP server settings, either
        ' "jdoe" or "jdoe@domain.com" should be used as user account name.
        Dim server As New SmtpServer("mail.isp.com", "jdoe", "secret")
        server.Priority = 100 ' low priority
        mailer.SmtpServers.Add(server)

        ' Subscribe to events.
        AddHandler mailer.MessageDirectSendDone, AddressOf OnMessageDirectSendDone
        AddHandler mailer.MessageSent, AddressOf OnMessageSent

        ' Send a message to 3 recipients on 2 domains. Let's assume we send
        ' from a domain which has no its own MX record, and domain1.com checks
        ' this and rejects our message to user1@domain1.com. In this case,
        ' the message will be delivered to user1@domain1.com using ISP's mail
        ' server (we assume ISP's mail server has MX record assigned).
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.Send()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MessageMXLookupDone Event

SmtpMessageMXLookupDone Event
Occurs in direct send mode after the component finished DNS MX lookup of SMTP MX servers of recipients domains.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageMXLookupDoneEventHandler MessageMXLookupDone
Public Event MessageMXLookupDone As SmtpMessageMXLookupDoneEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageMXLookupDoneEventHandler
Remarks
If the message is sent without SMTP relay server directly to MX servers of recipient domains, the component must first discover these servers by performing MX lookup queries to DNS servers. Once this process is finished, the component raises MessageMXLookupDone and starts submitting the mail message to the discovered MX servers.
Examples
This sample sends a message in direct send mode to 3 recipients on 2 domains. MessageMXLookupDone event is raised 1 time.
C#
VB
Copy
using System;
using System.Collections;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // MessageMXLookupDone event handler.
    private static void OnMessageMXLookupDone(object sender,
        SmtpMessageMXLookupDoneEventArgs e)
    {
        // Create and display comma-separated list of domains for which
        // SMTP MX servers have been found.
        string domains = string.Join(", ",
            (string[])ArrayList.Adapter(e.SuccessfulDomains).ToArray(typeof(string)));

        Console.WriteLine("Will send to MX servers of the following domains: " + domains);
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the MessageMXLookupDone event.
        mailer.MessageMXLookupDone +=
            new SmtpMessageMXLookupDoneEventHandler(OnMessageMXLookupDone);

        // Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.Send();

        Console.WriteLine("Sent to: " + mailer.GetAcceptedRecipients().ToString());
    }
}
Imports System
Imports System.Collections
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' MessageMXLookupDone event handler.
    Private Shared Sub OnMessageMXLookupDone(ByVal sender As Object, _
        ByVal e As SmtpMessageMXLookupDoneEventArgs)
        ' Create and display comma-separated list of domains for which
        ' SMTP MX servers have been found.
        Dim domains As String
        domains = String.Join(", ", ArrayList.Adapter(e.SuccessfulDomains).ToArray())

        Console.WriteLine("Will send to MX servers of the following domains: " & domains)
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the MessageMXLookupDone event.
        AddHandler mailer.MessageMXLookupDone, AddressOf OnMessageMXLookupDone

        ' Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.Send()

        Console.WriteLine("Sent to: " & mailer.GetAcceptedRecipients().ToString())
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MessageNotSent Event

SmtpMessageNotSent Event
Occurs when the message was not sent due to an error.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageNotSentEventHandler MessageNotSent
Public Event MessageNotSent As SmtpMessageNotSentEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageNotSentEventHandler
Remarks

This event is a counterpart of MessageSent event.

MessageNotSent event occurs only when there was an attempt to send a message and this attempt failed. Such attempt could be complex, such as sending to a primary and a backup mail servers. If, however, MailBee was unable to send the e-mail to the primary server but managed to send it to the backup one (or send it using alternative method, such as direct send), MessageNotSent will not be raised.

MessageNotSent may occur only for e-mail messages which have already been created. If the error occurred before the message was even built, this event will not occur. The same applies to the events which are raised when a message is about to be sent (or submitted to the pickup folder).

For instance, if SendJobs or SendMailMerge(String, EmailAddressCollection, DataTable) method is running and mail merge of a data row with the mail template failed for some reason, SendingMessage and MessageNotSent events will not occur.

If you have mail merge functionality in your application and need to subscribe to an event which occurs before performing mail merge of a data row with the template, use MergingMessage event.

Examples
The example is available at SendMailMerge(String, EmailAddressCollection, DataTable) topic.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpMessageSent


Smtp.MessageRecipientSubmitted Event

SmtpMessageRecipientSubmitted Event
Occurs each time the next recipient in the mail message recipients list is accepted or refused by the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageRecipientSubmittedEventHandler MessageRecipientSubmitted
Public Event MessageRecipientSubmitted As SmtpMessageRecipientSubmittedEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageRecipientSubmittedEventHandler
Remarks
If the message contains multiple recipients, this event is raised for each recipient. The developer can use Result property to detremine whether the recipient was accepted or refused.
Note Note
If refused recipients are not allowed (AllowRefusedRecipients is false), the component will cancel the SMTP session after raising MessageRecipientSubmitted event.
Examples
This sample sends a message in direct send mode to 3 recipients on 2 domains. MessageSenderSubmitted event is raised 3 times (for each recipient).
Note Note
In some cases, it may be raised more than 2 times. If certain domain has more than one SMTP MX server assigned, and sending to high-priority MX server failed after the message recipient has already been submitted, then backup MX servers are tried (so that the message recipient is submitted again, and so does MessageRecipientSubmitted event).
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // MessageRecipientSubmitted event handler.
    private static void OnMessageRecipientSubmitted(object sender,
        SmtpMessageRecipientSubmittedEventArgs e)
    {
        if (e.Result)
        {
            Console.WriteLine("SMTP server accepted " + e.RecipientEmail + " address");
        }
        else
        {
            Console.WriteLine("SMTP server refused " + e.RecipientEmail + " address");
        }
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the MessageRecipientSubmitted event.
        mailer.MessageRecipientSubmitted +=
            new SmtpMessageRecipientSubmittedEventHandler(OnMessageRecipientSubmitted);

        // Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.Send();

        Console.WriteLine("Message sent to: " + mailer.GetAcceptedRecipients().ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Connected event handler.
    Private Shared Sub OnMessageRecipientSubmitted(ByVal sender As Object, ByVal e As SmtpMessageRecipientSubmittedEventArgs)
        If e.Result Then
            Console.WriteLine("SMTP server accepted " & e.RecipientEmail & " address")
        Else
            Console.WriteLine("SMTP server refused " & e.RecipientEmail & " address")
        End If
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the MessageRecipientSubmitted event.
        AddHandler mailer.MessageRecipientSubmitted, AddressOf OnMessageRecipientSubmitted

        ' Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.Send()

        Console.WriteLine("Message sent to: " & mailer.GetAcceptedRecipients().ToString())
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MessageSenderSubmitted Event

SmtpMessageSenderSubmitted Event
Occurs after the sender of the mail message was successfully submitted to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageSenderSubmittedEventHandler MessageSenderSubmitted
Public Event MessageSenderSubmitted As SmtpMessageSenderSubmittedEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageSenderSubmittedEventHandler
Remarks
If the message is being sent to multiple SMTP servers (such as to SMTP MX servers in direct mode), this event will be raised multiple times (once per each individual SMTP connection).
Examples
This sample sends a message in direct send mode to 3 recipients on 2 domains. MessageSenderSubmitted event is raised 2 times (for each domain).
Note Note
In some cases, it may be raised more than 2 times. If certain domain has more than one SMTP MX server assigned, and sending to high-priority MX server failed after the message sender has already been submitted, then backup MX servers are tried (so that the message sender is submitted again, and so does MessageSenderSubmitted event).
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // MessageSenderSubmitted event handler.
    private static void OnMessageSenderSubmitted(object sender,
        SmtpMessageSenderSubmittedEventArgs e)
    {
        Console.WriteLine("SMTP server accepted " + e.SenderEmail + " address");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the MessageSenderSubmitted event.
        mailer.MessageSenderSubmitted +=
            new SmtpMessageSenderSubmittedEventHandler(OnMessageSenderSubmitted);

        // Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.Send();

        Console.WriteLine("Message sent to: " + mailer.GetAcceptedRecipients().ToString());
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' Connected event handler.
    Private Shared Sub OnMessageSenderSubmitted(ByVal sender As Object, ByVal e As SmtpMessageSenderSubmittedEventArgs)
        Console.WriteLine("SMTP server accepted " & e.SenderEmail & " address")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the MessageSenderSubmitted event.
        AddHandler mailer.MessageSenderSubmitted, AddressOf OnMessageSenderSubmitted

        ' Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.Send()

        Console.WriteLine("Message sent to: " & mailer.GetAcceptedRecipients().ToString())
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MessageSent Event

SmtpMessageSent Event
Occurs after the message was successfully sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageSentEventHandler MessageSent
Public Event MessageSent As SmtpMessageSentEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageSentEventHandler
Remarks
If the message is sent to multiple SMTP servers (common case in direct send mode where the message is submitted to SMTP MX server of each recipient domain separately), this event is raised after the message was submitted to all SMTP servers.
Examples
This sample sends a message in direct send mode to 3 recipients on 2 domains. MessageSent event is raised 1 time.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // MessageSent event handler.
    private static void OnMessageSent(object sender, SmtpMessageSentEventArgs e)
    {
        Console.WriteLine("Sent to: " + e.SuccessfulRecipients.ToString());
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the MessageSent event.
        mailer.MessageSent += new SmtpMessageSentEventHandler(OnMessageSent);

        // Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.Send();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' DataSent event handler.
    Private Shared Sub OnMessageSent(ByVal sender As Object, ByVal e As SmtpMessageSentEventArgs)
        Console.WriteLine("Sent to: " & e.SuccessfulRecipients.ToString())
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the MessageSent event.
        AddHandler mailer.MessageSent, AddressOf OnMessageSent

        ' Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.Send()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MessageSubmittedToPickupFolder Event

SmtpMessageSubmittedToPickupFolder Event
Occurs after the current message was saved to MailBee.NET Queue or IIS SMTP pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageSubmittedToPickupFolderEventHandler MessageSubmittedToPickupFolder
Public Event MessageSubmittedToPickupFolder As SmtpMessageSubmittedToPickupFolderEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageSubmittedToPickupFolderEventHandler
Remarks
This event can help to keep track of submitting multiple e-mails to the pickup folder (initiated with SubmitJobsToPickupFolder(String, Boolean) method), and find out which filename has been assigned to each e-mail's .EML file when it was saved to disk.
Examples
The example is available at SubmitJobsToPickupFolder(String, Boolean) topic.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.MessageSubmittedToServer Event

SmtpMessageSubmittedToServer Event
Occurs each time the message is successfully submitted to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpMessageSubmittedToServerEventHandler MessageSubmittedToServer
Public Event MessageSubmittedToServer As SmtpMessageSubmittedToServerEventHandler

Value

Type: MailBee.SmtpMailSmtpMessageSubmittedToServerEventHandler
Remarks
If the message is sent to multiple SMTP servers (common case in direct send mode where the message is submitted to SMTP MX server of each recipient domain separately), this event is raised for each SMTP server the message was successfully submitted to.
Examples
This sample sends a message in direct send mode to 3 recipients on 2 domains. MessageSubmittedToServer event is raised 2 times (for each domain).
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // MessageSubmittedToServer event handler.
    private static void OnMessageSubmittedToServer(object sender,
        SmtpMessageSubmittedToServerEventArgs e)
    {
        Console.WriteLine(e.AcceptedRecipients.ToString() + " accepted");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect();

        // Subscribe to the MessageRecipientSubmitted event.
        mailer.MessageSubmittedToServer +=
            new SmtpMessageSubmittedToServerEventHandler(OnMessageSubmittedToServer);

        // Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com";
        mailer.From.Email = "sender@domain.com";
        mailer.Subject = "Test message";
        mailer.Send();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' MessageSubmittedToServer event handler.
    Private Shared Sub OnMessageSubmittedToServer(ByVal sender As Object, _
        ByVal e As SmtpMessageSubmittedToServerEventArgs)
        Console.WriteLine(e.AcceptedRecipients.ToString() & " accepted")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Get DNS servers from config file/OS settings.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the MessageRecipientSubmitted event.
        AddHandler mailer.MessageSubmittedToServer, AddressOf OnMessageSubmittedToServer

        ' Send a message to 3 recipients on 2 domains.
        mailer.To.AsString = "user1@domain1.com, user2@domain1.com, user2@domain2.com"
        mailer.From.Email = "sender@domain.com"
        mailer.Subject = "Test message"
        mailer.Send()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SendingMessage Event

SmtpSendingMessage Event
Occurs when the message is about to be sent.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpSendingMessageEventHandler SendingMessage
Public Event SendingMessage As SmtpSendingMessageEventHandler

Value

Type: MailBee.SmtpMailSmtpSendingMessageEventHandler
Remarks

The developer can typically use this event for the following purposes:

  • Control whether particular messages should be skipped (not sent). This can be useful when performing mail merge tasks. To make the message be skipped, set SendIt to false.
  • Fine-tune messages before they get sent. This is also useful in mail merge tasks if the developer wants to perform some actions on the messages which had already been merged. You can change properties of the mail message itself (returned by MailMessage property), change ActualSenderEmail or ActualRecipients.
  • Change Delivery Status Notification (DSN) settings of the message. It's easier to specify a template for DSN Tracking-ID via setting mailer.DeliveryNotification.TrackingID value (where mailer is Smtp instance) prior to calling SendMailMerge(String, EmailAddressCollection, DataTable) or SendJobs. However, other DSN values (NotifyCondition and ReturnPortion) can be set for every e-mail separately only in SendingMessage event handler. This is because other DSN values are not strings and search-and-replace is not possible for them. However, most applications use the same NotifyCondition and ReturnPortion values for all e-mail messages within a mail merge job.

Note Note
If you changed the message sender or recipients via modification of the e-mail message itself (MailMessage property), you should also update ActualSenderEmail or ActualRecipients as well (for instance, set them to a null reference (Nothing in Visual Basic) to tell MailBee to grab these values from MailMessage property. Alternatively, if you only changed ActualSenderEmail or ActualRecipients, the corresponding message headers won't be changed (the message will be sent from or to addresses different from those specified in the message headers).
Examples
The example is available at SendMailMerge(String, EmailAddressCollection, DataTable) topic.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.SocketConnected Event

SmtpSocketConnected Event
Occurs when the SMTP server accepts the connection attempt and opens the transmission channel between the remote host (SMTP server) and the client (MailBee).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SocketConnectedEventHandler SocketConnected
Public Event SocketConnected As SocketConnectedEventHandler

Value

Type: MailBeeSocketConnectedEventHandler
Remarks

This event is raised immediately after Socket successfully connected to the SMTP server host. After the socket itself has been connected and this event raised, the client needs to receive some data from the server in order to complete the procedure of establishing connection with the SMTP server. If the connection must be SSL-encrypted, a few additional round-trips to the server required in order to completely establish the connection. Then, once the connection is fully initialized and ready for sending SMTP commands to the server, Connected event is raised.

If POP-before-SMTP authentication is used and MailBee successfully connects to the POP3 server host, this event is raised as well. The developer can examine Protocol property value to determine whether the connection was made to POP3 or SMTP server.

Examples
This sample demonstrates the order in which events are raised during Connect method call (POP-before-SMTP authentication is enabled, so certain events first occur for POP3 connection and then for SMTP connection). The events used in this sample occur in the following order:
  1. HostResolved (POP3 server host resolved)
  2. SocketCreating (MailBee is about to create a socket for connecting to POP3 server)
  3. SocketConnected (POP3 server accepted connection)
  4. LowLevelDataReceived (greeting from POP3 server)
  5. DataReceived (greeting from POP3 server)
  6. Connected (connected to POP3 server)
  7. LowLevelDataSent (send user account name to POP3 server)
  8. DataSent
  9. LowLevelDataReceived (POP3 server response to user account name)
  10. DataReceived (POP3 server response to user account name)
  11. LowLevelDataSent (send user account password to POP3 server)
  12. DataSent (send user account password to POP3 server)
  13. LowLevelDataReceived (POP3 greeting to authenticated user)
  14. DataReceived (POP3 greeting to authenticated user)
  15. LowLevelDataSent (send QUIT to logout from POP3 server)
  16. DataSent (send QUIT to logout from POP3 server)
  17. LowLevelDataReceived (POP3 bye message)
  18. DataReceived (empty string indicating the connection is closed)
  19. LowLevelDataReceived (empty string indicating the connection is closed)
  20. DataReceived (POP3 bye message)
  21. Disconnected (disconnected from POP3 server)
  22. HostResolved (SMTP server host resolved)
  23. SocketCreating (MailBee is about to create a socket for connecting to SMTP server)
  24. SocketConnected (SMTP server accepted connection)
  25. LowLevelDataReceived (greeting from SMTP server)
  26. DataReceived (greeting from SMTP server)
  27. Connected (connected to SMTP server)

Once Connect method finishes, all event handlers are removed in the code, thus Disconnect method does not generate any events.

C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // Replaces CRLF with \r\n in the end of each sent/received string.
    // Used to improve readability of the console output.
    private static string EscapeCrLf(string s)
    {
        return s.Replace("\r\n", @"\r\n");
    }

    // HostResolved event handler (called twice - for POP3 and SMTP). However,
    // since server name is the same for both SMTP and POP3 servers, the IP
    // address will be the same for both.
    private static void OnHostResolved(object sender, HostResolvedEventArgs e)
    {
        Console.WriteLine("The host name " + e.RemoteHost.HostName +
            " was resolved into IP address(es).");
    }

    // SocketConnected event handler (called twice - for POP3 and SMTP).
    private static void OnSocketConnected(object sender, SocketConnectedEventArgs e)
    {
        string serverType = (e.Protocol == TopLevelProtocolType.Smtp) ? "SMTP" : "POP3";
        Console.WriteLine("The " + serverType + " server at " +
            e.RemoteEndPoint.Address.ToString() + " accepted the connection.");
    }

    // LowLevelDataSent event handler.
    private static void OnLowLevelDataSent(object sender, DataTransferEventArgs e)
    {
        // Since SSL connection is not used, OnDataReceived and OnLowLevelDataReceived
        // routines will produce the same output. This sample handles both events just
        // to demonstrate that LowLevelDataSent event is raised before the
        // corresponding DataSent event.
        // But in SSL case, DataSent and LowLevelDataSent event data would be
        // completely different, and some LowLevelDataSent events (such as ones
        // occurred during the SSL handshake) would not be followed by DataSent
        // events at all, because the data sent or received during the SSL handshake
        // does not relate to SMTP protocol and cannot be decoded into textual form.
        Console.WriteLine("Low level data sent: [" +
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) + "]");
    }

    // DataSent event handler.
    private static void OnDataSent(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("Data sent: [" +
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) + "]");
    }

    // LowLevelDataReceived event handler.
    private static void OnLowLevelDataReceived(object sender, DataTransferEventArgs e)
    {
        // All considerations for LowLevelDataSent event (see above).
        // also apply to LowLevelDataReceived event.
        Console.WriteLine("Low level data received: [" +
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) + "]");
    }

    // DataReceived event handler.
    private static void OnDataReceived(object sender, DataTransferEventArgs e)
    {
        Console.WriteLine("Data received: [" +
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) + "]");
    }

    // Connected event handler (called twice - for POP3 and SMTP).
    private static void OnConnected(object sender, ConnectedEventArgs e)
    {
        string serverType = (e.Protocol == TopLevelProtocolType.Smtp) ? "SMTP" : "POP3";
        Console.WriteLine("Successfully connected to the " + serverType + " server.");
    }

    // Disconnected event handler (called once - for POP3).
    private static void OnDisconnected(object sender, DisconnectedEventArgs e)
    {
        string serverType = (e.Protocol == TopLevelProtocolType.Smtp) ? "SMTP" : "POP3";
        Console.WriteLine("Successfully disconnected from the " + serverType + " server.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Specify SMTP server and enable POP-before-SMTP authentication.
        SmtpServer server = new SmtpServer("mail.company.com");
        server.AuthPopBeforeSmtp = true;
        server.AccountName = "jdoe@company.com"; // or jdoe (depends on mail server).
        server.Password = "secret";
        mailer.SmtpServers.Add(server);

        // Subscribe to the events.
        mailer.HostResolved += new HostResolvedEventHandler(OnHostResolved);
        mailer.SocketConnected += new SocketConnectedEventHandler(OnSocketConnected);
        mailer.LowLevelDataReceived += new DataTransferEventHandler(OnLowLevelDataReceived);
        mailer.DataReceived += new DataTransferEventHandler(OnDataReceived);
        mailer.LowLevelDataSent += new DataTransferEventHandler(OnLowLevelDataSent);
        mailer.DataSent += new DataTransferEventHandler(OnDataSent);
        mailer.Connected += new ConnectedEventHandler(OnConnected);
        mailer.Disconnected += new DisconnectedEventHandler(OnDisconnected);

        // Connect to the server and make the events get raised.
        // Actually, it will connect to POP3 server first, authenticate, disconnect,
        // and immediately connect to SMTP server.
        mailer.Connect();

        // Unsubscribe from the events.
        mailer.HostResolved -= new HostResolvedEventHandler(OnHostResolved);
        mailer.SocketConnected -= new SocketConnectedEventHandler(OnSocketConnected);
        mailer.LowLevelDataReceived -= new DataTransferEventHandler(OnLowLevelDataReceived);
        mailer.DataReceived -= new DataTransferEventHandler(OnDataReceived);
        mailer.LowLevelDataSent -= new DataTransferEventHandler(OnLowLevelDataSent);
        mailer.DataSent -= new DataTransferEventHandler(OnDataSent);
        mailer.Connected -= new ConnectedEventHandler(OnConnected);
        mailer.Disconnected -= new DisconnectedEventHandler(OnDisconnected);

        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
       Private Shared Function EscapeCrLf(ByVal s As String)
        Return s.Replace(vbCrLf, "\r\n")
       End Function

       ' HostResolved event handler (called twice - for POP3 and SMTP). However,
       ' since server name is the same for both SMTP and POP3 servers, the IP
       ' address will be the same for both.
       Private Shared Sub OnHostResolved(ByVal sender As Object, ByVal e As HostResolvedEventArgs)
        Console.WriteLine("The host name " & e.RemoteHost.HostName & _
            " was resolved into IP address(es).")
       End Sub

       ' SocketConnected event handler (called twice - for POP3 and SMTP).
       Private Shared Sub OnSocketConnected(ByVal sender As Object, ByVal e As SocketConnectedEventArgs)
        Dim serverType As String
        If e.Protocol = TopLevelProtocolType.Smtp Then
            serverType = "SMTP"
        Else
            serverType = "POP3"
        End If
        Console.WriteLine("The " & serverType & " server at " & _
            e.RemoteEndPoint.Address.ToString() & " accepted the connection.")
       End Sub

       ' LowLevelDataSent event handler.
       Private Shared Sub OnLowLevelDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' Since SSL connection is not used, OnDataReceived and OnLowLevelDataReceived
        ' routines will produce the same output. This sample handles both events just
        ' to demonstrate that LowLevelDataSent event is raised before the
        ' corresponding DataSent event.
        ' But in SSL case, DataSent and LowLevelDataSent event data would be
        ' completely different, and some LowLevelDataSent events (such as ones
        ' occurred during the SSL handshake) would not be followed by DataSent
        ' events at all, because the data sent or received during the SSL handshake
        ' does not relate to SMTP protocol and cannot be decoded into textual form.
        Console.WriteLine("Low level data sent: [" & _
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) & "]")
       End Sub

       ' DataSent event handler.
       Private Shared Sub OnDataSent(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("Data sent: [" & _
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) & "]")
       End Sub

       ' LowLevelDataReceived event handler.
       Private Shared Sub OnLowLevelDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        ' All considerations for LowLevelDataSent event (see above).
        ' also apply to LowLevelDataReceived event.
        Console.WriteLine("Low level data received: [" & _
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) & "]")
       End Sub

       ' DataReceived event handler.
       Private Shared Sub OnDataReceived(ByVal sender As Object, ByVal e As DataTransferEventArgs)
        Console.WriteLine("Data received: [" & _
            EscapeCrLf(System.Text.Encoding.Default.GetString(e.Data)) & "]")
       End Sub

       ' Connected event handler (called twice - for POP3 and SMTP).
       Private Shared Sub OnConnected(ByVal sender As Object, ByVal e As ConnectedEventArgs)
        Dim serverType As String
        If e.Protocol = TopLevelProtocolType.Smtp Then
            servertype = "SMTP"
        Else
            servertype = "POP3"
        End If
        Console.WriteLine("Successfully connected to the " & servertype & " server.")
       End Sub

       ' Disconnected event handler (called once - for POP3).
       Private Shared Sub OnDisconnected(ByVal sender As Object, ByVal e As DisconnectedEventArgs)
        Dim serverType As String
        If e.Protocol = TopLevelProtocolType.Smtp Then
            servertype = "SMTP"
        Else
            servertype = "POP3"
        End If
            Console.WriteLine("Successfully disconnected from the " & servertype & " server.")
       End Sub

       ' The actual code.
       Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp
        Dim server As New SmtpServer("mail.company.com")

        ' Specify SMTP server and enable POP-before-SMTP authentication.
        server.AuthPopBeforeSmtp = True
        server.AccountName = "jdoe@company.com" ' or jdoe (depends on mail server)
        server.Password = "secret"
        mailer.SmtpServers.Add(server)

        ' Subscribe to the events.
        AddHandler mailer.HostResolved, AddressOf OnHostResolved
        AddHandler mailer.SocketConnected, AddressOf OnSocketConnected
        AddHandler mailer.LowLevelDataReceived, AddressOf OnLowLevelDataReceived
        AddHandler mailer.DataReceived, AddressOf OnDataReceived
        AddHandler mailer.LowLevelDataSent, AddressOf OnLowLevelDataSent
        AddHandler mailer.DataSent, AddressOf OnDataSent
        AddHandler mailer.Connected, AddressOf OnConnected
        AddHandler mailer.Disconnected, AddressOf OnDisconnected

        ' Connect to the server and make the events get raised.
        ' Actually, it will connect to POP3 server first, authenticate, disconnect,
        ' and immediately connect to SMTP server.
        mailer.Connect()

        ' Unsubscribe from the events.
        RemoveHandler mailer.HostResolved, AddressOf OnHostResolved
        RemoveHandler mailer.SocketConnected, AddressOf OnSocketConnected
        RemoveHandler mailer.LowLevelDataReceived, AddressOf OnLowLevelDataReceived
        RemoveHandler mailer.DataReceived, AddressOf OnDataReceived
        RemoveHandler mailer.LowLevelDataSent, AddressOf OnLowLevelDataSent
        RemoveHandler mailer.DataSent, AddressOf OnDataSent
        RemoveHandler mailer.Connected, AddressOf OnConnected
        RemoveHandler mailer.Disconnected, AddressOf OnDisconnected

        mailer.Disconnect()
       End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpConnected


Smtp.SocketCreating Event

SmtpSocketCreating Event
Occurs when MailBee needs a new socket object for establishing a connection with the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SocketCreatingEventHandler SocketCreating
Public Event SocketCreating As SocketCreatingEventHandler

Value

Type: MailBeeSocketCreatingEventHandler
Remarks

This event is raised just before MailBee will start making the connection (i.e. before SocketConnected event). This lets you specify your own socket object in case if you need some special socket settings. If you need this, set NewSocket property to the socket object needed in your event handler.

This event fires for mail server connections only. Connections with DNS servers (such as DNS MX lookup during direct send) don't trigger this event.

Note Note
It's possible that this event will fire multiple times in case if the host has multple endpoints assigned. For instance, if the first endpoint was IPv6, the connection could not be made but second endpoint (IPv4) would succeed. On each call of this event handler, your code must supply a new, fresh socket object (otherwise MailBee will create its own). By default, however, MailBee tries IPv4 addresses first (see PreferIPv4Hosts) so this situation is unlikely to happen. Another case would be if you have multiple SMTP servers in SmtpServers collection, the first server failed and fail-over server is tried. Mass-mailing, direct-send and POP-before-SMTP auth scenarios can also cause multiple connections to SMTP servers occur (in case of POP-before-SMTP, to POP3 server as well). This results in firing this event multiple times as well.
Examples

Imap.SocketCreating topic contains a code snippet which shows the idea how to use this event in UWP apps to implement support of self-signed certificates.

The code snippet below shows how to assign a local end point for an SMTP connection in classic .NET apps (for instance, for direct send). Although you can specify local IP address by setting mailer.DirectSendDefaults.LocalEndPoint (mailer is Smtp instance), you may want to set different local IPs for individual sends during the same mass mailing operation.

C#
VB
Copy
using System;
using System.Net;
using System.Net.Sockets;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    static void mailer_SocketCreating(object sender, SocketCreatingEventArgs e)
    {
        e.NewSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        // In real app, you can select a particular IP address from a pool of your local IP addresses on random or round-robin basis.
        e.NewSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 0));
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        mailer.DnsServers.Autodetect();

        // Subscribe to the SocketCreating event.
        mailer.SocketCreating += new SocketCreatingEventHandler(mailer_SocketCreating);

        ...
        // Here you'll add multiple email jobs with .AddJobs method.
        ...

        mailer.SendJobs();
    }
}
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    Private Shared Sub mailer_SocketCreating(sender As Object, e As SocketCreatingEventArgs)
        e.NewSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        ' In real app, you can select a particular IP address from a pool of your local IP addresses on random or round-robin basis.
        e.NewSocket.Bind(New IPEndPoint(IPAddress.Parse("192.168.0.1"), 0))
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp
        mailer.DnsServers.Autodetect()

        ' Subscribe to the SocketCreating event.
        AddHandler mailer.SocketCreating , AddressOf SocketCreating

        ...
        ' Here you'll add multiple email jobs with .AddJobs method.
        ...

        mailer.SendJobs()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpConnected


Smtp.SubmittingMessageToPickupFolder Event

SmtpSubmittingMessageToPickupFolder Event
Occurs when the message is about to be saved into MailBee.NET Queue or IIS SMTP pickup folder.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpSubmittingMessageToPickupFolderEventHandler SubmittingMessageToPickupFolder
Public Event SubmittingMessageToPickupFolder As SmtpSubmittingMessageToPickupFolderEventHandler

Value

Type: MailBee.SmtpMailSmtpSubmittingMessageToPickupFolderEventHandler
Remarks

The developer can typically use this event for the following purposes:

  • Control whether particular messages should be skipped (not saved to the pickup folder). This can be useful when performing mail merge tasks. To make the message be skipped, set SubmitIt to false.
  • Fine-tune messages before they get saved to the pickup folder. This is also useful in mail merge tasks if the developer wants to perform some actions on the messages which had already been merged. You can change properties of the mail message itself (returned by MailMessage property), change ActualSenderEmail or ActualRecipients.
  • Change the pickup folder name or specify your own filename of the message file to be saved. This is useful if there is more than one pickup folder. Set Filename or PickupFolderName properties for this.

Note Note
If you changed the message sender or recipients via modification of the e-mail message itself (MailMessage property), you should also update ActualSenderEmail or ActualRecipients as well (for instance, set them to a null reference (Nothing in Visual Basic) to tell MailBee to grab these values from MailMessage property. Alternatively, if you only changed ActualSenderEmail or ActualRecipients, the corresponding message headers won't be changed (the message will be sent from or to addresses different from those specified in the message headers).
Examples
The example is available at SubmitJobsToPickupFolder(String, Boolean) topic.
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp.TlsStarted Event

SmtpTlsStarted Event
Occurs when the connection with the server becomes secure.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event TlsStartedEventHandler TlsStarted
Public Event TlsStarted As TlsStartedEventHandler

Value

Type: MailBeeTlsStartedEventHandler
Remarks
This event is raised when TLS/SSL negotiation completes and TLS session successfully starts. Usually, this happens as a result of successful completion of StartTls method or if automatic TLS/SSL negotiation was requested via setting SslMode property of the active SmtpServer object to non-Manual value.
Examples
This console sample demonstrates that TlsStarted event is raised during executing Hello method when SslMode property of the active SmtpServer object is set to UseStartTls value.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Security;

class Sample
{
    // TlsStarted event handler.
    private static void OnTlsStarted(object sender, TlsStartedEventArgs e)
    {
        // This will happen during Hello method execution.
        Console.WriteLine("TLS/SSL session started.");
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Subscribe to TlsStarted event.
        mailer.TlsStarted += new TlsStartedEventHandler(OnTlsStarted);

        // Notify MailBee it should start TLS/SSL session when appropriate.
        // The connection is made to the regular port so that STLS command
        // will be used to start TLS/SSL session.
        SmtpServer server = new SmtpServer("smtp.company.com");
        server.SslMode = SslStartupMode.UseStartTls;
        mailer.SmtpServers.Add(server);

        mailer.Connect();

        Console.WriteLine("Connected to the server. Will send greeting now...");

        // TLS/SSL negotiation will take place here. Thus, any subseqeunt commands
        // such as sending user credentials or mail message submission will take
        // place under secure TLS/SSL layer.
        // Note: EHLO command will be sent twice: first, before TLS/SSL negotiation;
        // second, after. This is because capability list presented by EHLO response
        // can change after TLS negotiation.
        mailer.Hello();

        Console.WriteLine("Hello completed successfully.");

        // Can send mail, perform login or whatever here.

        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Security

Public Class Sample
    ' TlsStarted event handler.
    Private Shared Sub OnTlsStarted(ByVal sender As Object, ByVal e As TlsStartedEventArgs)
        ' This will happen during Hello method execution.
        Console.WriteLine("TLS/SSL session started.")
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp

        ' Subscribe to TlsStarted event.
        AddHandler mailer.TlsStarted, AddressOf OnTlsStarted

        ' Notify MailBee it should start TLS/SSL session when appropriate.
        ' The connection is made to the regular port so that STLS command
        ' will be used to start TLS/SSL session.
        Dim server As SmtpServer = New SmtpServer("smtp.company.com")
        server.SslMode = SslStartupMode.UseStartTls
        mailer.SmtpServers.Add(server)

        mailer.Connect()

        Console.WriteLine("Connected to the server. Will send greeting now...")

        ' TLS/SSL negotiation will take place here. Thus, any subseqeunt commands
        ' such as sending user credentials or mail message submission will take
        ' place under secure TLS/SSL layer.
        ' Note: EHLO command will be sent twice: first, before TLS/SSL negotiation;
        ' second, after. This is because capability list presented by EHLO response
        ' can change after TLS negotiation.
        mailer.Hello()

        Console.WriteLine("Hello completed successfully.")

        ' Can send mail, perform login or whatever here.

        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace
SmtpServerSslMode
SmtpStartTls


Smtp.TransientErrorOccurred Event

SmtpTransientErrorOccurred Event
Occurs on a transient SMTP error which can be ignored because at least one fail-over SMTP server hasn't been tried yet.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public event SmtpTransientErrorOccurredEventHandler TransientErrorOccurred
Public Event TransientErrorOccurred As SmtpTransientErrorOccurredEventHandler

Value

Type: MailBee.SmtpMailSmtpTransientErrorOccurredEventHandler
Remarks

This event may not occur if only a single SMTP server is available for sending to the domain for which sending has failed.

This event lets the application decide what to do when the current SMTP server reports that it cannot deliver your message to the given e-mail address. You can either let MailBee try another server or stop trying the current message. This choice is helpful because the library itself cannot determine if sending should be stopped. Two kinds of transient errors exists:

  • Temporary errors which can be fixed if another server is tried (e.g. the current server is experiencing temporary failure).
  • Temporary errors which occur by purpose (such as "try again later" grey-listing). You need to try again later, simply trying another server won't help.

Unfortunately, there is no distinction between SMTP codes for these errors. Thus, the app or even the user will have to make choice based on their preferences (or you can examine the human-readable response from the server although this is not reliable). If you subscribe to this event, you can control this behavior. If you don't subscribe, MailBee will retry if there is at least one more SMTP relay server left (in case if you're sending via SMTP relay servers) and won't retry in case of direct send.

This default behavior is a general recommendation: you should retry in case of relay SMTP servers (SmtpServers) and don't retry if you're using direct send (MX lookup) so that SmtpServers is empty. SMTP servers obtained via MX lookup often use greylisting so in most cases retrying with another MX will make your IP address getting banned. If, however, your situation is different, you can use this event to adjust the default behavior.

Examples
This sample sends enables retries of SMTP MX servers (if there are multiple available for the given recipient's e-mail domain) in case of direct sends.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;

class Sample
{
    // TransientErrorOccurred event handler.
    private static void OnTransientErrorOccurred(object sender,
        SmtpTransientErrorOccurredEventArgs e)
    {
        Console.WriteLine("SMTP error code: " + e.Reason.ErrorCode);
        Console.WriteLine("Server response: " + e.Reason.ResponseString);
        e.Continue = true; // Enable SMTP MX retries.
    }

    // The actual code.
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();

        // Logging is cool for debugging.
        mailer.Log.Enabled = true;
        mailer.Log.Filename = @"C:\Temp\log.txt";
        mailer.Log.Clear();

        // Get DNS servers from the system.
        mailer.DnsServers.Autodetect();

        // Subscribe to the event.
        mailer.TransientErrorOccurred +=
            new SmtpTransientErrorOccurredEventHandler(OnTransientErrorOccurred);

        // Prepare and send the message
        mailer.To.AsString = "john@theirdomain.com";
        mailer.From.Email = "alice@yourdomain.com";
        mailer.Subject = "Test message";
        mailer.Send();
    }
}
Imports MailBee
Imports MailBee.SmtpMail

Class Sample
    ' TransientErrorOccurred event handler.
    Private Shared Sub OnTransientErrorOccurred(ByVal sender As Object, ByVal e As SmtpTransientErrorOccurredEventArgs)
        Console.WriteLine("SMTP error code: " & e.Reason.ErrorCode)
        Console.WriteLine("Server response: " & e.Reason.ResponseString)
        e.Continue = True    ' Enable SMTP MX retries.
    End Sub

    ' The actual code.
    Shared Sub Main(ByVal args As String())
        Dim mailer As New Smtp()

        ' Logging is cool for debugging.
        mailer.Log.Enabled = True
        mailer.Log.Filename = "C:\Temp\log.txt"
        mailer.Log.Clear()

        ' Get DNS servers from the system.
        mailer.DnsServers.Autodetect()

        ' Subscribe to the event.
        AddHandler mailer.TransientErrorOccurred, AddressOf OnTransientErrorOccurred

        ' Prepare and send the message
        mailer.To.AsString = "john@theirdomain.com"
        mailer.From.Email = "alice@yourdomain.com"
        mailer.Subject = "Test message"
        mailer.Send()
    End Sub
End Class
See Also

Reference

Smtp Class
MailBee.SmtpMail Namespace


Smtp8bitDataConversion Enumeration

Smtp8bitDataConversion Enumeration
Defines the available actions to perform when the message contains 8bit data when the SMTP server does not support transmission of 8bit data.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum Smtp8bitDataConversion
Public Enumeration Smtp8bitDataConversion
Members
Member name | Value | Description
DoNothing | 0 | Do not care about 8bit-to-7bit conversion. The fastest setting.
ConvertAndWarn | 1 | Check if the SMTP server supports 8BITMIME/BINARYMIME extensions. If they are supported, no conversion will be made. If they are not supported, convert the data into 7bit and raise ErrorOccurred warning event passing MailBeeSmtp8bitDataNotSupportedException as Reason parameter value, and also put the corresponding message into the log if logging is enabled.
ConvertAndForget | 2 | Check 8BITMIME/BINARYMIME availibility and silently convert the data into 7bit if 8BITMIME/BINARYMIME not supported.
WarnOnly | 3 | Check 8BITMIME/BINARYMIME availibility and, if they are not supported, raise ErrorOccurred warning event passing MailBeeSmtp8bitDataNotSupportedException as Reason parameter value, and also put the corresponding message into the log if logging is enabled.
ThrowException | 4 | Check 8BITMIME/BINARYMIME availibility and, if they are not supported, throw MailBeeSmtp8bitDataNotSupportedException.
Remarks

The developer can set this action via Conversion8BitTo7bit property.

All modes other than DoNothing will either take advantage of 8BITMIME (RFC1426) and BINARYMIME (RFC1830.4) extensions (so that no 8bit-to-7bit conversion will be made) or do 8bit-to-7bit conversion (or throw exceptions, raise warning events, etc) if the SMTP server does not support these extensions or MailBee was configured to operate in classic SMTP mode with all ESMTP extensions disabled (see SmtpOptions for details).

See Also

Reference

MailBee.SmtpMail Namespace
SmtpConversion8BitTo7bit


SmtpServer Class

SmtpServer Class
Represents an SMTP relay server to which the mail messages will be sent.
Inheritance Hierarchy
SystemObject
MailBee.SmtpMailSmtpServer

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class SmtpServer : ISortableByPriority
<SerializableAttribute>
Public Class SmtpServer
    Implements ISortableByPriority

The SmtpServer type exposes the following members.

Constructors
 | Name | Description
Public method | SmtpServer | Initializes a new instance of the SmtpServer class.
Public method | SmtpServer(String) | Initializes a new instance of the SmtpServer class with the given host name or IP address string, and assigns the top priority to this instance.
Public method | SmtpServer(String, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given host name (or IP address string) and port number, and assigns the specified priority to this instance.
Public method | SmtpServer(String, String, String) | Initializes a new instance of the SmtpServer class with the given host name or IP address string, enables ESMTP authentication and assigns the top priority to this instance.
Public method | SmtpServer(String, String, String, AuthenticationMethods) | Initializes a new instance of the SmtpServer class with the given host name or IP address string, enables ESMTP authentication using the specified methods, and assigns the top priority to this instance.
Public method | SmtpServer(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions) | Initializes a new instance of the SmtpServer class with the given parameter values.
Public method | SmtpServer(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions, Int32, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given parameter values.
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | AccountDomain | Gets or sets the user domain name on the SMTP relay server.
Public property | AccountName | Gets or sets the user account name on the SMTP relay server.
Public property | AllowRefusedRecipients | Gets or sets whether refused recipients should be allowed when submitting a mail message to the server.
Public property | AuthMethods | Gets or sets a set of authentication methods which can be used when authenticating the user on the server.
Public property | AuthOptions | Gets or sets the options which alter ESMTP authentication process.
Public property | AuthPopBeforeSmtp | Gets or sets whether the Smtp component should perform POP-before-SMTP authentication prior to connecting to the SMTP server.
Public property | AuthUserDefined | Gets or sets a reference to the instance of a class implementing custom SASL authentication mechanism.
Public property | HelloDomain | Gets or sets the string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details).
Public property | IgnoreLoginFailure | Gets or sets whether the Smtp component should ignore ESMTP or POP-before-SMTP authentication error (if any) and still attempt to send the message.
Public property | LocalEndPoint | Gets or sets the local end point which will be used when connecting to the SMTP server.
Public property | MaxConnectionCount | Gets or sets the maximum number of simultaneous connections to this SMTP server in multi-thread sending mode.
Public property | MaxSendPerSessionCount | Gets or sets the maximum number of e-mail messages which can be sent within a single connection with the server.
Public property | Name | Gets or sets the host name or IP address string of the SMTP relay server.
Public property | Password | Gets or sets the user account password on the SMTP relay server.
Public property | PauseInterval | Gets or sets the amount of time MailBee must wait prior to connecting to the server after last disconnection from this server.
Public property | Pipelining | Gets or sets whether to use commands pipelining if it's supported by the server.
Public property | Port | Gets or sets the port number on which to communicate with the SMTP relay server.
Public property | Priority | Gets or sets the usage preference of this SMTP relay server as compared to preferences of other servers in SmtpServers and DnsServers collections.
 | Proxy | Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.
Public property | SmtpOptions | Gets or sets the options which can be used to disable certain extended SMTP capabilities.
 | SslCertificates | Provides access to the client and server SSL certificate settings.
 | SslMode | Gets or sets how the component should establish TLS/SSL connection with the mail server.
Public property | SslProtocol | Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.
Public property | TargetName | Gets or sets the target name (Service Principal Name, SPN) of the SMTP relay server.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the Smtp component will wait for a response from this server.
Top
Remarks

This class is used to specify an SMTP relay server the mail messages should be submitted to. Another type of SMTP server is SMTP MX server which is a server which accepts mail for a particular domain. When the mail message is submitted to SMTP relay server, the relay server performs the following operations:

  • The message is received from the client
  • For each recipient e-mail address, the domain part is extracted, and duplicates are removed (example: for user1@domain1.com, user2@domain1.com, user1@domain2.com, user3@domain1.com), the list of unique domains is domain1.com, domain2.com)
  • For each of the unique domains, DNS MX lookup query is sent to the DNS server
  • For each domain, the DNS server returns the list of SMTP MX servers which accept mail for this domain
  • The relay server then relays the mail message to SMTP MX server of each domain
In other words, SMTP relay server dispatches the mail message received from the client, to the SMTP MX servers of the target recipients.

To specify SMTP relay server in your application, call mailer.SmtpServers.Add method (assuming mailer is an instance of Smtp class).

Note Note
When MailBee is used in direct send mode (by performing DNS MX lookup against DNS servers in DnsServers collection), MailBee itself acts as SMTP relay server, and dispatches the mail message to the MX servers of recipients domains.
Examples
Another example of specifying SMTP relay server in the application is available at SslMode topic.
See Also

Reference

MailBee.SmtpMail Namespace


SmtpServer Constructor

SmtpServer Constructor
Overload List
 | Name | Description
Public method | SmtpServer | Initializes a new instance of the SmtpServer class.
Public method | SmtpServer(String) | Initializes a new instance of the SmtpServer class with the given host name or IP address string, and assigns the top priority to this instance.
Public method | SmtpServer(String, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given host name (or IP address string) and port number, and assigns the specified priority to this instance.
Public method | SmtpServer(String, String, String) | Initializes a new instance of the SmtpServer class with the given host name or IP address string, enables ESMTP authentication and assigns the top priority to this instance.
Public method | SmtpServer(String, String, String, AuthenticationMethods) | Initializes a new instance of the SmtpServer class with the given host name or IP address string, enables ESMTP authentication using the specified methods, and assigns the top priority to this instance.
Public method | SmtpServer(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions) | Initializes a new instance of the SmtpServer class with the given parameter values.
Public method | SmtpServer(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions, Int32, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given parameter values.
Top
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer Constructor

SmtpServer Constructor
Initializes a new instance of the SmtpServer class.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer()
Public Sub New
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace


SmtpServer Constructor (String)

SmtpServer Constructor (String)
Initializes a new instance of the SmtpServer class with the given host name or IP address string, and assigns the top priority to this instance.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer(
    string name
)
Public Sub New (
    name As String
)

Parameters

name
Type: SystemString
The host name or IP address of the SMTP relay server.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
Remarks
You can find more information on the server priority in SortableByPriorityCollection class documentation.
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace
MailBeeSortableByPriorityCollection


SmtpServer Constructor (String, Int32, Int32)

SmtpServer Constructor (String, Int32, Int32)
Initializes a new instance of the SmtpServer class with the given host name (or IP address string) and port number, and assigns the specified priority to this instance.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer(
    string name,
    int port,
    int priority
)
Public Sub New (
    name As String,
    port As Integer,
    priority As Integer
)

Parameters

name
Type: SystemString
The host name or IP address of the SMTP relay server.
port
Type: SystemInt32
The port on which to communicate with the SMTP relay server. The standard SMTP port is 25.
priority
Type: SystemInt32
A preference of the SMTP relay server. Lower values are preferred.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic) or port is an invalid port number.
Remarks
You can find more information on the server priority in SortableByPriorityCollection class documentation.
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace
MailBeeSortableByPriorityCollection


SmtpServer Constructor (String, String, String)

SmtpServer Constructor (String, String, String)
Initializes a new instance of the SmtpServer class with the given host name or IP address string, enables ESMTP authentication and assigns the top priority to this instance.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer(
    string name,
    string accountName,
    string password
)
Public Sub New (
    name As String,
    accountName As String,
    password As String
)

Parameters

name
Type: SystemString
The host name or IP address of the SMTP relay server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
Remarks
This constructor automatically sets AuthMethods property value to Auto.
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace
MailBeeSortableByPriorityCollection


SmtpServer Constructor (String, String, String, AuthenticationMethods)

SmtpServer Constructor (String, String, String, AuthenticationMethods)
Initializes a new instance of the SmtpServer class with the given host name or IP address string, enables ESMTP authentication using the specified methods, and assigns the top priority to this instance.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer(
    string name,
    string accountName,
    string password,
    AuthenticationMethods authMethods
)
Public Sub New (
    name As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods
)

Parameters

name
Type: SystemString
The host name or IP address of the SMTP relay server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when authenticating the user on the server.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic).
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace
MailBeeSortableByPriorityCollection


SmtpServer Constructor (String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions)

SmtpServer Constructor (String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions)
Initializes a new instance of the SmtpServer class with the given parameter values.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer(
    string name,
    int port,
    int priority,
    int timeout,
    bool pipelining,
    AuthenticationMethods authMethods,
    string accountName,
    string password,
    bool allowRefusedRecipients,
    string helloDomain,
    ExtendedSmtpOptions smtpOptions
)
Public Sub New (
    name As String,
    port As Integer,
    priority As Integer,
    timeout As Integer,
    pipelining As Boolean,
    authMethods As AuthenticationMethods,
    accountName As String,
    password As String,
    allowRefusedRecipients As Boolean,
    helloDomain As String,
    smtpOptions As ExtendedSmtpOptions
)

Parameters

name
Type: SystemString
The host name or IP address of the SMTP relay server.
port
Type: SystemInt32
The port on which to communicate with the SMTP relay server. The standard SMTP port is 25.
priority
Type: SystemInt32
A preference of the SMTP relay server. Lower values are preferred.
timeout
Type: SystemInt32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error, or zero to wait indefinitely.
pipelining
Type: SystemBoolean
Specifies whether to use commands pipelining (ESMTP PIPELINING) if it's supported by the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when authenticating the user on the server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.
allowRefusedRecipients
Type: SystemBoolean
Specifies whether refused recipients should be allowed when submitting a mail message to the server.
helloDomain
Type: SystemString
The string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details).
smtpOptions
Type: MailBee.SmtpMailExtendedSmtpOptions
A set of flags which can be used to disable certain extended SMTP capabilities.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic) or port is an invalid port number or timeout is negative.
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace


SmtpServer Constructor (String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions, Int32, Int32, Int32)

SmtpServer Constructor (String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions, Int32, Int32, Int32)
Initializes a new instance of the SmtpServer class with the given parameter values.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer(
    string name,
    int port,
    int priority,
    int timeout,
    bool pipelining,
    AuthenticationMethods authMethods,
    string accountName,
    string password,
    bool allowRefusedRecipients,
    string helloDomain,
    ExtendedSmtpOptions smtpOptions,
    int maxConnectionCount,
    int maxSendPerSessionCount,
    int pauseInterval
)
Public Sub New (
    name As String,
    port As Integer,
    priority As Integer,
    timeout As Integer,
    pipelining As Boolean,
    authMethods As AuthenticationMethods,
    accountName As String,
    password As String,
    allowRefusedRecipients As Boolean,
    helloDomain As String,
    smtpOptions As ExtendedSmtpOptions,
    maxConnectionCount As Integer,
    maxSendPerSessionCount As Integer,
    pauseInterval As Integer
)

Parameters

name
Type: SystemString
The host name or IP address of the SMTP relay server.
port
Type: SystemInt32
The port on which to communicate with the SMTP relay server. The standard SMTP port is 25.
priority
Type: SystemInt32
A preference of the SMTP relay server. Lower values are preferred.
timeout
Type: SystemInt32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error, or zero to wait indefinitely.
pipelining
Type: SystemBoolean
Specifies whether to use commands pipelining (ESMTP PIPELINING) if it's supported by the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when authenticating the user on the server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.
allowRefusedRecipients
Type: SystemBoolean
Specifies whether refused recipients should be allowed when submitting a mail message to the server.
helloDomain
Type: SystemString
The string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details).
smtpOptions
Type: MailBee.SmtpMailExtendedSmtpOptions
A set of flags which can be used to disable certain extended SMTP capabilities.
maxConnectionCount
Type: SystemInt32
The maximum number of simultaneous connections to this SMTP server in multi-thread sending mode, or -1 if unlimited.
maxSendPerSessionCount
Type: SystemInt32
The maximum number of e-mail messages which can be sent within a single connection with the server, or -1 if unlimited.
pauseInterval
Type: SystemInt32
The amount of time in milliseconds MailBee must wait prior to connecting to the server after last disconnection from this server, or zero if instant reconnecting allowed.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | name is a null reference (Nothing in Visual Basic), or any of port, timeout, maxSendPerSessionCount, maxConnectionCount, or pauseInterval parameters is an invalid value.
See Also

Reference

SmtpServer Class
SmtpServer Overload
MailBee.SmtpMail Namespace


SmtpServer Methods

SmtpServer Methods

The SmtpServer type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer Properties

SmtpServer Properties

The SmtpServer type exposes the following members.

Properties
 | Name | Description
Public property | AccountDomain | Gets or sets the user domain name on the SMTP relay server.
Public property | AccountName | Gets or sets the user account name on the SMTP relay server.
Public property | AllowRefusedRecipients | Gets or sets whether refused recipients should be allowed when submitting a mail message to the server.
Public property | AuthMethods | Gets or sets a set of authentication methods which can be used when authenticating the user on the server.
Public property | AuthOptions | Gets or sets the options which alter ESMTP authentication process.
Public property | AuthPopBeforeSmtp | Gets or sets whether the Smtp component should perform POP-before-SMTP authentication prior to connecting to the SMTP server.
Public property | AuthUserDefined | Gets or sets a reference to the instance of a class implementing custom SASL authentication mechanism.
Public property | HelloDomain | Gets or sets the string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details).
Public property | IgnoreLoginFailure | Gets or sets whether the Smtp component should ignore ESMTP or POP-before-SMTP authentication error (if any) and still attempt to send the message.
Public property | LocalEndPoint | Gets or sets the local end point which will be used when connecting to the SMTP server.
Public property | MaxConnectionCount | Gets or sets the maximum number of simultaneous connections to this SMTP server in multi-thread sending mode.
Public property | MaxSendPerSessionCount | Gets or sets the maximum number of e-mail messages which can be sent within a single connection with the server.
Public property | Name | Gets or sets the host name or IP address string of the SMTP relay server.
Public property | Password | Gets or sets the user account password on the SMTP relay server.
Public property | PauseInterval | Gets or sets the amount of time MailBee must wait prior to connecting to the server after last disconnection from this server.
Public property | Pipelining | Gets or sets whether to use commands pipelining if it's supported by the server.
Public property | Port | Gets or sets the port number on which to communicate with the SMTP relay server.
Public property | Priority | Gets or sets the usage preference of this SMTP relay server as compared to preferences of other servers in SmtpServers and DnsServers collections.
 | Proxy | Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.
Public property | SmtpOptions | Gets or sets the options which can be used to disable certain extended SMTP capabilities.
 | SslCertificates | Provides access to the client and server SSL certificate settings.
 | SslMode | Gets or sets how the component should establish TLS/SSL connection with the mail server.
Public property | SslProtocol | Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.
Public property | TargetName | Gets or sets the target name (Service Principal Name, SPN) of the SMTP relay server.
Public property | Timeout | Gets or sets the amount of time (in milliseconds) the Smtp component will wait for a response from this server.
Top
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AccountDomain Property

SmtpServerAccountDomain Property
Gets or sets the user domain name on the SMTP relay server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountDomain { get; set; }
Public Property AccountDomain As String
    Get
    Set

Property Value

Type: String
The user domain name on the SMTP relay server. The default value is a null reference (Nothing in Visual Basic) which means "use the current domain".
Remarks
This value is only used with MS-specific authentication methods like NTLM or GSSAPI.
Note Note
If you specify this property to an empty string (not to a null reference), it will assume the user does not belong to any domain.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AccountName Property

SmtpServerAccountName Property
Gets or sets the user account name on the SMTP relay server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string AccountName { get; set; }
Public Property AccountName As String
    Get
    Set

Property Value

Type: String
The user account name on the SMTP relay server. The default value is an empty string.
Remarks
If you're using NTLM or GSSAPI authentication, missing AccountName will tell MailBee to authenticate as the current Windows user (Integrated Windows Authentication).
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AllowRefusedRecipients Property

SmtpServerAllowRefusedRecipients Property
Gets or sets whether refused recipients should be allowed when submitting a mail message to the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AllowRefusedRecipients { get; set; }
Public Property AllowRefusedRecipients As Boolean
    Get
    Set

Property Value

Type: Boolean
A boolean value specifying whether refused recipients should be allowed when submitting a mail message to the server. The default value is true.
Remarks

If this property is true, MailBee will send the message if at least one recipient has been accepted by the server. The developer can subscribe to ErrorOccurred warning event to keep track of occurrences of this event in order to receive notification when certain recipient gets refused. Or, the developer can just call GetRefusedRecipients method after sending the message to get the list of refused recipients.

The developer can also subscribe to MessageRecipientSubmitted event and control whether to allow or disallow failed recipients for every recipient separately.

See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AuthMethods Property

SmtpServerAuthMethods Property
Gets or sets a set of authentication methods which can be used when authenticating the user on the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationMethods AuthMethods { get; set; }
Public Property AuthMethods As AuthenticationMethods
    Get
    Set

Property Value

Type: AuthenticationMethods
An AuthenticationMethods value containing bitwise combination of flags specifying which SASL authentication methods can be used when authenticating the user on the server. The default value is None (ESMTP authentication is not used, so that AccountName and Password values are ignored).
Remarks

This property specifies a set of the methods MailBee can choose from during performing ESMTP authentication (starting from the most secure method to less secure). MailBee, however, will not try methods which are not supported by the server even if they are listed in AuthMethods value. In particular, only SASL methods can be tried, since ESMTP authentication does not support any non-SASL methods.

Sometimes, the mail server may support certain SASL method even if it's not listed in the server capabilities. To force MailBee try even those methods which seem to be unsupported by the server, set TryUnsupportedMethods flag in AuthOptions property value.

For example of using OAuth 2.0, see GetXOAuthKeyStatic(String, String) topic.

See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AuthOptions Property

SmtpServerAuthOptions Property
Gets or sets the options which alter ESMTP authentication process.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public AuthenticationOptions AuthOptions { get; set; }
Public Property AuthOptions As AuthenticationOptions
    Get
    Set

Property Value

Type: AuthenticationOptions
An AuthenticationOptions value containing bitwise combination of flags affecting MailBee's default behavior during ESMTP authentication on the server. The default value is None (unless SafeMode is true).
Remarks
If SafeMode was true to the moment of creating this SmtpServer object, AuthOptions will be set to 4 (PreferSimpleMethods).
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AuthPopBeforeSmtp Property

SmtpServerAuthPopBeforeSmtp Property
Gets or sets whether the Smtp component should perform POP-before-SMTP authentication prior to connecting to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool AuthPopBeforeSmtp { get; set; }
Public Property AuthPopBeforeSmtp As Boolean
    Get
    Set

Property Value

Type: Boolean
A boolean value specifying whether the Smtp component should perform POP-before-SMTP authentication prior to connecting to the SMTP server. The default value is false.
Remarks

POP-before-SMTP authentication is used by some older mail systems which do not support ESMTP authentication to authenticate users. In this scenario, Smtp component connects to the POP3 server first, authenticates the user, disconnects from the POP3 server, and immediately reconnects to the SMTP server.

Automatic POP-before-SMTP authentication (which is performed when this property is true) requires the POP3 server run on the same host as the SMTP server (e.g. both servers are mail.domain.com). If it's not so (e.g. pop.domain.com for POP3 and smtp.domain.com for SMTP), AuthPopBeforeSmtp(String, Int32, String, String) method can be called prior to connecting to the SMTP server instead of setting AuthPopBeforeSmtp to true.

Note Note
After POP-before-SMTP authentication was performed and the connection with the server was established, there is no need to call Login method. Login method performs ESMTP authentication only.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.AuthUserDefined Property

SmtpServerAuthUserDefined Property
Gets or sets a reference to the instance of a class implementing custom SASL authentication mechanism.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SaslMethod AuthUserDefined { get; set; }
Public Property AuthUserDefined As SaslMethod
    Get
    Set

Property Value

Type: SaslMethod
A reference to the instance of a class implementing custom SASL authentication mechanism, or a null reference (Nothing in Visual Basic) if no user-defined SASL method was supplied. The default value is a null reference.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.HelloDomain Property

SmtpServerHelloDomain Property
Gets or sets the string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details).

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string HelloDomain { get; set; }
Public Property HelloDomain As String
    Get
    Set

Property Value

Type: String
The string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details). The default value is a null reference.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.IgnoreLoginFailure Property

SmtpServerIgnoreLoginFailure Property
Gets or sets whether the Smtp component should ignore ESMTP or POP-before-SMTP authentication error (if any) and still attempt to send the message.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool IgnoreLoginFailure { get; set; }
Public Property IgnoreLoginFailure As Boolean
    Get
    Set

Property Value

Type: Boolean
The boolean value specifying whether the Smtp component should ignore ESMTP or POP-before-SMTP authentication error (if any) and still attempt to send the message. The default value is false.
Remarks
Since ESMTP and POP-before-SMTP authentication is not always necessary in order to send the message, the component can be told to try to send the message even if the authentication fails. Usually, SMTP relay servers allow unauthenticated users to send mail to local recipients only (i.e. to user@localdomain.com but not to user@remotedomain.com, provided that the SMTP relay server is somewhat like mail.localdomain.com).
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.LocalEndPoint Property

SmtpServerLocalEndPoint Property
Gets or sets the local end point which will be used when connecting to the SMTP server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public EndPoint LocalEndPoint { get; set; }
Public Property LocalEndPoint As EndPoint
    Get
    Set

Property Value

Type: EndPoint
A reference to the local end point to be used when connecting to the SMTP server, or a null reference (Nothing in Visual Basic) if the local end point should be assigned automatically. The default value is a null reference.
Remarks

If the computer running MailBee has multiple IP addresses assigned (for instance, it has several network adapters installed), you can set this property to the IP address and port which should be used for outbound connections. See Bind(EndPoint) and LocalEndPoint topics for more information.

If you're sending in "direct send" mode (not using SMTP relay server), the property to be set in this case is Smtp.DirectSendDefaults.LocalEndPoint.

See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.MaxConnectionCount Property

SmtpServerMaxConnectionCount Property
Gets or sets the maximum number of simultaneous connections to this SMTP server in multi-thread sending mode.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxConnectionCount { get; set; }
Public Property MaxConnectionCount As Integer
    Get
    Set

Property Value

Type: Int32
Non-zero integer specifying the maximum allowed number of simultaneous connections to this server in multi-thread sending mode. The default value is -1 (number of connections is unlimited).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is zero.
Remarks
In multi-thread mode (MaxThreadCount > 1) the Smtp component can establish multiple connections to the same SMTP server. However, if MaxThreadCount is fairly high and the server resticts the number of simultaneous connections from the same IP address to a certain value, it will start rejecting connection attempts if the current connection count exceeds the allowed limit. In this case, MaxConnectionCount property value must be set to any positive value which does not exceed the corresponding setting on the SMTP server.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace
SmtpMaxThreadCount


SmtpServer.MaxSendPerSessionCount Property

SmtpServerMaxSendPerSessionCount Property
Gets or sets the maximum number of e-mail messages which can be sent within a single connection with the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int MaxSendPerSessionCount { get; set; }
Public Property MaxSendPerSessionCount As Integer
    Get
    Set

Property Value

Type: Int32
Non-zero integer specifying the maximum number of e-mail messages which can be successfully submitted to the SMTP relay server within a single session. The default value is -1 (number of submissions per session is unlimited).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is zero.
Remarks
To prevent abuse or spam, many mail servers limit the maximum number of e-mail messages accepted from a client during a single SMTP session. The developer can use MaxSendPerSessionCount property to restrict the number of e-mail submissions from MailBee to the SMTP relay server within a single session. When this number is exceeded, MailBee will disconnect from the server and either use another server (if SmtpServers collection contains other servers with the same or higher priority) or wait for PauseInterval milliseconds and then attempt to connect to the server again to send another portion of the messages.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace
SmtpServerPauseInterval


SmtpServer.Name Property

SmtpServerName Property
Gets or sets the host name or IP address string of the SMTP relay server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Name { get; set; }
Public Property Name As String
    Get
    Set

Property Value

Type: String
The host name or IP address string of the SMTP relay server. The default value is DefaultServerName.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is a null reference (Nothing in Visual Basic).
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.Password Property

SmtpServerPassword Property
Gets or sets the user account password on the SMTP relay server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string Password { get; set; }
Public Property Password As String
    Get
    Set

Property Value

Type: String
The user account password on the SMTP relay server. The default value is an empty string.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.PauseInterval Property

SmtpServerPauseInterval Property
Gets or sets the amount of time MailBee must wait prior to connecting to the server after last disconnection from this server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int PauseInterval { get; set; }
Public Property PauseInterval As Integer
    Get
    Set

Property Value

Type: Int32
Non-negative integer specifying the mimimum amount of time (in milliseconds) between disconnection from the server and subsequent connection attempt to the same server. The default value is 0 (no waiting required).
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
To prevent abuse or spam, many mail servers limit the maximum number of connection attempts per minute (or per hour, day, etc) from a single client IP address. The number of e-mail submissions to the server within a single session may also be restricted (see MaxSendPerSessionCount property). The developer can use PauseInterval property to force MailBee to make connections with the server less frequently. For instance, if the server accepts not more than 20 connections per minute from a single IP address, the developer should set PauseInterval value to at least 3000 (3000 * 20 = 60000 milliseconds = 1 minute).
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace
SmtpServerMaxSendPerSessionCount


SmtpServer.Pipelining Property

SmtpServerPipelining Property
Gets or sets whether to use commands pipelining if it's supported by the server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public bool Pipelining { get; set; }
Public Property Pipelining As Boolean
    Get
    Set

Property Value

Type: Boolean
A boolean value specifying whether to use commands pipelining (ESMTP PIPELINING) if it's supported by the server. The default value is Pipelining.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.Port Property

SmtpServerPort Property
Gets or sets the port number on which to communicate with the SMTP relay server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Port { get; set; }
Public Property Port As Integer
    Get
    Set

Property Value

Type: Int32
The port number on which to communicate with the SMTP relay server. The default value is 25.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is an invalid port number.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.Priority Property

SmtpServerPriority Property
Gets or sets the usage preference of this SMTP relay server as compared to preferences of other servers in SmtpServers and DnsServers collections.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Priority { get; set; }
Public Property Priority As Integer
    Get
    Set

Property Value

Type: Int32
An integer value in the range 0 to 999 (lower values are preferred, i.e. 0 is the highest priority while 999 is the lowest priority), specifying the order in which Smtp component will connect to the servers if more than one server is specified in SmtpServers and DnsServers collection.
Remarks
Priority can be used to split the available servers into groups (for instance, define primary servers and backup servers) and combine different methods of sending mail (for instance, if top priority SMTP relay server in SmtpServers collection has higher priority than top priority DNS server in DnsServers collection, MailBee will attempt to send to relay servers first, and use direct send if sending to relay servers failed).
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.Proxy Property

SmtpServerProxy Property
Provides access to the settings which allow MailBee to connect to a mail server via a proxy server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ProxyServer Proxy { get; }
Public ReadOnly Property Proxy As ProxyServer
    Get

Property Value

Type: ProxyServer
A reference to the proxy server settings.
Remarks
By default, proxy server is not used. The developer can change this to make MailBee use SOCKS4, SOCKS5, or HTTP proxy server. This is useful when a firewall prohibits direct connections with a mail server but permits connections via a proxy.
Examples
This console sample establishes connection with the mail server via an HTTP proxy server which requires clients to authenticate themselves.
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Proxy;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        SmtpServer server = new SmtpServer("mail.domain.com");
        server.Proxy.Name = "proxy.server.com";
        server.Proxy.Protocol = ProxyProtocol.Http;
        server.Proxy.Port = 808;
        server.Proxy.AccountName = "jdoe";
        server.Proxy.Password = "secret";
        mailer.SmtpServers.Add(server);
        mailer.Connect();
        Console.WriteLine("Connected via a proxy server");
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Proxy

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp
        Dim server As SmtpServer = New SmtpServer("mail.domain.com")
        server.Proxy.Name = "proxy.server.com"
        server.Proxy.Protocol = ProxyProtocol.Http
        server.Proxy.Port = 808
        server.Proxy.AccountName = "jdoe"
        server.Proxy.Password = "secret"
        mailer.SmtpServers.Add(server)
        mailer.Connect()
        Console.WriteLine("Connected via a proxy server")
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.SmtpOptions Property

SmtpServerSmtpOptions Property
Gets or sets the options which can be used to disable certain extended SMTP capabilities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ExtendedSmtpOptions SmtpOptions { get; set; }
Public Property SmtpOptions As ExtendedSmtpOptions
    Get
    Set

Property Value

Type: ExtendedSmtpOptions
An ExtendedSmtpOptions value containing bitwise combination of flags which disable certain extended SMTP capabilities. The default value is Default (unless SafeMode is true).
Remarks

If this property value is set to ClassicSmtpMode, no ESMTP extensions will be used (including PIPELINING and AUTH).

If SafeMode was true to the moment of creating this SmtpServer object, SmtpOptions will be set to 7.

See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.SslCertificates Property

SmtpServerSslCertificates Property
Provides access to the client and server SSL certificate settings.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public ClientServerCertificates SslCertificates { get; }
Public ReadOnly Property SslCertificates As ClientServerCertificates
    Get

Property Value

Type: ClientServerCertificates
A reference to the client and server SSL certificate settings.
Remarks

The following code should be used to access the server certificate (assuming server is an SmtpServer class instance currently used by Smtp component as an SMTP server definition): server.SslCertificates.Server. To set the client certificate, the developer should assign server.SslCertificates.Client property.

Note Note
To use SSL certificates, your license key must include Security license. See Powerup class for details.
Examples
This console sample establishes secure connection with the mail server using the private certificate of the client and then displays various information about the server certificate. The client certificate is taken from a file (MailBee can also read certificates from the registry, see CertificateStore class description for details).
C#
VB
Copy
using System;
using MailBee;
using MailBee.SmtpMail;
using MailBee.Security;

class Sample
{
    static void Main(string[] args)
    {
        Smtp mailer = new Smtp();
        SmtpServer server = new SmtpServer("mail.domain.com");
        server.SslMode = SslStartupMode.UseStartTls;
        server.SslCertificates.Client = new Certificate(@"C:\my.pfx", CertFileType.Pfx, "secret");
        mailer.SmtpServers.Add(server);
        mailer.Connect();
        mailer.Hello();
        Console.WriteLine("The server certificate info");
        Console.WriteLine("===========================");
        Console.WriteLine("Issued by:    " + server.SslCertificates.Server.IssuedBy);
        Console.WriteLine("Issued to:    " + server.SslCertificates.Server.IssuedTo);
        Console.WriteLine("Valid from:    " + server.SslCertificates.Server.ValidFromDate);
        Console.WriteLine("Valid to:    " + server.SslCertificates.Server.ValidToDate);
        mailer.Disconnect();
    }
}
Imports System
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Security

Class Sample
    Shared Sub Main(ByVal args() As String)
        Dim mailer As Smtp = New Smtp
        Dim server As SmtpServer = New SmtpServer("mail.domain.com")
        server.SslMode = SslStartupMode.UseStartTls
        server.SslCertificates.Client = New Certificate("C:\my.pfx", CertFileType.Pfx, "secret")
        mailer.SmtpServers.Add(server)
        mailer.Connect()
        mailer.Hello()
        Console.WriteLine("The server certificate info")
        Console.WriteLine("===========================")
        Console.WriteLine("Issued by:    " & server.SslCertificates.Server.IssuedBy)
        Console.WriteLine("Issued to:    " & server.SslCertificates.Server.IssuedTo)
        Console.WriteLine("Valid from:    " & server.SslCertificates.Server.ValidFromDate)
        Console.WriteLine("Valid to:    " & server.SslCertificates.Server.ValidToDate)
        mailer.Disconnect()
    End Sub
End Class
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace
MailBee.SecurityCertificate
MailBee.SecurityCertificateStore


SmtpServer.SslMode Property

SmtpServerSslMode Property
Gets or sets how the component should establish TLS/SSL connection with the mail server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SslStartupMode SslMode { get; set; }
Public Property SslMode As SslStartupMode
    Get
    Set

Property Value

Type: SslStartupMode
One of SslStartupMode values specifying if and how the component should establish TLS/SSL connection with the mail server. The default value is Manual which means the connection won't be established in TLS/SSL mode unless the developer manually calls StartTls method.
Remarks
Note Note
Not all mail servers support TLS/SSL functionality. Also, some servers support only TLS or only SSL (see SslProtocol topic for details).
Examples
This sample submits a mail message to the SMTP server through the secure TLS/SSL connection. The connection is made to the regular SMTP port 25, and STARTTLS command is sent to switch the connection into TLS/SSL mode.
C#
VB
Copy
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.SmtpMail;
using MailBee.Security;

// The actual code (put it into a method of your class).
Smtp mailer = new Smtp();
SmtpServer server = new SmtpServer("mail.domain.com", "jdoe", "secret");
server.SslMode = SslStartupMode.UseStartTls;
mailer.SmtpServers.Add(server);
mailer.From.Email = "jdoe@domain.com";
mailer.To.Add("kathy@company.com");
mailer.Subject = "Report";
mailer.BodyPlainText = "The report contents";
mailer.Send();
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.SmtpMail
Imports MailBee.Security

' The actual code (put it into a method of your class).
Dim mailer As New Smtp
Dim server As SmtpServer = New SmtpServer("mail.domain.com", "jdoe", "secret")
server.SslMode = SslStartupMode.UseStartTls
mailer.SmtpServers.Add(server)
mailer.From.Email = "jdoe@domain.com"
mailer.To.Add("kathy@company.com")
mailer.Subject = "Report"
mailer.BodyPlainText = "The report contents"
mailer.Send()
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace
SmtpServerSslMode
SmtpServerSslProtocol
SmtpStartTls


SmtpServer.SslProtocol Property

SmtpServerSslProtocol Property
Gets or sets the security protocol to be used for performing TLS/SSL negotiation and data encryption.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SecurityProtocol SslProtocol { get; set; }
Public Property SslProtocol As SecurityProtocol
    Get
    Set

Property Value

Type: SecurityProtocol
One of SecurityProtocol values specifying the security protocol to be used for performing TLS/SSL negotiation and data encryption. The default value is Auto.
Remarks
The default value allows MailBee to select the best (the mosy secure) protocol supported by the mail server. However, if the mail server does not support automatic protocol negotiation, it will likely close the connection (MailBeeSocketResetException will be thrown). In this case, the application should set this property to non-Auto value (such as Tls1).
Note Note
In case of UWP platform, MailBee always uses TlsAuto setting.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.TargetName Property

SmtpServerTargetName Property
Gets or sets the target name (Service Principal Name, SPN) of the SMTP relay server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public string TargetName { get; set; }
Public Property TargetName As String
    Get
    Set

Property Value

Type: String
The target name (SPN) of the SMTP relay server. The default value is a null reference (Nothing in Visual Basic), which means the SPN must be auto-detected.
Remarks

This value is only used during GSSAPI authentication (Kerberos or NTLM). If it's a null reference, MailBee will construct it as "SMTP" + "/" + ServerName. Or, if it's set to a non-empty string, its value will be used as-is. If it's an empty string, GSSAPI authentication will perform as NTLM (not as Kerberos).

You may need to set this property if you want to authenticate with Kerberos and your SMTP server has SPN different from "SMTP" + "/" + ServerName. For instance, IIS SMTP may use "SmtpSvc" + "/" + ServerName.

See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServer.Timeout Property

SmtpServerTimeout Property
Gets or sets the amount of time (in milliseconds) the Smtp component will wait for a response from this server.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public int Timeout { get; set; }
Public Property Timeout As Integer
    Get
    Set

Property Value

Type: Int32
The amount of time (in milliseconds) the Smtp component will wait for data to be received from this server before returning an error, or zero to wait indefinitely. The default value is DefaultTimeout.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | value is negative.
Remarks
By default, MS Exchange 2010 can delay its reply to the e-mail message data submitted with DATA or BDAT LAST command for up to 30 seconds (actual delay values can reach 33 seconds). Due to this, MailBee increases the timeout value to 35000 milliseconds (35 seconds) after submitting e-mail data to the server even if the Timeout value is lower. Once the operation completes (or throws an exception), it's reverted back to the Timeout value. Of course, if you explicitly set Timeout to a value greater than 35000 milliseconds, no timeout correction for DATA/BDAT operation will be made.
See Also

Reference

SmtpServer Class
MailBee.SmtpMail Namespace


SmtpServerCollection Class

SmtpServerCollection Class
Represents a sorted collection of SmtpServer objects.
Inheritance Hierarchy
SystemObject
System.CollectionsCollectionBase
MailBeeSortableByPriorityCollection
MailBee.SmtpMailSmtpServerCollection

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class SmtpServerCollection : SortableByPriorityCollection
<SerializableAttribute>
Public Class SmtpServerCollection
    Inherits SortableByPriorityCollection

The SmtpServerCollection type exposes the following members.

Constructors
 | Name | Description
Public method | SmtpServerCollection | Initializes a new instance of the SmtpServerCollection class
Top
Methods
 | Name | Description
Public method | Add(String) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection and sorts the collection according to the elements priorities.
Public method | Add(SmtpServer) | Adds an SmtpServer to the collection and sorts the collection according to the elements priorities.
Public method | Add(String, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given host name (or IP address string), port number and priority value, adds this instance into the collection, and sorts the collection according to the elements priorities.
Public method | Add(String, String, String) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server, and sorts the collection according to the elements priorities.
Public method | Add(String, String, String, AuthenticationMethods) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server using the specified methods, and sorts the collection according to the elements priorities.
Public method | Add(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions) | Initializes a new instance of the SmtpServer class with the given parameter values, adds this instance to the collection, and sorts the collection according to the elements priorities.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove | Removes the specified SmtpServer object from the collection.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | SortByPriority | Sorts the items in the collection by their priority value. (Inherited from SortableByPriorityCollection.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the element at the specified index.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
Remarks

When SmtpServers collection is populated with at least one SMTP relay server of the same or higher priority than the top priority DNS server in DnsServers collection (or DnsServers collection is empty), Smtp component will attempt to send the mail message to the first SMTP relay server in SmtpServers collection. If it fails, MailBee will attempt to connect and send to lower priority SMTP relay servers. If this fails too and DnsServers collection is not empty, the mail message will be sent in direct send mode.

If the top priority SMTP relay server has lower priority than the top priority DNS server in DnsServers collection, Smtp component will attempt to send the mail message in direct send mode, and then try to send to SMTP relay servers if certain recipients failed during direct send.

When Connect method is called (rather than Send), the Smtp component will attempt to connect to the SMTP relay servers in the same way as described above. However, if all SMTP relay servers failed, no attempt to perform direct send is made (because Connect method does not send any mail messages, it only connects to an SMTP relay server). In other words, when the connection is established via explicit call to Connect method, direct send mode and DnsServers collection are never used.

See Also

Reference

MailBee.SmtpMail Namespace


SmtpServerCollection Constructor

SmtpServerCollection Constructor
Initializes a new instance of the SmtpServerCollection class

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServerCollection()
Public Sub New
See Also

Reference

SmtpServerCollection Class
MailBee.SmtpMail Namespace


SmtpServerCollection Methods

SmtpServerCollection Methods

The SmtpServerCollection type exposes the following members.

Methods
 | Name | Description
Public method | Add(String) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection and sorts the collection according to the elements priorities.
Public method | Add(SmtpServer) | Adds an SmtpServer to the collection and sorts the collection according to the elements priorities.
Public method | Add(String, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given host name (or IP address string), port number and priority value, adds this instance into the collection, and sorts the collection according to the elements priorities.
Public method | Add(String, String, String) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server, and sorts the collection according to the elements priorities.
Public method | Add(String, String, String, AuthenticationMethods) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server using the specified methods, and sorts the collection according to the elements priorities.
Public method | Add(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions) | Initializes a new instance of the SmtpServer class with the given parameter values, adds this instance to the collection, and sorts the collection according to the elements priorities.
Public method | Clear | Removes all objects from the CollectionBase instance. This method cannot be overridden. (Inherited from CollectionBase.)
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetEnumerator | Returns an enumerator that iterates through the CollectionBase instance. (Inherited from CollectionBase.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method | OnClear | Performs additional custom processes when clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnClearComplete | Performs additional custom processes after clearing the contents of the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsert | Performs additional custom processes before inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnInsertComplete | Performs additional custom processes after inserting a new element into the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemove | Performs additional custom processes when removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnRemoveComplete | Performs additional custom processes after removing an element from the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSet | Performs additional custom processes before setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnSetComplete | Performs additional custom processes after setting a value in the CollectionBase instance. (Inherited from CollectionBase.)
Protected method | OnValidate | Performs additional custom processes when validating a value. (Inherited from CollectionBase.)
Public method | Remove | Removes the specified SmtpServer object from the collection.
Public method | RemoveAt | Removes the element at the specified index of the CollectionBase instance. This method is not overridable. (Inherited from CollectionBase.)
Public method | SortByPriority | Sorts the items in the collection by their priority value. (Inherited from SortableByPriorityCollection.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

SmtpServerCollection Class
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method

SmtpServerCollectionAdd Method
Overload List
 | Name | Description
Public method | Add(String) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection and sorts the collection according to the elements priorities.
Public method | Add(SmtpServer) | Adds an SmtpServer to the collection and sorts the collection according to the elements priorities.
Public method | Add(String, Int32, Int32) | Initializes a new instance of the SmtpServer class with the given host name (or IP address string), port number and priority value, adds this instance into the collection, and sorts the collection according to the elements priorities.
Public method | Add(String, String, String) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server, and sorts the collection according to the elements priorities.
Public method | Add(String, String, String, AuthenticationMethods) | Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server using the specified methods, and sorts the collection according to the elements priorities.
Public method | Add(String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions) | Initializes a new instance of the SmtpServer class with the given parameter values, adds this instance to the collection, and sorts the collection according to the elements priorities.
Top
See Also

Reference

SmtpServerCollection Class
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method (String)

SmtpServerCollectionAdd Method (String)
Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection and sorts the collection according to the elements priorities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer Add(
    string serverName
)
Public Function Add (
    serverName As String
) As SmtpServer

Parameters

serverName
Type: SystemString
The host name or IP address string of the SMTP relay server to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).

Return Value

Type: SmtpServer
A reference to SmtpServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | serverName is a null reference (Nothing in Visual Basic).
See Also

Reference

SmtpServerCollection Class
Add Overload
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method (SmtpServer)

SmtpServerCollectionAdd Method (SmtpServer)
Adds an SmtpServer to the collection and sorts the collection according to the elements priorities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Add(
    SmtpServer server
)
Public Sub Add (
    server As SmtpServer
)

Parameters

server
Type: MailBee.SmtpMailSmtpServer
An SmtpServer to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).
Remarks
It's recommended to add elements from higher priority to lower priority. Thus, the elements will stay in the same order as they were added.
See Also

Reference

SmtpServerCollection Class
Add Overload
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method (String, Int32, Int32)

SmtpServerCollectionAdd Method (String, Int32, Int32)
Initializes a new instance of the SmtpServer class with the given host name (or IP address string), port number and priority value, adds this instance into the collection, and sorts the collection according to the elements priorities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer Add(
    string serverName,
    int serverPort,
    int priority
)
Public Function Add (
    serverName As String,
    serverPort As Integer,
    priority As Integer
) As SmtpServer

Parameters

serverName
Type: SystemString
The host name or IP address string of the SMTP relay server to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).
serverPort
Type: SystemInt32
The port on which to communicate with the SMTP relay server. The standard SMTP port is 25.
priority
Type: SystemInt32
A preference of the SMTP relay server. Lower values are preferred.

Return Value

Type: SmtpServer
A reference to SmtpServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | serverName is a null reference (Nothing in Visual Basic) or serverPort is an invalid port number.
Remarks
It's recommended to add elements from higher priority to lower priority. Thus, the elements will stay in the same order as they were added.
See Also

Reference

SmtpServerCollection Class
Add Overload
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method (String, String, String)

SmtpServerCollectionAdd Method (String, String, String)
Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server, and sorts the collection according to the elements priorities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer Add(
    string serverName,
    string accountName,
    string password
)
Public Function Add (
    serverName As String,
    accountName As String,
    password As String
) As SmtpServer

Parameters

serverName
Type: SystemString
The host name or IP address string of the SMTP relay server to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.

Return Value

Type: SmtpServer
A reference to SmtpServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | serverName is a null reference (Nothing in Visual Basic).
Remarks
This method automatically sets AuthMethods property value to Auto.
See Also

Reference

SmtpServerCollection Class
Add Overload
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method (String, String, String, AuthenticationMethods)

SmtpServerCollectionAdd Method (String, String, String, AuthenticationMethods)
Adds a top (0) priority SMTP relay server under the specified host name (or IP address string) to the collection, enables ESMTP authentication for this server using the specified methods, and sorts the collection according to the elements priorities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer Add(
    string serverName,
    string accountName,
    string password,
    AuthenticationMethods authMethods
)
Public Function Add (
    serverName As String,
    accountName As String,
    password As String,
    authMethods As AuthenticationMethods
) As SmtpServer

Parameters

serverName
Type: SystemString
The host name or IP address string of the SMTP relay server to be added to the collection. The value cannot be a null reference (Nothing in Visual Basic).
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when authenticating the user on the server.

Return Value

Type: SmtpServer
A reference to SmtpServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | serverName is a null reference (Nothing in Visual Basic).
See Also

Reference

SmtpServerCollection Class
Add Overload
MailBee.SmtpMail Namespace


SmtpServerCollection.Add Method (String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions)

SmtpServerCollectionAdd Method (String, Int32, Int32, Int32, Boolean, AuthenticationMethods, String, String, Boolean, String, ExtendedSmtpOptions)
Initializes a new instance of the SmtpServer class with the given parameter values, adds this instance to the collection, and sorts the collection according to the elements priorities.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer Add(
    string serverName,
    int serverPort,
    int priority,
    int timeout,
    bool pipelining,
    AuthenticationMethods authMethods,
    string accountName,
    string password,
    bool allowRefusedRecipients,
    string helloDomain,
    ExtendedSmtpOptions smtpOptions
)
Public Function Add (
    serverName As String,
    serverPort As Integer,
    priority As Integer,
    timeout As Integer,
    pipelining As Boolean,
    authMethods As AuthenticationMethods,
    accountName As String,
    password As String,
    allowRefusedRecipients As Boolean,
    helloDomain As String,
    smtpOptions As ExtendedSmtpOptions
) As SmtpServer

Parameters

serverName
Type: SystemString
The host name or IP address of the SMTP relay server.
serverPort
Type: SystemInt32
The port on which to communicate with the SMTP relay server. The standard SMTP port is 25.
priority
Type: SystemInt32
A preference of the SMTP relay server. Lower values are preferred.
timeout
Type: SystemInt32
The amount of time (in milliseconds) the component will wait for data to be received from the server before returning an error, or zero to wait indefinitely.
pipelining
Type: SystemBoolean
Specifies whether to use commands pipelining (ESMTP PIPELINING) if it's supported by the server.
authMethods
Type: MailBeeAuthenticationMethods
A set of authentication methods which can be used when authenticating the user on the server.
accountName
Type: SystemString
The user account name on the server.
password
Type: SystemString
The user account password on the server.
allowRefusedRecipients
Type: SystemBoolean
Specifies whether refused recipients should be allowed when submitting a mail message to the server.
helloDomain
Type: SystemString
The string to be supplied as an argument of HELO/EHLO commands, or a null reference (Nothing in Visual Basic) to let MailBee autodetect the correct value (see Hello for details).
smtpOptions
Type: MailBee.SmtpMailExtendedSmtpOptions
A set of flags which can be used to disable certain extended SMTP capabilities.

Return Value

Type: SmtpServer
A reference to SmtpServer object which was created based on the given parameter values and then added to the collection.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | serverName is a null reference (Nothing in Visual Basic) or serverPort is an invalid port number.
See Also

Reference

SmtpServerCollection Class
Add Overload
MailBee.SmtpMail Namespace


SmtpServerCollection.Remove Method

SmtpServerCollectionRemove Method
Removes the specified SmtpServer object from the collection.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public void Remove(
    SmtpServer server
)
Public Sub Remove (
    server As SmtpServer
)

Parameters

server
Type: MailBee.SmtpMailSmtpServer
A reference to the SmtpServer object to be removed.
See Also

Reference

SmtpServerCollection Class
MailBee.SmtpMail Namespace


SmtpServerCollection Properties

SmtpServerCollection Properties

The SmtpServerCollection type exposes the following members.

Properties
 | Name | Description
Public property | Capacity | Gets or sets the number of elements that the CollectionBase can contain. (Inherited from CollectionBase.)
Public property | Count | Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden. (Inherited from CollectionBase.)
Protected property | InnerList | Gets an ArrayList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Public property | Item | Gets or sets the element at the specified index.
Protected property | List | Gets an IList containing the list of elements in the CollectionBase instance. (Inherited from CollectionBase.)
Top
See Also

Reference

SmtpServerCollection Class
MailBee.SmtpMail Namespace


SmtpServerCollection.Item Property

SmtpServerCollectionItem Property
Gets or sets the element at the specified index.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public SmtpServer this[
    int index
] { get; set; }
Public Default Property Item (
    index As Integer
) As SmtpServer
    Get
    Set

Parameters

index
Type: SystemInt32
The zero-based index of the entry to get or set.

Property Value

Type: SmtpServer
The element at the specified index.
See Also

Reference

SmtpServerCollection Class
MailBee.SmtpMail Namespace


TestSendResult Enumeration

TestSendResult Enumeration
Provides values returned by TestSend(SendFailureThreshold) method as the result of test send operation.

Namespace: MailBee.SmtpMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public enum TestSendResult
Public Enumeration TestSendResult
Members
Member name | Value | Description
OK | 0 | Successful completion.
NoSender | 1 | No sender was specified.
NoRecipients | 2 | No recipients were specified.
BadSender | 3 | Sender e-mail address was refused by the SMTP server.
BadRecipient | 4 | Recipient e-mail was refused by the SMTP server.
NoAcceptedRecipients | 5 | No recipients have been accepted by the SMTP server.
NoCredentials | 6 | ESMTP or POP-before-SMTP authentication failed because no user account name and/or password was provided.
NoSupportedAuth | 7 | No suitable ESMTP authentication method is supported by the SMTP server.
BadAuthMethod | 8 | The requested authentication method is not supported by the SMTP server.
BadCredentials | 9 | ESMTP or POP-before-SMTP authentication failed because invalid user account name and/or password was provided.
NegativeSmtpResponse | 10 | The SMTP server returned negative response.
NegativePop3Response | 11 | The POP3 server returned negative response during POP-before-SMTP authentication.
SmtpResolveHostError | 12 | The SMTP server name could not be resolved into IP address.
SmtpConnectionError | 13 | There was connection error with the SMTP server.
Pop3ResolveHostError | 14 | The POP3 server name could not be resolved into IP address. POP-before-SMTP authentication could not start.
Pop3ConnectionError | 15 | There was connection error with the POP3 server during POP-before-SMTP authentication.
NoDomainInRecipientEmail | 16 | Recipient was specified as jdoe (or jdoe@) rather than jdoe@domain.com, and LocalSmtpMXServerName is set to an empty string.
NoMXRecord | 17 | No MX or A records have been found for a recipient domain. This domain cannot accept mail.
DnsProtocolError | 18 | The DNS server responded with an error on DNS MX lookup query from MailBee.
DnsConnectionError | 19 | There was connection error with the DNS server.
UnknownError | 20 | Other error.
See Also

Reference

MailBee.SmtpMail Namespace


MailBee.Tnef Namespace

MailBee.Tnef Namespace

MailBee.Tnef namespace contains TnefParser class which lets you parse winmail.dat files in MS-TNEF format, and defines exceptions specific to MS-TNEF functionality. Winmail.dat files are usually created by MS Office Outlook and MS Exchange.

Methods which extract data from MS-TNEF attachments of e-mail messages are defined in MailBee.Mime.Attachment class (such as GetAttachmentsFromTnef method).

Classes
 | Class | Description
Public class | MailBeeTnefException | An abstract parent for all exceptions which can be thrown during parsing an MS-TNEF file.
Public class | MailBeeTnefNotFoundException | The exception that is thrown on an attempt to parse a file which is not MS-TNEF.
Public class | MailBeeTnefParsingException | The exception that is thrown when the MS-TNEF parsing error occurs.
 | TnefParser | Provides methods to parse winmail.dat (MS-TNEF) files.


MailBeeTnefException Class

MailBeeTnefException Class
An abstract parent for all exceptions which can be thrown during parsing an MS-TNEF file.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.TnefMailBeeTnefException
MailBee.TnefMailBeeTnefNotFoundException
MailBee.TnefMailBeeTnefParsingException

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public abstract class MailBeeTnefException : MailBeeLocalException
Public MustInherit Class MailBeeTnefException
    Inherits MailBeeLocalException

The MailBeeTnefException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeTnefException | Initializes a new instance of the MailBeeTnefException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Tnef Namespace


MailBeeTnefException Constructor

MailBeeTnefException Constructor
Initializes a new instance of the MailBeeTnefException class

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeTnefException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeTnefException Class
MailBee.Tnef Namespace


MailBeeTnefException Methods

MailBeeTnefException Methods

The MailBeeTnefException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefException Class
MailBee.Tnef Namespace


MailBeeTnefException Properties

MailBeeTnefException Properties

The MailBeeTnefException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefException Class
MailBee.Tnef Namespace


MailBeeTnefException Events

MailBeeTnefException Events

The MailBeeTnefException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefException Class
MailBee.Tnef Namespace


MailBeeTnefNotFoundException Class

MailBeeTnefNotFoundException Class
The exception that is thrown on an attempt to parse a file which is not MS-TNEF.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.TnefMailBeeTnefException
MailBee.TnefMailBeeTnefNotFoundException

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeTnefNotFoundException : MailBeeTnefException
<SerializableAttribute>
Public Class MailBeeTnefNotFoundException
    Inherits MailBeeTnefException

The MailBeeTnefNotFoundException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeTnefNotFoundException | Initializes a new instance of the MailBeeTnefNotFoundException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Tnef Namespace


MailBeeTnefNotFoundException Constructor

MailBeeTnefNotFoundException Constructor
Initializes a new instance of the MailBeeTnefNotFoundException class

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeTnefNotFoundException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeTnefNotFoundException Class
MailBee.Tnef Namespace


MailBeeTnefNotFoundException Methods

MailBeeTnefNotFoundException Methods

The MailBeeTnefNotFoundException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefNotFoundException Class
MailBee.Tnef Namespace


MailBeeTnefNotFoundException Properties

MailBeeTnefNotFoundException Properties

The MailBeeTnefNotFoundException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefNotFoundException Class
MailBee.Tnef Namespace


MailBeeTnefNotFoundException Events

MailBeeTnefNotFoundException Events

The MailBeeTnefNotFoundException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefNotFoundException Class
MailBee.Tnef Namespace


MailBeeTnefParsingException Class

MailBeeTnefParsingException Class
The exception that is thrown when the MS-TNEF parsing error occurs.
Inheritance Hierarchy
SystemObject
SystemException
SystemApplicationException
MailBeeMailBeeException
MailBeeMailBeeLocalException
MailBee.TnefMailBeeTnefException
MailBee.TnefMailBeeTnefParsingException

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
[SerializableAttribute]
public class MailBeeTnefParsingException : MailBeeTnefException
<SerializableAttribute>
Public Class MailBeeTnefParsingException
    Inherits MailBeeTnefException

The MailBeeTnefParsingException type exposes the following members.

Constructors
 | Name | Description
Protected method | MailBeeTnefParsingException | Initializes a new instance of the MailBeeTnefParsingException class
Top
Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBee.Tnef Namespace


MailBeeTnefParsingException Constructor

MailBeeTnefParsingException Constructor
Initializes a new instance of the MailBeeTnefParsingException class

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
protected MailBeeTnefParsingException(
    SerializationInfo info,
    StreamingContext context
)
Protected Sub New (
    info As SerializationInfo,
    context As StreamingContext
)

Parameters

info
Type: System.Runtime.SerializationSerializationInfo
context
Type: System.Runtime.SerializationStreamingContext
See Also

Reference

MailBeeTnefParsingException Class
MailBee.Tnef Namespace


MailBeeTnefParsingException Methods

MailBeeTnefParsingException Methods

The MailBeeTnefParsingException type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public method | GetType | Gets the runtime type of the current instance. (Inherited from Exception.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Creates and returns a string representation of the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefParsingException Class
MailBee.Tnef Namespace


MailBeeTnefParsingException Properties

MailBeeTnefParsingException Properties

The MailBeeTnefParsingException type exposes the following members.

Properties
 | Name | Description
Public property | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public property | ErrorCode | Gets the error code. (Inherited from MailBeeException.)
Public property | HelpLink | Gets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public property | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public property | InnerException | Gets the Exception instance that caused the current exception. (Inherited from Exception.)
Public property | Message | Gets a message that describes the current exception. (Inherited from Exception.)
Public property | Source | Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public property | StackTrace | Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public property | TargetSite | Gets the method that throws the current exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefParsingException Class
MailBee.Tnef Namespace


MailBeeTnefParsingException Events

MailBeeTnefParsingException Events

The MailBeeTnefParsingException type exposes the following members.

Events
 | Name | Description
Protected event | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top
See Also

Reference

MailBeeTnefParsingException Class
MailBee.Tnef Namespace


TnefParser Class

TnefParser Class
Provides methods to parse winmail.dat (MS-TNEF) files.
Inheritance Hierarchy
SystemObject
MailBee.TnefTnefParser

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public class TnefParser
Public Class TnefParser

The TnefParser type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAttachments(Byte, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a TNEF data.
 | GetAttachments(Stream, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a TNEF stream.
 | GetAttachments(String, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a winmail.dat file.
 | GetAttachmentsAsync | async/await version of GetAttachments(String, TnefExtractionOptions).
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
Remarks

Usually, you'll use GetAttachmentsFromTnef methods of Attachment class to extract contents from winmail.dat attachments in e-mail messages. However, in case if you already have winmail.dat file as a separate entity (not part of an e-mail message), you can use the methods of this class.

MailBee.NET TNEF parser can also extract attachments from nested winmail.dat files. Once you call GetAttachments(Stream, TnefExtractionOptions), you can iterate through the returned AttachmentCollection and check each individual Attachment object for IsMessageInside set to true. Then use GetEncapsulatedMessage method to get the contents of the nested winmail.dat, and its Attachments collection to get the attachments (or other properties like BodyHtmlText or BodyPlainText to get text body). This works for any number of nesting levels.

TNEF parser can also extract RTF body as richbody.rtf attachment (if it's present in winmail.dat). This works for nested winmail.dat files as well.

All the methods are static (Shared in Visual Basic), you don't need to create an instance of this class. Setting MailBee.NET license key is not required either.

Examples
This example saves all attachments and RTF bodies in winmail.dat itself and in any e-mails nested in this winmail.dat.
C#
VB
Copy
using System;
using MailBee.Mime;
using MailBee.Tnef;

class Sample
{
    static void RecursivelySaveAllAttachmentsFromTnef(AttachmentCollection attachs)
    {
        foreach (Attachment att in attachs)
        {
            Console.WriteLine(att.Filename);
            if (att.IsMessageInside)
            {
                Console.WriteLine("Nested mail message in winmail.dat");
                MailMessage innerMsg = att.GetEncapsulatedMessage();
                RecursivelySaveAllAttachmentsFromTnef(innerMsg.Attachments);
            }
            else
            {
                // Content-type will be "application/rtf".
                if (att.Filename == "richbody.rtf")
                {
                    Console.WriteLine("Got RTF message body. Content-type: " + att.ContentType);
                }
                att.SaveToFolder(@"C:\Temp", true);
            }
        }
    }

    static void Main(string[] args)
    {
        AttachmentCollection attachs = TnefParser.GetAttachments(@"C:\Temp\winmail.dat",
            TnefExtractionOptions.ExtractAttachments | TnefExtractionOptions.ExtractRtfBody);
        RecursivelySaveAllAttachmentsFromTnef(attachs);
    }
}
Imports MailBee.Mime
Imports MailBee.Tnef

Class Sample
    Private Shared Sub RecursivelySaveAllAttachmentsFromTnef(ByVal attachs As AttachmentCollection)
        For Each att As Attachment In attachs
            Console.WriteLine(att.Filename)
            If att.IsMessageInside Then
                Console.WriteLine("Nested mail message in winmail.dat")
                Dim innerMsg As MailMessage = att.GetEncapsulatedMessage()
                RecursivelySaveAllAttachmentsFromTnef(innerMsg.Attachments)
            Else
                ' Content-type will be "application/rtf".
                If att.Filename = "richbody.rtf" Then
                    Console.WriteLine("Got RTF message body. Content-type: " & att.ContentType)
                End If
                att.SaveToFolder("C:\Temp", True)
            End If
        Next
    End Sub

    Shared Sub Main(ByVal args As String())
        Dim attachs As AttachmentCollection = TnefParser.GetAttachments("C:\Temp\winmail.dat", _
         TnefExtractionOptions.ExtractAttachments Or TnefExtractionOptions.ExtractRtfBody)
        RecursivelySaveAllAttachmentsFromTnef(attachs)
    End Sub
End Class
See Also

Reference

MailBee.Tnef Namespace


TnefParser Methods

TnefParser Methods

The TnefParser type exposes the following members.

Methods
 | Name | Description
Public method | Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 | GetAttachments(Byte, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a TNEF data.
 | GetAttachments(Stream, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a TNEF stream.
 | GetAttachments(String, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a winmail.dat file.
 | GetAttachmentsAsync | async/await version of GetAttachments(String, TnefExtractionOptions).
Public method | GetHashCode | Serves as the default hash function. (Inherited from Object.)
Public method | GetType | Gets the Type of the current instance. (Inherited from Object.)
Protected method | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.)
Public method | ToString | Returns a string that represents the current object. (Inherited from Object.)
Top
See Also

Reference

TnefParser Class
MailBee.Tnef Namespace


TnefParser.GetAttachments Method

TnefParserGetAttachments Method
Overload List
Name | Description
GetAttachments(Byte, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a TNEF data.
GetAttachments(Stream, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a TNEF stream.
GetAttachments(String, TnefExtractionOptions) | Extracts attachments and, optionally, rich-text body from a winmail.dat file.
Top
See Also

Reference

TnefParser Class
MailBee.Tnef Namespace


TnefParser.GetAttachments Method (Byte[], TnefExtractionOptions)

TnefParserGetAttachments Method (Byte, TnefExtractionOptions)
Extracts attachments and, optionally, rich-text body from a TNEF data.

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static AttachmentCollection GetAttachments(
    byte[] data,
    TnefExtractionOptions options
)
Public Shared Function GetAttachments (
    data As Byte(),
    options As TnefExtractionOptions
) As AttachmentCollection

Parameters

data
Type: SystemByte
The byte array containing TNEF data.
options
Type: MailBee.MimeTnefExtractionOptions
Specifies which kinds of items (attachments and/or RTF message body) to extract from TNEF.

Return Value

Type: AttachmentCollection
An AttachmentCollection object representing the collection of the requested items extracted from TNEF.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | data is a null reference (Nothing in Visual Basic).
MailBeeTnefException | A TNEF parsing error occurred.
Remarks

In case if you got an e-mail with a TNEF attachment, it's easier to use GetAttachmentsFromTnef method to extract data from it.

This overload internally handles the situation when the source data ends with excessive CRLF at the end. You don't need to do anything to handle this situation.

See Also

Reference

TnefParser Class
GetAttachments Overload
MailBee.Tnef Namespace
AttachmentGetAttachmentsFromTnef


TnefParser.GetAttachments Method (Stream, TnefExtractionOptions)

TnefParserGetAttachments Method (Stream, TnefExtractionOptions)
Extracts attachments and, optionally, rich-text body from a TNEF stream.

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static AttachmentCollection GetAttachments(
    Stream data,
    TnefExtractionOptions options
)
Public Shared Function GetAttachments (
    data As Stream,
    options As TnefExtractionOptions
) As AttachmentCollection

Parameters

data
Type: System.IOStream
The stream containing TNEF data.
options
Type: MailBee.MimeTnefExtractionOptions
Specifies which kinds of items (attachments and/or RTF message body) to extract from TNEF.

Return Value

Type: AttachmentCollection
An AttachmentCollection object representing the collection of the requested items extracted from TNEF.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | data is a null reference (Nothing in Visual Basic).
MailBeeException | A stream reading or TNEF parsing error occurred.
Remarks

In case if you got an e-mail with a TNEF attachment, it's easier to use GetAttachmentsFromTnef method to extract data from it.

Note Note
For this overload, it's important to make sure the source stream does not end with CRLF (sometimes, winmail.dat files have this excessive CRLF). For instance, with most stream classes you can use SetLength(Int64) method to decrease the stream length by two in case if it ends with CRLF. Or, simply use GetAttachments(byte[], TnefExtractionOptions) overload which internally does that.
See Also

Reference

TnefParser Class
GetAttachments Overload
MailBee.Tnef Namespace
AttachmentGetAttachmentsFromTnef


TnefParser.GetAttachments Method (String, TnefExtractionOptions)

TnefParserGetAttachments Method (String, TnefExtractionOptions)
Extracts attachments and, optionally, rich-text body from a winmail.dat file.

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static AttachmentCollection GetAttachments(
    string filename,
    TnefExtractionOptions options
)
Public Shared Function GetAttachments (
    filename As String,
    options As TnefExtractionOptions
) As AttachmentCollection

Parameters

filename
Type: SystemString
The path to the file containing TNEF data.
options
Type: MailBee.MimeTnefExtractionOptions
Specifies which kinds of items (attachments and/or RTF message body) to extract from TNEF.

Return Value

Type: AttachmentCollection
An AttachmentCollection object representing the collection of the requested items extracted from TNEF.
Exceptions
Exception | Condition
MailBeeInvalidArgumentException | filename is a null reference (Nothing in Visual Basic) or an empty string.
MailBeeIOException | A file reading error occurred.
MailBeeTnefException | A TNEF parsing error occurred.
Remarks

In case if you got an e-mail with a TNEF attachment, it's easier to use GetAttachmentsFromTnef method to extract data from it.

This overload internally handles the situation when the source file contents ends with excessive CRLF at the end. You don't need to do anything to handle this situation.

See Also

Reference

TnefParser Class
GetAttachments Overload
MailBee.Tnef Namespace
AttachmentGetAttachmentsFromTnef


TnefParser.GetAttachmentsAsync Method

TnefParserGetAttachmentsAsync Method
async/await version of GetAttachments(String, TnefExtractionOptions).

Namespace: MailBee.Tnef
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.0.0 build 615 for .NET 4.5
Syntax
C#
VB
Copy
public static Task<AttachmentCollection> GetAttachmentsAsync(
    string filename,
    TnefExtractionOptions options
)
Public Shared Function GetAttachmentsAsync (
    filename As String,
    options As TnefExtractionOptions
) As Task(Of AttachmentCollection)

Parameters

filename
Type: SystemString
The path to the file containing TNEF data.
options
Type: MailBee.MimeTnefExtractionOptions
Specifies which kinds of items (attachments and/or RTF message body) to extract from TNEF.

Return Value

Type: Task AttachmentCollection
A task that represents the asynchronous operation. The value of TResult parameter is an AttachmentCollection object representing the collection of the requested items extracted from TNEF.
Exceptions
Exception | Condition
MailBeeIOException | A file reading error occurred.
MailBeeTnefException | A TNEF parsing error occurred.
See Also

Reference

TnefParser Class
MailBee.Tnef Namespace