Sending eMail using SMTP in Visual Basic.NET & Visual Basic 2005/2008/2010
This small article is just going to cover the Normal basic features of a email client to send mail messages. This post shows how to Send a email using Visual Basic 2005, VB 2008, and VB.NET 2010.
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 a article at The Code Project for which I got the info for using gMail as the smtp host.
Covered:
- Attachment
- To
- From
- Subject
- Body
Maybe when I get time I will do some research and make a article on adding more mail features.
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…
- the SMTPClient Class
- the MailMessage Class
- 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
And now your can set up 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. I will have to take a look when I can to see the diferrences and will then post them. 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

(13 votes, average: 4.46 out of 5)
I tried your code. But some thing is wrong.
For me the error message is “operation timed out”.
Can you please clear this?
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
Its great, ive been searching for this for weeks. Thanks !!
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….
it works it works !
i uploaded just the src to http://sel2in.com/pages/dotnet/vb/smtp1/
this is with a console app
now i need to learn how to read an ini in dotnet and set the smtps for the mail component
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.”
Hi,
I got this error while i runninng in my Port “The remote certificate is invalid according to the validation procedure”
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….
Hi,
Thx, i have tried it and it worked
Awsome I have been looking for help on this all over the net thank you sooooo much!!!
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
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
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.
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
I get the following error – any ideas?
Mailbox unavailable. The server response was: 5.7.1 Unable to relay for myemailaddress.com
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!
hi, i tried the code above where i get a general error or failure sending mail.
hi, i tried the code above where i get a general error or failure sending mail.
Thanks pal, ive been Trying to send mails, without needing to configure my programs for each ISP for weeks.
como hago para enviar archivos zip
i need send a zip file as attachment
Hi,
While running the code i am getting the following error – MustIssueStartTlsFirst.
Can someone please suggest?
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.
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.
Thank you! Thank you! Thank you! I have been looking for this all morning. Good Job!!!
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
thanks
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
thak you sir
i try your code it works
thaking you
i want to send mail through my pop address but it give me error
i have test this code when execute this code this error occur. “general failur”
AWESOME! I tried for hours getting this to work using other stuff. It took me 5 minutes with this!!!!!
Thank you so much!!
hi,
is it possible to mention time the mail should be delivered.
Thank you
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
i want yo make it to send info to my email using a text box and a button
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
Worked for me like a treat. Visual studio 2008 express, vista home and away it went.
Thanks for sharing
Thanks
Thanks!
I tried it and it solved my problem.
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.
The best and simplest way. I love u
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?
Hi!,
Just a note to simply say Thank you!
Your code works just great!
I get the same Error “MustIssueStartTlsFirst” Help please?
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
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
i have problems .
Why? Please Help!
Cannot connect to SMTP server 72.14.213.109 (72.14.213.109:587), connect error 10060
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
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
Thanks so much Jason. The problem was firewalls and antivirus, because the ports were blocking
Good to see you found out what was going on. Take care
Jason
How do you recieve emails?
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
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
Lysander, try the answer in the link below. Its in C# but you can easily convert it to vb.net using a c# to vb converter.
http://stackoverflow.com/questions/844835/sending-mail-throught-http-proxy/844874#844874
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
Thanks!
But there is a problem…
I try to Attach a file, but it’s not work.
Message sent without attachment.
Plz Hlp!!!
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
How would you send a whole folder instead of just a file?
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
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
Hi, looking over your code i’m having a hard time understanding it. I have a full email example application at my vbcodesource.com website at this link:http://www.vbcodesource.com/downloads/vbNet2005/sendingEmailMultipleSmtp.zip
Check out that example and you can see how I send an email to multiple recipients and multiple cc’s as well. Hopefully that will help you.
Jason
I have changed the port number to 25 and it works =)
asp.net email source code in vb.net and c#
asp.net-informations.com/communications/asp-email.htm
merca
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?
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.
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.
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.