Send from ASP.NET web application

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:

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

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

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