Click here to Skip to main content
15,860,972 members
Articles / Database Development / SQL Server
Article

Sending complex emails in .NET 1.1

Rate me:
Please Sign up or sign in to vote.
4.44/5 (32 votes)
15 Mar 20062 min read 181.2K   1.1K   104   42
This article describes complex issues about sending emails in .NET 1.1 (such as using a SMTP server that requires authentication).

Introduction

System.Web.Mail can be used to send emails from .NET 1.1 applications. Sending simple emails is very easy. It is more complicated when you try to send emails using a SMTP server that requires authentication, or even when you just need to format the From name of the email you want to send.

Background

Here is the most simple piece of code that will send an email using C#:

C#
// build the email message
MailMessage msg = new MailMessage();

msg.From = "from.email@domain.com";
msg.To = "to.email@domain.com";
msg.Subject = "Subject";
msg.Body = "Body";

// send the message
SmtpMail.SmtpServer = "smtp.server.com";
SmtpMail.Send(msg);

Problems and the immediate solution

Things need to get more complicated if instead of displaying the From email address, you want to display a name that the recipient of the email will see. For that, a custom header needs to be added:

C#
string sFromName = "From display name";
string sFromAddress = "from.email@domain.com";
msg.Headers.Add("From", string.Format("{0} <{1}>", 
                sFromName, sFromAddress));

Even more complicated will be to send an email using a SMTP server that requires authentication. For that, the Fields collection of the MailMessage object needs to be used. Here is the sample piece of code that will help you solve your problems:

C#
// set SMTP server name
msg.Fields["http://schemas.microsoft.com" + 
    "/cdo/configuration/smtpserver"] = "smtp.server.com";
// set SMTP server port
msg.Fields["http://schemas.microsoft.com/" + 
    "cdo/configuration/smtpserverport"] = 25;
msg.Fields["http://schemas.microsoft.com/" + 
    "cdo/configuration/sendusing"] = 2;

msg.Fields["http://schemas.microsoft.com/cdo/" + 
    "configuration/smtpauthenticate"] = 1;
// set SMTP username
msg.Fields["http://schemas.microsoft.com/cdo" + 
    "/configuration/sendusername"] = "username";
// set SMTP user password
msg.Fields["http://schemas.microsoft.com/" + 
    "cdo/configuration/sendpassword"] = "password";

The better solution

A better solution for the enhancements described above would be to create a new class that is inherited from MailMessage and has the extra features. Here is the content of the new class:

C#
/// <summary>
/// EnhancedMailMessage is a class that provides
/// more features for email sending in .NET
/// </summary>
public class EnhancedMailMessage : MailMessage
{
    private string fromName;
    private string smtpServerName;
    private string smtpUserName;
    private string smtpUserPassword;
    private int smtpServerPort;
    private bool smtpSSL;

    public EnhancedMailMessage()
    {
        fromName = string.Empty;
        smtpServerName = string.Empty;
        smtpUserName = string.Empty;
        smtpUserPassword = string.Empty;
        smtpServerPort = 25;
        smtpSSL = false;
    }

    /// <summary>
    /// The display name that will appear
    /// in the recipient mail client
    /// </summary>
    public string FromName 
    {
        set 
        {
            fromName = value;
        }
        get 
        {
            return fromName;
        }
    }

    /// <summary>
    /// SMTP server (name or IP address)
    /// </summary>
    public string SMTPServerName 
    {
        set 
        {
            smtpServerName = value;
        }
        get 
        {
            return smtpServerName;
        }
    }

    /// <summary>
    /// Username needed for a SMTP server
    /// that requires authentication
    /// </summary>
    public string SMTPUserName 
    {
        set 
        {
            smtpUserName = value;
        }
        get 
        {
            return smtpUserName;
        }
    }
    
    /// <summary>
    /// Password needed for a SMTP server
    /// that requires authentication
    /// </summary>
    public string SMTPUserPassword 
    {
        set 
        {
            smtpUserPassword = value;
        }
        get 
        {
            return smtpUserPassword;
        }
    }
    
    /// <summary>
    /// SMTP server port (default 25)
    /// </summary>
    public int SMTPServerPort 
    {
        set 
        {
            smtpServerPort = value;
        }
        get 
        {
            return smtpServerPort;
        }
    }
    
    /// <summary>
    /// If SMTP server requires SSL
    /// </summary>
    public bool SMTPSSL
    {
        set 
        {
            smtpSSL = value;
        }
        get 
        {
            return smtpSSL;
        }
    }

    public void Send() 
    {
        if (smtpServerName.Length == 0) 
        {
            throw new Exception("SMTP Server not specified");
        }

        if (fromName.Length > 0) 
        {
            this.Headers.Add("From", 
                 string.Format("{0} <{1}>", 
                 FromName, From));            
        }

        // set SMTP server name
        this.Fields["http://schemas.microsoft.com/" + 
                    "cdo/configuration/smtpserver"] = smtpServerName;
        // set SMTP server port
        this.Fields["http://schemas.microsoft.com/cdo" + 
                    "/configuration/smtpserverport"] = smtpServerPort;
        this.Fields["http://schemas.microsoft.com/" + 
                    "cdo/configuration/sendusing"] = 2;

        if (smtpUserName.Length >0 && smtpUserPassword.Length > 0) 
        {
            this.Fields["http://schemas.microsoft.com/" + 
                        "cdo/configuration/smtpauthenticate"] = 1;
            
            // set SMTP username
            this.Fields["http://schemas.microsoft.com" + 
                 "/cdo/configuration/sendusername"] = smtpUserName;
            // set SMTP user password
            this.Fields["http://schemas.microsoft.com/" + 
                 "cdo/configuration/sendpassword"] = smtpUserPassword;
        }

        // ssl if needed
        if (smtpSSL) 
        {
            this.Fields.Add("http://schemas.microsoft" + 
                 ".com/cdo/configuration/smtpusessl", "true");
        }

        SmtpMail.SmtpServer = smtpServerName;
        SmtpMail.Send(this);
    }

    public static void QuickSend(
        string SMTPServerName, 
        string ToEmail, 
        string FromEmail, 
        string Subject, 
        string Body, 
        MailFormat BodyFormat) 
    {
        EnhancedMailMessage msg = new EnhancedMailMessage();

        msg.From = FromEmail;
        msg.To = ToEmail;
        msg.Subject = Subject;
        msg.Body = Body;
        msg.BodyFormat = BodyFormat;

        msg.SMTPServerName = SMTPServerName;
        msg.Send();
    }
}

As you can see from the code above, you can send emails using SMTP servers that require authentication. Here is a sample usage code:

C#
EnhancedMailMessage msg = new EnhancedMailMessage();

msg.From = "from.email@domain.com";
msg.FromName = "From display name";
msg.To = "to.email@domain.com";
msg.Subject = "Subject";
msg.Body = "Body";

msg.SMTPServerName = "smtp.server.com";
msg.SMTPUserName = "username";
msg.SMTPUserPassword = "password";

msg.Send();

There are SMTP servers that require SSL. One very well known example is Gmail. In order to send emails using the Gmail SMTP server, you need to specify that and also set the correct port. The following example can be used to send emails using the Gmail SMTP:

C#
EnhancedMailMessage msg = new EnhancedMailMessage();

msg.From = "your.address@gmail.com";
msg.FromName = "Your name";
msg.To = "to.email@domain.com";
msg.Subject = "Test email from gmail";
msg.Body = "Gmail is great";

msg.SMTPServerName = "smtp.gmail.com";
msg.SMTPUserName = "your.address@gmail.com";
msg.SMTPUserPassword = "yourpassword";
msg.SMTPServerPort = 465;
msg.SMTPSSL = true;

msg.Send();

Also, you can send emails using just one line of code:

C#
EnhancedMailMessage.QuickSend("smtp.server.com", 
    "to.email@domain.com", 
    "from.email@domain.com",
    "Subject",
    "Body",
    MailFormat.Html);

Conclusion

Complex things can be done using simple .NET Framework classes. I will explain more things about email sending in one of my next articles.

History

  • 27 Feb 2006 - first draft of the article.
  • 28 Feb 2006 - created a wrapper class for all the code, and created properties.
  • 01 Mar 2006 - more comments in the class, performance and coding style improvements.
  • 16 Mar 2006 - added support for SMTP servers that require SSL.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here



Comments and Discussions

 
GeneralRe: Thanks for this ! Pin
FlorentinB8-Mar-06 20:47
FlorentinB8-Mar-06 20:47 
GeneralHelpful in sending internal e-mails Pin
Joel S.8-Mar-06 8:28
Joel S.8-Mar-06 8:28 
QuestionSame Thing in VB .NET ? Pin
MehdiAnis7-Mar-06 4:25
MehdiAnis7-Mar-06 4:25 
AnswerRe: Same Thing in VB .NET ? Pin
FlorentinB7-Mar-06 5:39
FlorentinB7-Mar-06 5:39 
AnswerRe: Same Thing in VB .NET ? Pin
MehdiAnis7-Mar-06 9:51
MehdiAnis7-Mar-06 9:51 
GeneralRe: Same Thing in VB .NET ? Pin
FlorentinB7-Mar-06 10:51
FlorentinB7-Mar-06 10:51 
AnswerRe: Same Thing in VB .NET ? Pin
Anders Dalvander15-Mar-06 22:15
Anders Dalvander15-Mar-06 22:15 
GeneralRe: Same Thing in VB .NET ? Pin
jimpar20-Mar-06 11:19
jimpar20-Mar-06 11:19 
here is what i had to do to the code to get it to work in vb.net

thanx all who helped on this

Public Class EnhancedMailMessage
Inherits System.Web.Mail.MailMessage
Private m_FromName As String
Private m_SMTPServerName As String
Private m_SMTPUserName As String
Private m_SMTPUserPassword As String
Private m_SMTPServerPort As Integer
Private m_SMTPSSL As Boolean

Public Sub New()
m_FromName = String.Empty
m_SMTPServerName = String.Empty
m_SMTPUserName = String.Empty
m_SMTPUserPassword = String.Empty
m_SMTPServerPort = 25
m_SMTPSSL = False
End Sub 'New

'''
''' The display name that will appear in the recipient mail client
'''
Public Property FromName() As String
Get
Return m_FromName
End Get
Set(ByVal Value As String)
m_FromName = Value
End Set
End Property

'''
''' SMTP server (name or IP address)
'''
Public Property SMTPServerName() As String
Get
Return m_SMTPServerName
End Get
Set(ByVal Value As String)
m_SMTPServerName = Value
End Set
End Property

'''
''' Username needed for a SMTP server that requires authentication
'''
Public Property SMTPUserName() As String
Get
Return m_SMTPUserName
End Get
Set(ByVal Value As String)
m_SMTPUserName = Value
End Set
End Property

'''
''' Password needed for a SMTP server that requires authentication
'''
Public Property SMTPUserPassword() As String
Get
Return m_SMTPUserPassword
End Get
Set(ByVal Value As String)
m_SMTPUserPassword = Value
End Set
End Property

'''
''' SMTP server port (default 25)
'''
Public Property SMTPServerPort() As Integer
Get
Return m_SMTPServerPort
End Get
Set(ByVal Value As Integer)
m_SMTPServerPort = Value
End Set
End Property

'''
''' If SMTP server requires SSL
'''
Public Property SMTPSSL() As Boolean
Get
Return m_SMTPSSL
End Get
Set(ByVal Value As Boolean)
m_SMTPSSL = Value
End Set
End Property

Public Sub Send()
If m_SMTPServerName.Length = 0 Then
Throw New Exception("SMTP Server not specified")
End If

If FromName.Length > 0 Then
Me.Headers.Add("From", String.Format("{0} <{1}>", FromName, From))
End If

' set SMTP server name
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", SMTPServerName)
' set SMTP server port
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", SMTPServerPort)
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2)

If SMTPUserName.Length > 0 And SMTPUserPassword.Length > 0 Then
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1)

' set SMTP username
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", SMTPUserName)
' set SMTP user password
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", SMTPUserPassword)
End If

' ssl if needed
If SMTPSSL Then
Me.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "True")
End If
System.Web.Mail.SmtpMail.SmtpServer = SMTPServerName
System.Web.Mail.SmtpMail.Send(Me)

End Sub 'Send

Public Shared Sub QuickSend(ByVal SMTPServerName As String, ByVal ToEmail As String, ByVal FromEmail As String, _
ByVal Subject As String, ByVal Body As String, ByVal BodyFormat As System.Web.Mail.MailFormat)
Dim msg As New EnhancedMailMessage

msg.From = FromEmail
msg.To = ToEmail
msg.Subject = Subject
msg.Body = Body
msg.BodyFormat = BodyFormat

msg.SMTPServerName = SMTPServerName
msg.Send()
End Sub 'QuickSend


End Class
GeneralFunny Pin
soimu28-Feb-06 5:32
soimu28-Feb-06 5:32 
GeneralRe: Funny Pin
FlorentinB28-Feb-06 7:50
FlorentinB28-Feb-06 7:50 
GeneralRe: Funny Pin
soimu28-Feb-06 12:46
soimu28-Feb-06 12:46 
GeneralRe: Funny Pin
FlorentinB28-Feb-06 22:04
FlorentinB28-Feb-06 22:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.