Email Attachments in .NET

Send Email Walkthrough: for C# and VB NET Students

 

You can add attachments to your emails using Visual Basic or C#. What we need is an Open File Dialogue box that allows a user to select the files to attach. We'll then put the file names in an array. The Net.Mail namespace has an Attachments class that we can use along with our MailMessage object.

To make this work, add a new button to your Send Email tab. Add a textbox, as well. (This will just display the file names that the user selected.) Add an OpenFileDialog to your project by double-clicking its entry in the toolbox (under Dialog). Change the Name property of your OpenFileDialog to oFD1, and set the MultiSelect property to True.

Your form may look something like this:

Windows Form to send emails and add attachments using VB and C# code

Double click your new button to open its code stub. At the top of the coding window, but inside the Class code, set up the following two variables:

VB Net

Dim HasAttachment As Boolean = False
Dim aryAttachments( ) As String

C#

bool hasAttachment = false;
string[] aryAttachments;

The first one is a Boolean flag that we can use to check if the user has added an attachment or not. The second one is the array that will contain all the file names chosen.

In the code for your new button, add the following lines:

VB Net

txtAttach.Text = ""

oFD1.InitialDirectory = "C:\"
oFD1.Title = "Add Attachments"
oFD1.Filter = "PDF Files |*.pdf|Text Files|*.txt|All Files|*.*"
Dim ofdResults As Integer = oFD1.ShowDialog( )

If ofdResults = DialogResult.Cancel Then

HasAttachment = False
Exit Sub

End If

C#

txtAttach.Text = "";

oFD1.InitialDirectory = "C:\\";
oFD1.Title = "Attach Files";
oFD1.Filter = "PDFs|*.pdf|Text Files|*.txt|All Files|*.*";

DialogResult ofdResults = oFD1.ShowDialog();

if (ofdResults == DialogResult.Cancel)
{

hasAttachment = false;
return;

}

The first line just clears our new text box. The other lines are ones you've already met: set some properties for the Open File Dialogue box, display it, and then check if the cancel button was clicked. We're also making sure to set HasAttachment to False.

We now need to get at the files that the user selected, putting each file name into the array. Add the following code:

VB Net

Try

Dim numOfFiles As Integer = oFD1.FileNames.Length
Dim singleF As String
Dim counter As Integer = 0

ReDim aryAttachments( numOfFiles - 1)

For Each singleF In oFD1.FileNames

aryAttachments( counter ) = singleF
txtAttach.Text += singleF & " "
counter = counter + 1

Next

HasAttachment = True

Catch ex As Exception

MessageBox.Show("Error opening files")

End Try

C#

try {

int numOfFiles = oFD1.FileNames.Length;
int counter = 0;

aryAttachments = new string[numOfFiles];

foreach (string singleF in oFD1.FileNames)
{

aryAttachments[counter] = singleF;
txtAttach.Text += singleF + " ";
counter++;

}

hasAttachment = true;

}
catch (Exception ex) {

MessageBox.Show(ex.Message);

}

The first line in the Try … Catch block gets how many files the user selected, while the next two lines set up some variables, a string and an integer.

The fourth line is this in VB Net:

ReDim aryAttachments( numOfFiles - 1 )

What we're doing here is resizing the array. We need to set it to the number of files that the user selected, one position in the array for each file. We're deducting 1 because arrays in VB NET start at zero.

The For … Each loop gets each file name that the user selected, and places it in the variable we've called singleF. The counter variable is used to access each position in the array. We then place a file name at this position:

VB Net

aryAttachments( counter ) = singleF

C#

aryAttachments[counter] = singleF;

Next, we build up the text in the text box, displaying each file name (semicolon on the end for C#):

txtAttach.Text += singleF & " "

The final thing to do in the Try part of the Try … Catch block is to set HasAttachment to True. The code for your attachment button should now look like this in VB Net:

VB Net code to use an Open file dialog box to add attachments to an email

And here's the C# version:

C# code to use an Open file dialog box to add attachments to an email

If someone clicks your Attachment button, HasAttachment will either be True or False. In your Send Email button code, you can test for a True value. If it's True, add the attachments the user selected.

The way we'll add the attachments is to loop round and get each file name from our array. Here's some new code to add. Add it to BtnSend, just after all the message lines.

VB Net

If HasAttachment Then

Dim i As Integer

For i = 0 To aryAttachments.Length - 1

Dim file_attach As New Attachment(aryAttachments(i))
message.Attachments.Add( file_attach )

Next

End If

C#

if (hasAttachment)
{

for (int i = 0; i < aryAttachments.Length; i++)
{

Attachment fileAttach = new Attachment(aryAttachments[i]);
message.Attachments.Add(fileAttach);

}

}

The first line in the loop sets up a New Attachment object. The Attachment class is part of the Net.Mail namespace. In between the brackets of Attachment, you type the name of the file you want to attach, an array in our case.

The second line uses the message object we set up earlier. It has an Attachments property. This in turn has an Add subroutine. In between the round brackets of Add, you again specify the name of the attachment.

The code at the bottom of your BtnSend button should look like this:

VB Net

VB code that adds an attachment and sends the email

C#

C# .NET code that adds an attachment and sends the email

The message object will take care of adding the attachments for you. When you run your programme, you should now be able to send emails with an attachment.

You can also receive emails with Visual Basic .NET and C#, but the process is quite complicated. Even more so than sending emails! You'll see how to do it starting in the next section below.

POP3 Servers >>

Back to the C# NET Contents Page

Back to the VB NET Contents Page