Click here to Skip to main content
15,885,278 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.4K   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

 
GeneralMy vote of 1 Pin
Vasudevan Deepak Kumar23-Apr-13 4:14
Vasudevan Deepak Kumar23-Apr-13 4:14 
GeneralRe: My vote of 1 Pin
ManojRajan17-Jul-13 6:13
ManojRajan17-Jul-13 6:13 
GeneralRe: My vote of 1 Pin
Vasudevan Deepak Kumar22-Jul-13 16:03
Vasudevan Deepak Kumar22-Jul-13 16:03 
GeneralRe: My vote of 1 Pin
ManojRajan22-Jul-13 16:20
ManojRajan22-Jul-13 16:20 
Generalsending email via .net web site code Pin
Parth201227-Feb-11 23:24
Parth201227-Feb-11 23:24 
GeneralPlz help! Not able to fix this error Pin
nimi_201013-Dec-10 17:05
nimi_201013-Dec-10 17:05 
GeneralError of Sending email Pin
Member 75740806-Nov-10 2:50
Member 75740806-Nov-10 2:50 
GeneralUrgent help needed on this article [modified] Pin
Adeyemi27-Jul-09 1:28
Adeyemi27-Jul-09 1:28 
GeneralSending emails without IIS Pin
Rohit Dixit9-Jun-09 21:23
Rohit Dixit9-Jun-09 21:23 
General2 things need to discuss Pin
el3ashe230-May-09 0:41
el3ashe230-May-09 0:41 
QuestionError while running the code Pin
Bhuvan941123-Apr-09 22:44
Bhuvan941123-Apr-09 22:44 
AnswerRe: Error while running the code Pin
el3ashe230-May-09 0:42
el3ashe230-May-09 0:42 
QuestionTwo errors found.. Pin
vinayweb31-Oct-08 2:13
vinayweb31-Oct-08 2:13 
AnswerRe: Two errors found.. Pin
rsmldmv15-Dec-08 11:40
rsmldmv15-Dec-08 11:40 
GeneralPocket Pc mail Pin
serkan312324-Jun-07 22:19
serkan312324-Jun-07 22:19 
Hi,firstly thank you very much for this informations.But I have a another question about pocket pc development.I want to send and receive mail in Pocket Pc,I wrote only send part of program.How can I write recive part because there is no namespaces about receive mail (in vs .net 2005). If you have any comment abou tthis problem pls help...
thank you very much


seko
GeneralImports System.Web.mail is not available in the namespace Pin
SelvanPPK22-Jun-07 23:17
SelvanPPK22-Jun-07 23:17 
GeneralRe: Imports System.Web.mail is not available in the namespace Pin
hevesir29-Jul-07 22:25
hevesir29-Jul-07 22:25 
GeneralThanks! Pin
morry809-May-07 20:16
morry809-May-07 20:16 
Generalhi Pin
hebry18-Mar-07 23:51
hebry18-Mar-07 23:51 
QuestionFormatting text using MailFormat.Html Pin
booboo13alright9-Nov-06 7:16
booboo13alright9-Nov-06 7:16 
Generalif there's a solution for CDO.message problem , reply me:) Pin
shery_bn12-Sep-06 20:12
shery_bn12-Sep-06 20:12 
QuestionPlease help me! Pin
ptchuong2-Sep-06 9:50
ptchuong2-Sep-06 9:50 
Generali want Help... Pin
madhan_genn29-Jul-06 0:58
madhan_genn29-Jul-06 0:58 
QuestionCDO.Message Pin
parigi_anantha25-Jul-06 0:56
parigi_anantha25-Jul-06 0:56 
GeneralNo errors while mailing but, no mails also Pin
ronnienk20-May-06 21:06
ronnienk20-May-06 21:06 

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.