Asp.Net Send Email code
Particularly for notifications emails are one of the best medium to communicate.Normally the SMTP server will be in seperate location and reachable from application server or web servers. And normally an email account is created with credentials to access the SMTP server securely. We can use MailClient.Credentials object to pass the credentials to sucessfully logon to the SMTP server. Then only the relay will be succesful.
This is a simple code to send email from Web applications using ASP.Net using SMTPClient with User Credentials.
To Pass the Email Address to From, To, CC,BCC
MailAddress object has to be used to pass the email address to specific fields such as From,To,CC,BCC. By this object the multiple email addresses can be added to their respective collections as follows
Message.CC.Add(New System.Net.Mail.MailAddress(Cc))
Asp.net Send Email with Attachment
Adding attachements are very easy as we need to only pass the FilePath to the files we need to attach. Multiple attachments can be added to the Message.Attachments collection
Message.Attachments.Add(New Net.Mail.Attachment(strAttPath))
Asp.net SmtpClient Credentials
To successfully logon to the SMTP server we have to pass the credentials to the MailClient object we defiined earlier. Credentials has to be specified using Net.NetworkCredential(). to the Credentials object of the mail client. The rest are Port and host of the MailClient object.
MailClient.Credentials = New Net.NetworkCredential( _
GetConfig("EmailUserName"), _
GetConfig("EmailPassword"))
SmtpClient Vb .Net Sample
Public Shared Sub SendMail( _
ByVal strFrom
As String,
ByVal strTo
As String,
ByVal strSub
As String, _
ByVal strMsg
As String,
ByVal strCC
As String,
ByVal strBCC
As String, _
ByVal strAttPath
As String)
Try Dim MailClient
As New SmtpClient
Dim Message
As New MailMessage(strFrom, strTo)
If (strCC <> String.Empty) Then
If (strCC.Contains(",")) Then
For Each Cc In strCC.Split(CChar(","))
Message.CC.Add(New System.Net.Mail.MailAddress(Cc))
Next
Else
Message.CC.Add(New System.Net.Mail.MailAddress(strCC))
End If
End If
If (strBCC <> String.Empty) Then
If (strBCC.Contains(",")) Then
For Each Bcc In strBCC.Split(CChar(","))
Message.Bcc.Add(New System.Net.Mail.MailAddress(Bcc))
Next
Else
Message.Bcc.Add(New System.Net.Mail.MailAddress(strBCC))
End If
End If
Message.Subject = strSub
Message.Body = strMsg
If (Not String.IsNullOrEmpty(strAttPath)) Then
Message.Attachments.Add(New Net.Mail.Attachment(strAttPath))
End If
MailClient.Credentials = New Net.NetworkCredential( _
GetConfig("EmailUserName"), _
GetConfig("EmailPassword"))
MailClient.Port = CType(GetConfig("PORT"), Integer)
MailClient.Host = GetConfig("Server")
MailClient.Send(Message)
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
End Try
End Sub
Note:GetConfig is a function we are using for fetching values from configuration settings file