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. 🙂


Covered:

  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("smtp.gmail.com", 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: “mysmtp.host.com”

 

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("yourUsername@yourmail.com", "password")

 

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

        Try
            '
            'Send the mail message that was setup.
            smtp.Send(Message)
            '
            '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…

Jason

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?

    Reply
  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.

    Jason

    Reply
  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….

    Reply
  4. Navaneethan

    Hi,
    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.”

    Reply
  5. Navaneethan

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

    Reply
  6. Navaneethan

    Hi,
    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….

    Reply
  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 Shaw.ca 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.
    Thanks

    Reply
  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: http://www.vbcodesource.com website on how to create a full-blown richtextbox based word application for vb.net 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. 🙂

    Jason

    Reply
  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.

    Reply
  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

    Thanks

    Reply
  11. Bill

    I get the following error – any ideas?

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

    Reply
  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!

    Reply
  13. Murt

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

    Reply
  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.

    Reply
  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)
    Message.Attachments.Add(attachFile)
    Else
    MessageBox.Show(“File doesnt Exist!”, “Send Mail”, MessageBoxButtons.OK)
    End If

    Reply
  16. Aman

    Jason,
    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!!

    Thanks,

    Aman

    Reply
  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!!

    Reply
  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.

    Jason

    Reply
  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

    Reply
  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.

    Reply
  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?

    Reply
  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 🙂

    Jason

    Reply
  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.

    Liam

    Reply
  24. Israel

    i have problems .
    Why? Please Help!

    Cannot connect to SMTP server 72.14.213.109 (72.14.213.109:587), connect error 10060

    Reply
  25. Israel

    Error Cannot connect to SMTP server 72.14.213.109:465,connect error 10060 or 72.14.213.109:587,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

    ‘De
    correo.From = New MailAddress(“micuenta@gmail.com”)

    ‘Para
    correo.To.Add(“cuentaX@yahoo.com.mx”) ‘(TextPara.Text)

    ‘Asunto
    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(“smtp.gmail.com”, 465)

    smtp.EnableSsl = True

    smtp.Credentials = New System.Net.NetworkCredential(“username@gmail.com”, “password”)

    Try
    smtp.Send(correo)

    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

    Reply
  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: http://support.microsoft.com/kb/811087

    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.

    Jason

    Reply
  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(“koolzykoller@gmail.com”, “your id@gmail.com“, “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

    Reply
  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

    Reply
  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(“smtp.gmail.com”, 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
    message.Attachments.Add(attach)
    End If
    smtp.EnableSsl = True
    smtp.Credentials = New System.Net.NetworkCredential(“vinitsmsservices@gmail.com”, “02021993”)
    Try

    ‘Send the mail message that was setup.
    smtp.Send(message)

    ‘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

    Reply
  30. Vidura

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

    Reply
  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.

    http://www.vbcodesource.info/downloads/vbNet2005/sendingMailExGMail05.zip

    Jason

    Reply
  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.To.Add(txtto.Text)
    message.Subject = TxtSub.Text
    message.Body = TxtBody.Text
    message.Priority = MailPriority.Normal

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

    End Sub

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

    Reply
  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 = “classCover@mail.com”
    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 = “smtp.mail.com”
    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)
    Else
    MsgBox(“Message Sent” & token)
    End If
    End Sub
    End Class

    Many thanks in anticipation

    Reply
  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?

    Reply
  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.

    Reply
  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 vbcodesource.com 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. 🙂

    Reply
  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.

    Reply
  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 https://www.google.com/settings/security/lesssecureapps, and selecting the option to turn on access for less secure apps. After that, your code worked perfectly. Thanks very much!

    Reply

Leave a Reply