Click here to Skip to main content
15,884,298 members
Articles / Web Development / ASP.NET
Tip/Trick

Send mail using System.Web.Mail namespace

Rate me:
Please Sign up or sign in to vote.
3.29/5 (40 votes)
23 Apr 2013CPOL2 min read 517.2K   5.8K   91   77
This tutorial explains how to send mails with attachments

Introduction

The System.Web.Mail namespace provides the classes for sending email in .NET. This tutorial explains how to send emails with attachments.

Class: MailMessage manages the mail message contents.

Properties
  • Attachment specifies the list of the attachments that are transmitted with the message.
  • Bcc is a list of semicolon delimited email addresses that receive a Blind Carbon Copy of the message.
  • Body contains the message text that has to be sent.
  • BodyEncoding is the encoding type of the email message.
  • BodyFormat defines the content type of the body of the message.
  • Cc is a list of semicolon delimited email addresses that receive a Carbon Copy of the message.
  • From is the email address of the sender.
  • Header specifies the custom headers which are transmitted with the Message.
  • Priority is the priority of the email message.
  • Subject is the subject line of the email message.
  • To is the email address of the recipient.

Class: MailAttachments manages the mail attachment.

Class: SmtpMail sends email to the mail server.

The code

Let us see it step by step:

Create a Visual Basic .NET application and drop the following controls and set the properties accordingly.

ControlProperty
Label TextSMTP Server
TextBox NametxtSMTPServer
Label TextFrom
TextBox NametxtFrom
Label TextFrom Display Name
TextBox NametxtFromDisplayName
Label TextRecipient
TextBox txtTo
Label TextAttachment
ListBox NamelstAttachment
Label TextSubject
TextBox NametxtSubject
Label TextMessage
TextBox NametxtMessage
MultilineTrue
ScrollbarsBoth
Button TextAdd attachment
NameBtnAdd
Button TextRemove attachment
NamebtnRemove
Button TextSend
NamebtnSend
CheckBox TextSend As HTML
NamechkFormat
OpenFileDialog NameOFD
DefaultExt*.*
InitialDirectoryc:\
MultiselectTrue

Now let us see the coding part

Invoke the code window and type the following statement above the class declaration.

VB
Imports System.Web.Mail

Within the Class declaration, in the general section, declare variables required for this project.

VB
' Variable which will send the mail
Dim obj As System.Web.Mail.SmtpMail

'Variable to store the attachments 
Dim Attachment As System.Web.Mail.MailAttachment 

'Variable to create the message to send
Dim Mailmsg As New System.Web.Mail.MailMessage()

Double click on the "Add attachment" button to add the code. Type the following lines:

VB
'Show open dialogue box to select the files to attach

Dim Counter As Integer
OFD.CheckFileExists = True
OFD.Title = "Select file(s) to attach"
OFD.ShowDialog()

For Counter = 0 To UBound(OFD.FileNames)
   lstAttachment.Items.Add(OFD.FileNames(Counter))
Next

Double click on the "Remove attachment" button. Type the following lines:

VB
'Remove the attachments
If lstAttachment.SelectedIndex > -1 Then
    lstAttachment.Items.RemoveAt(lstAttachment.SelectedIndex)
End If

Double click on the "Send" button. Type the following lines:

VB
Dim Counter As Integer

'Validate the data
If txtSMTPServer.Text = "" Then
  MsgBox("Enter the SMTP server info ...!!!", _
           MsgBoxStyle.Information, "Send Email")
  Exit Sub
End If

If txtFrom.Text = "" Then
  MsgBox("Enter the From email address ...!!!", _
           MsgBoxStyle.Information, "Send Email")
  Exit Sub
End If

If txtTo.Text = "" Then
  MsgBox("Enter the Recipient email address ...!!!", _
           MsgBoxStyle.Information, "Send Email")
  Exit Sub
End If

If txtSubject.Text = "" Then
  MsgBox("Enter the Email subject ...!!!", _
           MsgBoxStyle.Information, "Send Email")
  Exit Sub
End If

'Set the properties
'Assign the SMTP server
obj.SmtpServer = txtSMTPServer.Text

'Multiple recepients can be specified using ; as the delimeter
'Address of the recipient
Mailmsg.To = txtTo.Text

'Your From Address
'You can also use a custom header Reply-To for a different replyto address
Mailmsg.From = "\" & txtFromDisplayName.Text & "\ <" & txtFrom.Text & ">"

'Specify the body format
If chkFormat.Checked = True Then
  Mailmsg.BodyFormat = MailFormat.Html 'Send the mail in HTML Format
Else
  Mailmsg.BodyFormat = MailFormat.Text
End If

'If you want you can add a reply to header 
'Mailmsg.Headers.Add("Reply-To", "testmail@mail.com")
'custom headersare added like this
'Mailmsg.Headers.Add("Manoj", "TestHeader")

'Mail Subject
Mailmsg.Subject = txtSubject.Text

'Attach the files one by one
For Counter = 0 To lstAttachment.Items.Count - 1
  Attachment = New MailAttachment(lstAttachment.Items(Counter))
  'Add it to the mail message
  Mailmsg.Attachments.Add(Attachment)
Next

'Mail Body
Mailmsg.Body = txtMessage.Text

'Call the send method to send the mail
obj.Send(Mailmsg)

This application is now ready to run, try it. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I'm ManojRajan, Working as a consultant architect in Tennessee. I have more than 8 years of experience in Microsoft Technologies.

Comments and Discussions

 
GeneralRe: Problems with References Pin
Steveoyoung129-Aug-07 5:29
Steveoyoung129-Aug-07 5:29 
GeneralRe: Problems with References Pin
kostasdiktia229-Aug-07 10:18
kostasdiktia229-Aug-07 10:18 
Questionhow to send a mail to multiply address Pin
stl06-Feb-06 16:33
stl06-Feb-06 16:33 
AnswerRe: how to send a mail to multiply address Pin
ManojRajan6-Feb-06 17:08
ManojRajan6-Feb-06 17:08 
AnswerRe: how to send a mail to multiply address Pin
EnderWiggins8-Jul-08 20:58
EnderWiggins8-Jul-08 20:58 
GeneralOFD not found in toolbox Pin
Shibe15-Jan-06 22:20
Shibe15-Jan-06 22:20 
AnswerRe: OFD not found in toolbox Pin
ManojRajan15-Jan-06 23:01
ManojRajan15-Jan-06 23:01 
QuestionCOULD NOT ACCESS CDO.MESSAGE OBJECT Pin
imdeepakpathak14-Oct-05 1:10
imdeepakpathak14-Oct-05 1:10 
I am writing an application in C# which needs to sent email messages to the customers. In this application the SMTP server can be changed dynamically. In this scenario, in my code, i m providing the username,password,port no(in case of some smtp servers like gmail which uses 465 for smtp). but recieving errors like:-

1. Could not access CDO.Message Object.
2. Exception returned by the target of invocation.

what could be the cause, is there need to configure my Outlook express or something else.


Help me, it's very urgent...

GeneralNo errors, no email Pin
ilyail318-Sep-05 18:32
ilyail318-Sep-05 18:32 
GeneralCDO error Pin
fcyjk,kl;24-Aug-05 23:30
fcyjk,kl;24-Aug-05 23:30 
GeneralAttachments doesnt fit. Help me pls Pin
Anomymos3-Jun-05 2:01
sussAnomymos3-Jun-05 2:01 
Generalhin frnz, i need ur help Pin
Lakhan Pal Garg23-May-05 4:26
Lakhan Pal Garg23-May-05 4:26 
GeneralRe: hin frnz, i need ur help Pin
Shady Aly24-May-05 21:56
Shady Aly24-May-05 21:56 
GeneralSend mail with no SMTP service available Pin
Member 18510323-Apr-05 10:40
Member 18510323-Apr-05 10:40 
GeneralRe: Send mail with no SMTP service available Pin
Member 18510326-Apr-05 12:13
Member 18510326-Apr-05 12:13 
GeneralRe: Send mail with no SMTP service available Pin
12dilip124-Nov-05 20:04
12dilip124-Nov-05 20:04 
GeneralSystem.Web.Mail Error Pin
PankajBanga7-Mar-05 11:39
PankajBanga7-Mar-05 11:39 
GeneralRe: System.Web.Mail Error Pin
Dejital123-Mar-05 5:22
sussDejital123-Mar-05 5:22 
QuestionSMTP Server? Pin
pleet26-Dec-04 16:47
pleet26-Dec-04 16:47 
GeneralThank You Pin
Anonymous31-Aug-04 23:22
Anonymous31-Aug-04 23:22 
Generalerror checking makes it crash. Pin
sameerashrafourkia12-Jul-04 1:20
sameerashrafourkia12-Jul-04 1:20 
Generalget namespace or type mail for the imports system.web.mail Pin
mamoman18-Jun-04 10:53
mamoman18-Jun-04 10:53 
GeneralRe: get namespace or type mail for the imports system.web.mail Pin
mamoman20-Jun-04 8:38
mamoman20-Jun-04 8:38 
GeneralRe: get namespace or type mail for the imports system.web.mail Pin
Anonymous12-Jul-04 10:56
Anonymous12-Jul-04 10:56 
GeneralRe: get namespace or type mail for the imports system.web.mail Pin
Anonymous14-Jul-04 3:24
Anonymous14-Jul-04 3:24 

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.