Sending Email with Advanced Features in Visual Basic.NET | Part 1 – Adding Multiple Attachments

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

 


 

This is Part 1 of ‘Sending Email with Advanced Features’ which will show how you can send an email message and add not just one attachment, but pretty much as many attachments as you want. If you haven’t already, I recommend you check out this article I made on the basics of setting up and sending email using the System.NET.Mail SMTP feature in the DotNET Framework. The code i’m using is compatible with Visual Basic .NET 2005, VB 2008, and VB.NET 2010 since i’m using the classes under the System.NET.Mail namespace which is made available in the .NET 2.0, .NET 3.0, .NET 3.5, and the .NET 4.0 Frameworks. I am using SMTP and a Google GMail account to send the email message.

 

First of all to get started you will want a instance of a few classes. Below are the ones you’ll need to setup…

 

  • System.Net.Mail.SmtpClient
  • System.Net.Mail.MailMessage
  • System.Net.Mail.Attachment

 

Below are the variables I am using for the classes above…

 


    'The Simple Mail Tranfer Protocol client with the Host and Port number to use. You will
    'want to change these settings to what you need to use. The host, smtp.gmail.com and port
    'will work if you have a gmail account.
    Dim smtp As New System.Net.Mail.SmtpClient("smtp.gmail.com", 587)

    'This will contain the actual message data to send.
    Dim eMailmessage As New System.Net.Mail.MailMessage

    'Will contain the attachment info to send with the message.
    Dim attachToMsg As System.Net.Mail.Attachment

 

Now that the main dimension code is done its time to setup your mail message.

 

        'Use Secure Socket Layer to Encrypt the connection for sending the mail. This needs
        'be set to "True".
        smtp.EnableSsl = True

        'Setup the gmail host.
        smtp.Credentials = New System.Net.NetworkCredential("gmailLoginName@gmail.com", "gmailLoginPassword")

 

You can now set the email’s Body/Text, Subject, From/Sender, and Recipient.


            eMailmessage.Subject = "Check out my attachments!"

            eMailmessage.Body = "I hope you got all of my attachments in this email!"

            eMailmessage.From = New Mail.MailAddress("you@hotmail.com, "Jason")

            eMailmessage.To.Add("ToPerson@yahoo.com)

 

Now before you send your email to the recipient, its time to setup and add more than a single attachment to your message. As you will see adding more than 1 attachment to your message is easy. I am using a OpeFileDialog to open a dialog window to select multiple files. Once the Dialog’s Open button is clicked then I will add all of the Filenames that was selected in the Open Dialog object.

 


        'Create a openDialog object to be able to select a attachment to the mail message.
        Dim openDLG As New OpenFileDialog

        'openDLG.AddExtension = True
        openDLG.ReadOnlyChecked = True
        openDLG.Multiselect = True
        openDLG.Title = "Select the file(s) you want added to the message..."
        openDLG.Filter = "All Files (*.*)|*.*"

        If openDLG.ShowDialog = Windows.Forms.DialogResult.OK Then

            For Each item As String In openDLG.FileNames

                'Create a new System.NET.Mail.Attachment class instance for each file.
                attachToMsg = New System.Net.Mail.Attachment(item)

                'Then add the attachment to your message. You have to do this everytime you run the code
                'above.
                eMailmessage.Attachments.Add(attachToMsg)

            Next

            Msgbox "I have finished adding all of the selected files! You can do more if you want!"

        End If

 

As you can see, adding multiple attachments to an email is very simple. Now all thats left to do is send your message to your recipient(s).

 


            'When you are done with setting up your email and add your attachments then you just need
            'to send your message.
            smtp.Send(eMailmessage)

 

Thats all there is to it! Do remember though that attachment sizes can add up very quickly. Before fully sending your email, it has to upload every file you attached to the message. So just remember that it could take awhile before its sent to the smtp server for processing. I advise you to use the smtp.SendAsync method to send your email since it will execute the resources for sending the email on a new thread seperate from your applications thread. Otherwise you will have to wait for the mail process to complete before you can continue using your application. I plan on adding a couple more parts in the near future. I plan on showing how to use a class I found that will easly convert rtf code to html code that allows you to use a richtextbox for the body of the email message and make it so the email will look very similar to how it looked and was formatted in the richtextbox control. I also plan on showing how to send an email with Alternative Views so that way you can send your email with different formats like Plain Text and Html and so on which allows the mail reader to pick which view would be best. Anyways, Have Fun!

Jason

How to Play Embedded Resource Wav Sound in VB.NET 2005, VB 2008, and Visual Basic 2010

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

 


 
I’ve recenty been making an example program with Visual Basic.NET 2008 on snapping forms to the edge of the screen. I wanted the program to play a sound wave file when it performed the snapping process. But I didn’t want to have to make it link to external wave files or anything. So I decided to embed the wave sound bytes(bites?) in the program itself. So this little article will show you how I went about doing that. Here is a link to the actual example application that this article is based on.
 
More Info

The first thing you want to do of course is determine the wave files you want to play in your application. Remember that the size of each .wav file in bytes, willl be added to your programs file size. So remember that when you decide on what sound files you want to use.

I also want to mention that this article is specific to VB .NET 2005 and higher since I am using the SoundPlayer class. That class was not added until VB 2005. Visual Basic .NET 2002 and VB.NET 2003 will have to use the PlaySound api thats part of the WinMM.dll library. The PlaySound api can play and do everything the SoundPlayer class in VB 2005 and higher can do. Just more code is involved. I actually found an article after I started this post that shows how to play wave files embedded in your VB.NET 02/03 application. Just click here to check it out.
 
Embedding your .Wave Files

After you have determined the wave files you want to embed in your program you need to add them to your project. There are a couple ways to do this. The easiest way is to copy your .wav file and then paste it in your project. To paste it to your project you just need to select your project name in the Solution Explorer, usually the top right panel. Then right click and click on the paste command. Another way is to click on the “Project” and click on “Add Existing Item”. Then just browse to the wave files location and select each file you want to embed. Once the files are added to your project, you will want to click on each wave file and in the properties panel (Its right below the Solution Explorer by Default). In the Properties panel you will see “Build Action”. From the build action combo list select “Embedded Resource”. Do that for each sound file you added to your project.
 

 
Playing your Embedded Files

Now that you have embedded your files into your application, its time to setup the code to play them. If your using .NET older than 2005 then check out this article on using the unManaged api call “PlaySound” to do the playback.

You now need to access your newly embedded *.wav file. You can access it as a stream under your programs manifest. Here is the method that will be used…
 
Public Overridable Function GetManifestResourceStream(ByVal name As String) As System.IO.Stream
 
You access the resource manifest through the: Reflection.Assembly.GetExecutingAssembly namespace. You have to provide the name of your programs assembly and the name of your wave file. The name of my example project is: ‘playEmbeddedWaveFileEx’ and the name of my .wav file is: ‘waveFile.wav’. Remember that your assembly and wav file IS CASE Sensitive. In other words, each letter has to be the exact upper casing and lower casing that your actual assembly and wave file is. So for my example, you would pass the assembly and wave file as: ‘playEmbeddedWaveFileEx.waveFile.wav’. Notice the . or period seperating the assembly name and the name of the wave file. An easy way of getting your assembly name is using this Property: My.Application.Info.AssemblyName. First is the code for literally specifying the name of your assembly. So you pass it to the GetManifestResourceStream’s parameter like below…
 
Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(“playEmbeddedWaveFileEx.waveFile.wav”)
 
BUT a better way…
 
Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(My.Application.Info.AssemblyName & “.waveFile.wav”)
 
 


 

Now all you have to do is create a new SoundPlayer or access the Soundplayer under the ‘MY’ interface and pass the stream and simply start playing the wavefile like below…
 

        '
        'This creates a new instance of the SoundPlayer class while passing the stream the wave file
        'is embedded in.
        '
        Dim audioPlayer As New Media.SoundPlayer(Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream( _
            My.Application.Info.AssemblyName & ".waveFile.wav")) ' "playEmbeddedWaveFileEx.waveFile.wav"))

        audioPlayer.Play()

 
OR you can use the MY Interface…
 

        '
        'This code uses MY, which basically makes it a touch easier since you want have to create
        'a instance of the SoundPlayer class.
        '
        My.Computer.Audio.Play((Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream( _
            My.Application.Info.AssemblyName & ".waveFile.wav")), AudioPlayMode.Background)

 
___________________
 
Remember that I have a example program on how to perform the steps in this article. Click here to download.

OK, so playing embedded wave files isn’t as straight forward perhaps as it should be. I think I found out about using the GetManifestResourceStream at vbforums.com. If you know of something better definitely leave a comment. Either way, the code I provided here DOES work. At least for me. :) Have fun!

Jason

Performing Various Listview Control Tasks in VB.NET | Part 2 – Sorting and Shuffling/Randomize Items

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

 


 
The listview control has been available to VBers since the classic days. VB.NET continues with its version of the listview control as well. The control can provide VERY user-friendly features to your program. You can add Groups, Columns, and more with various display preferences like Icons and Details. The purpose of this post is simply to give you some basic code that i’ve had to use over time for the Listview Control.

Note: These codes should have no problems working with VB 2005, Visual Basic.NET 2008, and Visual Basic 2010. For this article I am calling my Listview control’s name: Listview1. So all of the code will be using that name when referring to the listview object. I also set the controls ‘View’ property to: “Details” and added 2 columns.

 

Sorting Items…

I have a few tasks to show related to item based sorting. I will show how to Sort the Listviews item contents by Name, using Ascending and Descending styles. I want to show how to shuffle or randomize (or is it randomise?)  the items in a listview control. I will also show how to allow the user to click on one of the listviews columns to sort items both Asending and Desending,

Sorting Items - Ascending

            Listview1.Sorting = SortOrder.Ascending

Sorting Items – Descending

            Listview1.Sorting = SortOrder.Descending

Sorting Items – None (No Sorting at All)

            Listview1.Sorting = SortOrder.None

 

Shuffling, or Randomizing Items…

I will now provide source code to randomly sort all of the items in the listview control. I may see about a better solution to this but this code does work perfectly fine.

        '
        'This will go through the list contents and reorder the items randomly.
        '
        Dim r As New Random
        Dim item As ListViewItem
        Dim index As Integer
        '
        'You first need to set sorting to None.
        Listview1.Sorting = SortOrder.None
        '
        'Now go through the contents of the list.
        For i As Integer = 0 To Listview1.Items.Count - 1
            '
            'Get a randon number to use as the index to insert the item again.
            index = r.Next(i, Listview1.Items.Count)
            '
            'Set to each item in the list.
            item = Listview1.Items.Item(i)
            '
            'First remove that item.
            Listview1.Items.Remove(item)
            '
            'Then insert that item using the new random index number.
            Listview1.Items.Insert(index, item)

        Next

Sorting Items with a Column Click…

OK, this last bit of code will sort the items when a user clicks on the column. You just need to make minor changes to the code below, depending on which column in the Index you want to activate the sorting process. The code Has to go in the Listview controls _ColumnClicked event.

    Private Sub Listview1_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles Listview1.ColumnClick
        '
        'These codes will check which sorting style is enabled and will either set to Ascending or Descending.
        'e.Column is the Index of the column that was clicked. I check for the first Column only which is 0 (Zero).
        '
        If e.Column = 0 AndAlso Listview1.Sorting = SortOrder.Descending OrElse Listview1.Sorting = SortOrder.None Then

            Listview1.Sorting = SortOrder.Ascending

        ElseIf e.Column = 0 AndAlso Listview1.Sorting = SortOrder.Ascending Then

            Listview1.Sorting = SortOrder.None

        End If

    End Sub

_______________________________________

You see that it really is easy to do all of these tasks. I don’t exactly like the code I made on shuffling/randomizing the items so if I come up with something better I will update this article. I haven’t decided yet on what to do for the next Listview Control article. Hopefully it will prove to be useful… Feel Free to leave a comment if you have something in mind.  Have fun!

 

Jason

Performing Various Listview Control Tasks in VB.NET | Part 1 – Removing Items

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...


The listview control has been available to VBers since the classic days. VB.NET  continues with its version of the listview control as well. The control can provide VERY user-friendly features to your program. You can add Groups, Columns, and more with various display preferences like Icons and Details. The purpose of this post is simply to give you some basic code that i've had to use over time for removing items from the Listview Control.

Note: These codes should have no problems working with VB 2005, Visual Basic.NET 2008, and Visual Basic 2010. For this article I am calling my Listview control's name: Listview1. So all of the code will be using that name when referring to the listview object. I also set the controls 'View' property to: "Details" and added 2 columns.

   

Removing Items...

I have three tasks related to item removal. Removing All, Remove Checkmarked, and Remove the Selected items. Once you have a basic understanding of the component these task are quite easy. It actually takes very little code..

 

Remove - All Items

        Listview1.Items.Clear()

   

 

Remove - Checkmarked Items Only

        For item As Integer = 0 To Listview1.CheckedItems.Count - 1

            Listview1.CheckedItems(0).Remove()

        Next

OR

        Do While Listview1.CheckedItems.Count > 0

            Listview1.CheckedItems(0).Remove()

        Loop

    

 

Remove - Selected Items Only

        For item As Integer = 0 To Listview1.SelectedItems.Count - 1

            Listview1.SelectedItems(0).Remove()

        Next

OR

        Do While Listview1.SelectedItems.Count > 0

            Listview1.SelectedItems(0).Remove()

        Loop

 

_______________________________________

 

Thats all there is to it! If I come up with more ways or come across any other codes related to removing items then I will update this post. In the next article I plan on showing how to Sort items in the Listview control and Shuffle, or Randomize the contents/items of the Listview control. Have fun!

Jason


      	

Getting the Computers Windows Directory using VB and Visual Basic.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

This little article will show you how to get the Windows directory/folder using both classic vb and vb.net. For some reason Microsoft didn’t add built-in support for getting the path of the users windows directory until .NET 4.0. It is located under the: Environment.SpecialFolders feature. Otherwise I will show a way to get the windows path in the earlier versions of VB.NET and a way to get the directory path using VB 6.0 and Visual Basic.NET.

 

Works for Both VB 5.0/VB6.0 and Visual BasicNET

This is a simple API call that will give you the windows installed directory for the computer. You just need to create a string buffer and the api function will set the information you want in that buffer.

 

_______________

'Visual Basic 5.0, 6.0 Declare

  Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long

 

'Visual Basic.NET Declare

 Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Int32) As Int32

 

 

‘Remaining code for API Method for All VB’s below…
  
'For both VB and VB.NET. This variable is for receiving the path from the API call.

    Dim winDir As String

 'Create a simple string buffer that will be passed to the api call to receive the directory for windows.

     winDir = Space$(255)

  'The winDir variable will get the value from the api call.

      GetWindowsDirectory winDir, Len(winDir)

'Trim the end of the value to remove the unused whitespaces from the string buffer.

      winDir = RTrim(winDir)

'This should throw a message box displaying the windows directory for the target computer.

    MsgBox(winDir)

_____________

When executing the code above, you should get a messagebox with the target computers Windows directory. It could be something similar to: “C:Windows”

 

.NET based VB’s only below

Like I mentioned earlier Microsoft failed to include the Windows Directory as a Special Folder until .NET 4.0. But there is a another easy way to do it if you don’t want to use the API method.

This first way will actually use the Special Folder feature in .NET but will target the Environment.SystemDirectory. Since the System32 directory is always located under the base windows folder all you have to do is get the parent path of the SystemDirectory.

….

 MsgBox(My.Computer.FileSystem.GetParentPath(Environment.SystemDirectory))

….

The code above will throw a message with the parent path for the System32 directory. In my case is returned ‘c:Windows’ just like the API version did.

_____________

There are other ways to get the windows direcory like checking a environment variable that I might add later on. The API version works great for both VB 6.0 and VB.NET, and the System32 method works just fine for .NET.  Remember Microsoft included the WindowsDirectory as a SpecialFolder in Visual Basic 2010 so you should use that method if possible. Anyways, thats all!

         Jason

Hide/Show the Cursor’s Caret using VB and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

 

There may be times when you don’t want your textbox or combobox to show the cursor’s caret position (blinking cursor). Thanks to a couple API calls, its easy to both hide and show the caret from the user. Microsoft made available the HideCaret and ShowCaret api functions.  

I want to explain alittle more how the functions operate. Whenever you want to hide the caret using the HideCaret api call, say on one of your textbox controls, the target textbox needs to have ownership of the caret at the time the Hide Caret function is executed. Whenever the textbox loses ownership of the caret it will be reset back to the default setting. For example you call the HideCaret function which successfully hides the blinking cursor in the target textbox control. You then click on a button or another control that gets focus/ownership of the caret, then the caret/blinking cursor will be shown again in the target textbox when the user clicks or gives focus to the target textbox again. In other words, whenever ownership of the caret changes from one control to another then the Caret will reset back to its default setting. So, if you want the caret to always remain hidden from the user in your textbox, then you can do a simple trick to keep the blinking cursor from being shown even when it changes ownership.  

First of all, you need to get the code for the two API calls…  

 
 
________________________

VB.NET

Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Int32) As Int32

Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Int32) As Int32

VB 6.0

Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Long) As Long

Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Long) As Long

________________________

 
 
 These functions are easy to use. All you have to do is call the HideCaret function with the handle of the control whose caret you want to hide or show in the wHandle parameter like below…
 
 
________________________

VB.NET… 

    HideCaret(TextBox1.Handle.ToInt32)

    ShowCaret(TextBox1.Handle.ToInt32)
VB 6.0… 
    HideCaret Text1.hWnd

    ShowCaret Text1.hWnd
________________________
 
 
The codes above are set to Hide/Show the caret in a textbox control. If you want the cursor to never be shown in a textbox control, then simply put the HideCaret code in the Textbox_GotFocus() event. Like below… 
 
________________________
 
 
VB.NET 
 
Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus

HideCaret(TextBox1.Handle.ToInt32)

End Sub
 
VB 6.0 
Private Sub Text1_GotFocus()

    HideCaret(Text1.hWnd) 

End Sub

________________________

 

 

 With the code above, now each time the textbox control gets focus and ownership of the caret it will automatically call the HideCaret function. Thus the user should never see the blinking cursor at all. Thats all for this tip I guess. :) 

 

                      Jason

Next Page »