SmtpSend Method |
Namespace: MailBee.SmtpMail
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. |
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 |
---|
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 |
---|
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("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 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());
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 | 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 |
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(); } }