Saturday 31 March 2012

How To : Send Email using SMTPClient in asp.net

Introduction
Now a days most of the web application provide features for sending emails to customers or users for different purpose. In this article I will show you how to sent an email using smtpclient in asp.net.

we need to use System.Net namespace for that.MailMessage class object is used for collects To, CC, Bcc addresses as MailAddressCollection.

Before using mail send function we need to include below code in web.config file.

<system.net>
    <mailSettings>
      <smtp >
        <network host="host name" port="25" userName="userid" password="pwd"/>
      </smtp>
    </mailSettings>
  </system.net>

if you want attachements in email , need to pass arraylist of attachments which is list of set of files objects.

C#.Net 

public bool SendMail(string FromEmailID, string ToEmailID, string CCEmailID, string 
BCCEmailID, string Subject, string Body, Boolean IsBodyHtml, ArrayList _Attachments)
    {
        MailMessage mm;
        SmtpClient smtp;
        try
        {
            mm = new MailMessage(FromEmailID, ToEmailID, Subject, Body);
            mm.IsBodyHtml = IsBodyHtml;
            if (!string.IsNullOrEmpty(CCEmailID)) mm.CC.Add(CCEmailID);
            if (!string.IsNullOrEmpty(BCCEmailID)) mm.Bcc.Add(BCCEmailID);
            if (_Attachments != null)
            {
                for (int i = 0; i < _Attachments.Count; i++)
                {
                    mm.Attachments.Add((Attachment)_Attachments[i]);
                }
            }
            smtp = new SmtpClient();
            smtp.Send(mm);
            return true;
        }
       
        catch
        {
            return false;
        }
    }

VB.Net

Public Function SendMail(FromEmailID As String, ToEmailID As String, CCEmailID As String, _
BCCEmailID As String, Subject As String, Body As String, _
    IsBodyHtml As [Boolean], _Attachments As ArrayList) As Boolean
    Dim mm As MailMessage
    Dim smtp As SmtpClient
    Try
        mm = New MailMessage(FromEmailID, ToEmailID, Subject, Body)
        mm.IsBodyHtml = IsBodyHtml
        If Not String.IsNullOrEmpty(CCEmailID) Then
            mm.CC.Add(CCEmailID)
        End If
        If Not String.IsNullOrEmpty(BCCEmailID) Then
            mm.Bcc.Add(BCCEmailID)
        End If
        If _Attachments IsNot Nothing Then
            For i As Integer = 0 To _Attachments.Count - 1
                mm.Attachments.Add(DirectCast(_Attachments(i), Attachment))
            Next
        End If
        smtp = New SmtpClient()
        smtp.Send(mm)
        Return True

    Catch
        Return False
    End Try
End Function

I hope this article was useful and I thank you for viewing it. keep visiting blog , you can get more stuff.

No comments:

Post a Comment