Sending eMail using SMTP in Visual Basic.NET & Visual Basic 2008, VB 2010, and higher

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

This small article is just going to cover the Normal basic features of an email client to send mail messages. This post shows how to Send a email using Visual Basic 2005, VB 2008, VB.NET 2010, and newer.

Edit: I suggest you also check out the other articles i’ve make that expands on this article about sending your email messages with advanced features. Check out this one, and another one will be done shortly.

 Note: I do want to thank the author of an article at The Code Project for which I got the info for using gMail as the smtp host. 🙂


  1. Attachment
  2. To
  3. From
  4. Subject
  5. Body

To send a mail message through .NET 05, VB 08, Visual Basic 2010  you will want to head to the System.Net.Mail Namespace which contains the important Classes for setting up and sending mail messages. The main class to use is the SMTPClient class. Other classes that will be used is MailMessage and Attachment. To get started Three(Objects) needs to be made to…

  1. The SMTPClient Class
  2. The MailMessage Class
  3. And the Attachment Class


The following code will first setup the System.Net.Mail.MailMessage Class.

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


The next class is the SMTPClient…

'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.
Dim smtp As New System.Net.Mail.SmtpClient("", 587)

The code above has created and setup the SMTP Client. Googles gMail actually requires 587 to be the port number from what I understand. You can leave out the Port number if your SMTP doesn’t require a specific port. Also remember if you are not using the GMail to send your messages then you need to change the Host parameter to the Host you are going to use to send your mails. Example: “”


The final Class is the Attachment class…

        'Will contain the attachment info to send with the message.
        Dim attach As System.Net.Mail.Attachment
        'Setup the mail message using 4x Textbox controls that contains the From/To/Subject/Message-Body info.
        'You just  need to set it up the way you want it to be…
        Message = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtMessage.Text)


The code below will check a attachment to make sure the file exists..

        'Need to make sure the attachment exists before adding it to the message.
        If My.Computer.FileSystem.FileExists(txtAttachment.Text) Then Message.Attachments.Add(attach)


Set the Secure Socket Layer to be ‘TRUE’

        'Use Secure Socket Layer to Encrypt the connection for sending the mail.
        'This needs be set to “True” if you plan on using GMail or Hotmail or Yahoo as your host.
        smtp.EnableSsl = True


Then setup your Credentials for your Login info. (Username and Password)

        'Setup your account information for authorization…
        smtp.Credentials = New System.Net.NetworkCredential("", "password")


Now that the Mail setup is completed. The only thing left to do is Send your message.

            'Send the mail message that was setup.
            'Usually it was successful in sending the message if it makes it to here
            'Otherwise it should throw a error message from the Catch exception below.
            'You need to remember that after this point its up to the Host to do the rest.
            MessageBox.Show("Well, the mail message appears to have been asuccess!", _
                "Successful?",MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch exc As Net.Mail.SmtpException

            MessageBox.Show(exc.StatusCode.ToString, " Something Happened?", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

Well all of this code in the article works just fine for me to send messages with attachments. If using VB.NET 02/03 you may have to do some modification. I don’t think .NET 1.0/1.1 has the System.Net.Mail namespace and class. Please leave a comment if you know if/what is different so I can update this article. Hopefully it does for your too 🙂  Take care…


Minor Revision: 2015

69 thoughts on “Sending eMail using SMTP in Visual Basic.NET & Visual Basic 2008, VB 2010, and higher

  1. Arun

    I tried your code. But some thing is wrong.
    For me the error message is “operation timed out”.
    Can you please clear this?

  2. Jason Post author

    Hi, I just tried a example I made on these same codes and it worked fine.

    Make sure your internet is working fine and that you have your NetworkCredential setup properly with your gmail or smtp username and password.

    Maybe the smtp service was down at the time. Maybe try sending again.


  3. mahendra

    hi @jason….
    i tried this code….could u explain me couple of things….first let me tell abt my set..
    i have a network of 10 computer connected thru a server..internet on the server….ok

    1) i want to know how i can setup my SMTP configuration on server….???
    2) is that possible after configr SMTP on my server…the above mention code work..and circulate my mails ???

    Thanks in Advance….

  4. Navaneethan

    I tried this code its good
    But i have one problem if i m attaching two files as a attachment i got the error message as “The given path’s format is not supported.”

  5. Navaneethan

    I got this error while i runninng in my Port “The remote certificate is invalid according to the validation procedure”

  6. Navaneethan

    I got this error while i runninng in my Port “The remote certificate is invalid according to the validation procedure”

    If i used gmail port means it working….

  7. Michael

    I have written a VB program to send email using emails from a database. The programs works fine expcept for one or two problems. The first is that the email goes to some addresses but not all. The email is received at my gmail and my account but not to my yahoo account or for that matter my company account (Haven’t tested hotmail/live account yet). The program is useless if I can’t figure this out and get it working to all emails.

    Secondly, the ideal format to send the emails would be a richtext format. I would like to create the body of the text in something like Wordpad including if possible images then copy and paste into a richtextbox in my app. Using html format is a bit of a nusiance.
    Any thoughts on either problem would be appreciated.

  8. Jason Post author

    Hi Michael, I am not sure on what to tell you about your first problem. Maybe check and see if yahoo is putting your smtp email you sent in the spam folder or maybe blocking it.

    If you create a .rtf file in Word you can use the Richtextbox control to open it and modify if you want. Just save the Word contents to a .rtf file and open the file with the Richtextbox control. I have a example at my: website on how to create a full-blown richtextbox based word application for 02/03 and a example on getting started and doing the basics with the richtextbox control I made with VB 2005.

    I hope I understood what you were wanting. 🙂


  9. Michael

    Hi Jason
    The problem isn’t in creating the rtf file (copying and pasteing works just fine, looks great in the rtfbox) it is in sending the email. It comes up as plain text to the receipient.
    Any thoughts in those regard? As for Yahoo and now hotmail/live nothing shows up in any folder. At least with hotmail/live I get a notification ‘Delivery failed’ but I know it is a valid email address and I have used other account to email to them.

  10. nada

    hi Jasno
    I’ve tried this code and millions of others but none worked … 🙁
    I think the problem is in the smtp host, how can i know what’s the smtp host that needs to be used??
    please help me, i’m not an expert in vb


  11. Bill

    I get the following error – any ideas?

    Mailbox unavailable. The server response was: 5.7.1 Unable to relay for

  12. Oscar

    Hi, Jason,

    I used this code and worked very good sending mails to hotmails account and my company’s account. This code saved me a lot of work thanks for sharing your ideas!

  13. Murt

    How to make it require username and password. I have all that code, but i can send e-mails without any usernames or passwords.

  14. Murt

    Is there a way that it requires e-mail account username and password ? – Cuz those credentials aint making any difference for me. I can send emails leaving username and password empty.

  15. snab

    Thanks Dude.. it works fine except d attachment part . You can modify the attachment with the code:

    If My.Computer.FileSystem.FileExists(txtAttach.Text) Then
    Dim attachFile As New Attachment(txtAttach.Text)
    MessageBox.Show(“File doesnt Exist!”, “Send Mail”, MessageBoxButtons.OK)
    End If

  16. Aman

    I tried using your code and it works on one computer and doesn’t on other (even the same exe file which works on one computer). The “Failure sending email” error message pops up. Do I need to change some security or other setting to run this code!!



  17. Jon

    AWESOME! I tried for hours getting this to work using other stuff. It took me 5 minutes with this!!!!!

    Thank you so much!!

  18. Jason Post author

    The only thing I can think of to schedule a mail is to do so with your application. When the time/date comes that you want the mail sent just have a monitor in your email applcation and then have it auto-send your email.

    Otherwise I am not aware of any method built-in t the .net framework.


  19. ellie

    I also am getting the”failure sending email” error .I open port 25 and disabled the antivirus on the client.Any help would be appriciated

  20. Sovannara

    Please Help me, I use above code, message is success but I check in mail, i don see mail that i send for test.

    Please Help Me.

  21. Lincoln

    I tried the code and got an error:
    “A first chance exception of type ‘System.Net.Mail.SmtpException’ occurred in System.dll”. Can anyone help?

  22. Jason Post author

    Celtic, and others who are getting the “MustIssueStartTlsFirst” set the property below…

    smtp.EnableSsl = True

    Google’s GMail required that feature to be enabled and other SMTP Hosts may require it as well.

    LMK if this helps or not. Thanks 🙂


  23. Liam

    I know it’s nearly a year late but, all smtp servers require the Ssl to be enable

    When using Visual Basic for sending emails, You’d mostly get the the error “operation timed out” when trying to send files larger than 3MB’s and to my knowledge even smaller than that.

    Hope this helped you guy’s out and the one who posted the very first comment.


  24. Israel

    i have problems .
    Why? Please Help!

    Cannot connect to SMTP server (, connect error 10060

  25. Israel

    Error Cannot connect to SMTP server,connect error 10060 or,connect error 10060 depend port
    Please help!!
    My code
    Imports System.Net.Mail
    Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    ‘creamos un nuevo mensaje de correo
    Dim correo As New MailMessage

    correo.From = New MailAddress(“”)

    correo.To.Add(“”) ‘(TextPara.Text)

    correo.Subject = “Asunto”

    ‘Cuerpo del correo

    correo.Body = “TextMensaje.”

    correo.IsBodyHtml = False

    ‘Prioridad de el correo
    correo.Priority = MailPriority.Normal

    Dim smtp As New SmtpClient(“”, 465)

    smtp.EnableSsl = True

    smtp.Credentials = New System.Net.NetworkCredential(“”, “password”)


    MsgBox(“Mensaje enviado satisfactoriamente”)

    Catch exc As Net.Mail.SmtpException

    MessageBox.Show(exc.StatusCode.ToString, ” Something Happened?”, MessageBoxButtons.OK, MessageBoxIcon.Error)

    End Try

    End Sub

    End Class

  26. Jason Post author

    Hi Isreal, i’m not sure it specifically has anything to do with your actual source code. I do want to mention that Google Gmail does require you use port 587.

    I’m not sure if your behind a proxy or not, but microsoft has a couple suggestions even though its not directly related to your problem. But it still might shed some light. This link:

    But it mainly appears that something is blocking your applications port/smtp gmail access. (It can be possible its your ISP). Temporary disable your firewalls, antivirus software, and other security features and then try sending your mail again.

    You didn’t say whether you are running your application on the machine your programming on or not. Try setting clickonce security to – “This is a Full Trust Application” access just to be sure. Also if its on a non-programming machine try giving uac admin rights if you are using Vista or Windows 7.

    If I come up with something else I will post a comment here about it.


  27. koollife

    Sending eMail using SMTP Gmail yahoo hotmail in Visual Basic 2010
    Imports System.Net.Mail

    Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim msg As String
    Dim feedback As String

    msg = “Sender’s Name: ” & tbName.Text
    msg = msg + vbCrLf
    msg = msg + “Sender’s email Address: ” & tbEmail.Text

    feedback = SendEmailMessage(“”, “your“, “yourpasswod”, “Phone Unlock Enquiry”, msg)
    feedback = feedback + vbCrLf + “In order to help improve our services, please feel free to donate by send us a paypal or Western Union.”
    feedback = feedback + vbCrLf + “Thank you for using our free software. We will get back to you within 48 hours.”

    End Sub

  28. lysander.charsi

    pls the code does work in a normal internet cafe. i am using a proxy server to connect to the internet. whenever i try the application on my development laptop which is using the proxy server (ip and a port) it gives me error saying could not resolve host name.

    pls help me out

  29. Vinit

    There is only one problem that there is no End If for if condition of attachment
    The Program is really working very well. 🙂
    the corrected code is like this:

    Dim message As System.Net.Mail.MailMessage

    Dim smtp As New System.Net.Mail.SmtpClient(“”, 587)
    Dim attach As System.Net.Mail.Attachment
    message = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtMessage.Text)
    If My.Computer.FileSystem.FileExists(txtAttachment.Text) Then
    End If
    smtp.EnableSsl = True
    smtp.Credentials = New System.Net.NetworkCredential(“”, “02021993”)

    ‘Send the mail message that was setup.

    ‘Usually it was successful in sending the message if it makes it to here
    ‘Otherwise it should throw a error message from the Catch exception below.
    MessageBox.Show(“Well, the mail message appears to have been a success!”, ” Successful?”, MessageBoxButtons.OK, MessageBoxIcon.Information)
    Catch exc As Net.Mail.SmtpException
    MessageBox.Show(exc.StatusCode.ToString, ” Something Happened?”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

  30. Vidura

    But there is a problem…
    I try to Attach a file, but it’s not work.
    Message sent without attachment.
    Plz Hlp!!!

  31. Jason Post author

    Hi Vidura, i’m not sure what to tell you. If you did everything mentioned in the article it should have worked ok. Make sure the mail server you use allow attachments. Especially make sure that the attachment is not bigger than the mail server allows.

    Download the example from the link below and see if it works. You will need to put in your own password and username, and smtp mail server for it to work in the example.


  32. Ali

    works 1000000000000% perfect “””

    Imports System.Net.Mail
    Public Class Fsend
    Dim message As New MailMessage
    Dim smtp As New SmtpClient
    Private Sub btnsend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsend.Click
    message.From = New MailAddress(TxtFrom.Text)
    message.Subject = TxtSub.Text
    message.Body = TxtBody.Text
    message.Priority = MailPriority.Normal

    smtp.EnableSsl = True
    smtp.Port = “587”
    smtp.Host = “”
    smtp.Credentials = New Net.NetworkCredential(TxtFrom.Text, passtxt.Text)
    MsgBox(“Message has been sent”)

    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    End Sub
    End Class

  33. Charlie

    Hi Jason,

    I am trying to send multiple emails to the same address and have found some interesting results. It seems to only send the last two emails to the address and the first 8 fail. When i use a stop break to check whats going on it manages to send 7 emails to the address, i am completley confused as to why!! Can you help? The Code is below

    Public Class sendBut

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    Dim emailTo As String
    Dim emailFrom As String
    Dim emailSubject(10) As String
    Dim emailBody(10) As String
    Dim smtpServers(10) As System.Net.Mail.SmtpClient
    Dim userName As String = “”
    Dim password As String = “AHcomputing=1”

    ‘Gets the text from the text boxes
    emailTo = Trim(txtEmailTo.Text)
    emailFrom = Trim(txtEmailFrom.Text)

    For i As Integer = 1 To 3
    emailSubject(i) = Trim(txtEmailSubject.Text)
    emailBody(i) = Trim(txtEmailBody.Text)

    smtpServers(i) = New System.Net.Mail.SmtpClient
    smtpServers(i).Host = “”
    smtpServers(i).Timeout = 100
    smtpServers(i).Port = 25
    smtpServers(i).DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network

    smtpServers(i).Credentials = New Net.NetworkCredential(userName, password)

    AddHandler smtpServers(i).SendCompleted, AddressOf doSendCompleted

    Dim message As New Net.Mail.MailMessage(emailFrom, emailTo)

    Dim userState As String = “- Mail Message”
    smtpServers(i).SendAsync(message, userState)

    message.Subject = emailSubject(i)
    message.Body = emailBody(i)

    ‘Specify encoding type
    message.BodyEncoding = System.Text.Encoding.UTF8

    ‘Adds a Relpy to header and a Organisation header
    message.Headers.Add(“Reply-To”, emailFrom)
    message.Headers.Add(“X-Organisation”, “AH Comp”)
    Next i
    End Sub

    ‘This event creates a message box that will be diaplayed once the message has been sent
    Private Sub doSendCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
    Dim token As String = e.UserState.ToString

    If e.Error IsNot Nothing OrElse e.Cancelled Then
    MsgBox(“Error” & e.Error.Message)
    MsgBox(“Message Sent” & token)
    End If
    End Sub
    End Class

    Many thanks in anticipation

  34. Game Key

    Amazing issues here. I am very satisfied to peer your post. Thanks a lot and I’m taking a look ahead to contact you. Will you please drop me a e-mail?

  35. BD

    Thanks a lot for the wonderful code. I used it after I got “System.Exception: Trial Version Expired!” from using EASendMail with SmtpMail(“Tryit”).
    Thanks again.

  36. Jason Post author

    Hi BD, your welcome 🙂

    I have a couple other articles for more advanced features available on this site and a complete example program at my website of making a full mailer type program with advanced email features using the smtp class in the .net framework. Feel free to check them out. 🙂

  37. hid light

    It is in point of fact a great and helpful piece of info. I’m happy that you simply shared this useful info with us. Please stay us informed like this. Thank you for sharing.

  38. Andy Weaver

    Thanks very much for this information. I also kept getting the MustIssueStartTlsFirst error even though smtp.EnableSsl was set equal to “True”, and finally noticed an email from my gmail account indicating that my email acount may have been hacked (it wasn’t of course, it was me trying to log in from Visual Basic). I had to change the security settings on my gmail account by going to, and selecting the option to turn on access for less secure apps. After that, your code worked perfectly. Thanks very much!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.