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

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
 

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 that’s 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)

That’s 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 separate 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 easily 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.

Have Fun!

         Jason

Revised: 2015

5 thoughts on “Sending SMTP Email with Advanced Features in Visual Basic.NET | Part 1 – Adding Multiple Attachments

  1. Thiago

    Good work u are doing around here Jason….

    So man I can´t use this with hotmail just with gmail and some others…..
    do u have any idea or can help me in anyway ????

    Since, thanks man
    and sorry about my english…..

    Reply
  2. Jason Post author

    Hi, hotmail should work just fine. I have a example application for a complete, advanced email sending client and hotmail works great in the program.

    Make sure you use the right smtp info.

    Here is how it should be to work with hotmail.

    Dim smtp As New System.Net.Mail.SmtpClient(“smtp.live.com”, 587)

    Then of course your email address and password. It should work perfectly fine. 🙂

    Jason

    Reply
  3. Thiago

    So man thank u for try to help me but, it doesn´t work here…..
    I´m using a function that looks like yours and try to implement yours too..
    and on both cases i got the same error —- > Mailbox unavailable. The server response was: 5.7.3 Requested action aborted; user not authenticated

    take a look at my function and tell me if am i Doing something wrong….

    Private Function enviarEmail(ByVal usuario As String, ByVal senha As String, ByVal smtpNome As String, ByVal emailDestino As String, ByVal tituloMsg As String, ByVal msg As String, Optional ByVal anexo As String = “”) As Boolean

    Dim SmtpServer As New SmtpClient()
    Dim mail As New MailMessage()

    Try

    SmtpServer.Credentials = New Net.NetworkCredential(usuario, senha)
    SmtpServer.Port = 587
    SmtpServer.Host = smtpNome
    mail = New MailMessage()
    mail.From = New MailAddress(usuario)
    mail.To.Add(emailDestino)
    mail.Subject = tituloMsg
    mail.Body = msg
    If anexo “” Then
    mail.Attachments.Add(New Attachment(anexo))
    End If

    SmtpServer.Send(mail)
    enviarEmail = True

    Catch ex As Exception

    enviarEmail = Nothing

    End Try

    Return enviarEmail

    End Function

    Since, thanks for attention man
    []´s

    Reply
  4. Jason Post author

    I don’t see SSL enabled. That is a MUST when using Hotmail. So add the code below Before you send the mail.

    SmtpServer.EnableSsl = True

    That should fix it for you. 🙂

    Jason

    Reply

Leave a Reply