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.4 build 677 for .NET 4.5
public bool Send()

Return Value

Type: Boolean
true if the method succeeds; otherwise, false.
MailBeeExceptionAn error occurred and ThrowExceptions is true.
PlatformNotSupportedExceptionIn .NET Core, multi-threaded sending is supported with async methods only. Use SendAsync instead.

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.

You can improve performance of sending large messages by increasing TcpBufSize value.

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.

Note Note
See OAuth2 topic on how to use the modern OAuth 2.0 authentication (e.g. with Gmail and Office 365).

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.

// 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("", "jdoe", "secret");

// Set sender.
mailer.From.DisplayName = "John Doe";
mailer.From.Email = "";

// Demonstrate various methods to specify recipients.
mailer.To.AsString = ", \"Bill Smith, Jr.\" <>";
mailer.To.AddFromString("Kathy Smith <>");
mailer.To.Add("Mike Jackson, Sales Manager", "", "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;


Console.WriteLine("Sent to: " + mailer.GetAcceptedRecipients());

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.
// 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";

// 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 "" instead of "jdoe".
mailer.SmtpServers.Add("", "jdoe", "secret");

// Get the list of DNS servers from OS settings or the config file.

// Set sender.
mailer.From.DisplayName = "John Doe";
mailer.From.Email = "";

// Set To and CC recipients.
mailer.To.Add("Sales Department", "");
mailer.Cc.Add("Conversation archive", "");

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

// Print the outcome.
Console.WriteLine("Successfully sent to: " + mailer.GetAcceptedRecipients().ToString());
Console.WriteLine("Not sent to: " + mailer.GetRefusedRecipients().ToString());

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:

1jdoe@hisdomain.comJohn Doeorder_234.doc
2k.smith@herdomain.comKaty Smithorder_345.doc
It's assumed "C:\Docs" folder contains the following files: order_234.doc, order_345.doc, order_555.doc.

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;

        // Add primary server (SMTP AUTH is not used).
        // Default priority is 0 (top priority).

        // 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("", "jdoe", "secret");
        backupServer.Priority = 1;

        // 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"" <>";

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

John Doe, Sales Manager";

        // Set attachment pattern (assume all documents reside in C:\Docs folder).

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

        // Connect to the SMTP server.
        for (int i = 0; i < table.Rows.Count; i++)
                // 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!

                // Report the result.
                Console.WriteLine("The message has been set to " +
            catch (MailBeeException e)
                if (e is IMailBeeSmtpSendException)
                    Console.WriteLine("Message has not been sent to " +
                        table.Rows[i]["Email"].ToString() + ", error is: " + e.Message);
                // Clear merged message and prepare for the next mail merge iteration.

        // Finish.
See Also