willmrk
asked on
Sending email with vb.net
I need to be able to send an email to an email address from an application. I have access to an SMTP server. Can someone provide an example of how to do this in vb.net?
Thanks
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Forgotten to mention the source: http://www.freevbcode.com/ShowCode.asp?ID=6401
Hi willmrk;
If you are using VB .Net 2005 this is the new way to sent mail in this version.
Imports System.Net.Mail
Private Sub SendEmail(ByVal sender As String, _
ByVal recipient As String, ByVal subject As String, _
ByVal body As String, Optional ByVal attachmentString As String = "")
Dim fromAddress As New MailAddress(sender)
Dim toAddress As New MailAddress(recipient)
Dim message As New MailMessage(fromAddress, toAddress)
Dim mailSender As SmtpClient
' Change the Smtp server name on the next line
mailSender = New SmtpClient("smtp-server.ny .rr.com", 25)
message.Bcc.Add(fromAddres s)
message.Subject = subject
message.IsBodyHtml = False
message.Body = body
If Not attachmentString = "" Then
Dim msgAttach As New Attachment(attachmentStrin g)
message.Attachments.Add(ms gAttach)
End If
Try
mailSender.Send(message)
Catch ex As Exception
MessageBox.Show(ex.Message , "Error Mail Not Sent")
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
SendEmail("From@Domain.com ", "To@Domain.com", _
"This is a test Subject line", "This is the Body", "c:\Temp\Attachment_If_any \pp1.pdf")
End Sub
Fernando
If you are using VB .Net 2005 this is the new way to sent mail in this version.
Imports System.Net.Mail
Private Sub SendEmail(ByVal sender As String, _
ByVal recipient As String, ByVal subject As String, _
ByVal body As String, Optional ByVal attachmentString As String = "")
Dim fromAddress As New MailAddress(sender)
Dim toAddress As New MailAddress(recipient)
Dim message As New MailMessage(fromAddress, toAddress)
Dim mailSender As SmtpClient
' Change the Smtp server name on the next line
mailSender = New SmtpClient("smtp-server.ny
message.Bcc.Add(fromAddres
message.Subject = subject
message.IsBodyHtml = False
message.Body = body
If Not attachmentString = "" Then
Dim msgAttach As New Attachment(attachmentStrin
message.Attachments.Add(ms
End If
Try
mailSender.Send(message)
Catch ex As Exception
MessageBox.Show(ex.Message
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
SendEmail("From@Domain.com
"This is a test Subject line", "This is the Body", "c:\Temp\Attachment_If_any
End Sub
Fernando
Download the source code provided by Microsoft
www.vbhelp.gr/sendmail.zip
This sample shows how to send email over SMTP using classes in the System.Web.Mail namespace.
www.vbhelp.gr/sendmail.zip
This sample shows how to send email over SMTP using classes in the System.Web.Mail namespace.
Here is a simple sub you can use to send an email, I use it all the time (just enter the ip or hostname of your email server)
Private Shared Sub SendEmail(ByVal From As String, ByVal Recipient As String, ByVal Subject As String, ByVal Body As String)
Dim ip as string = "5.29.73.75"
Dim smtp As New SmtpClient(ip)
Try
'separate recipients by comma
smtp.Send(From, Recipient.Replace(";", ","), Subject, Body)
Catch ex As SmtpException
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Send Email")
End Try
smtp = Nothing
End Sub
Private Shared Sub SendEmail(ByVal From As String, ByVal Recipient As String, ByVal Subject As String, ByVal Body As String)
Dim ip as string = "5.29.73.75"
Dim smtp As New SmtpClient(ip)
Try
'separate recipients by comma
smtp.Send(From, Recipient.Replace(";", ","), Subject, Body)
Catch ex As SmtpException
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Send Email")
End Try
smtp = Nothing
End Sub
ASKER
I am using vb.net 2005, so the system.web.mail library doesnt exist.
I tried the suggestions provided using the system.net.mail, but always get the same error: Inner exception "Unable to read data from the transport connection: net_io_connectionclosed."
I find a lot of data on this error on google, but no resolutions. Any ideas?
System.Net.Mail.SmtpExcept ion was unhandled
Message="Failure sending mail."
Source="System"
StackTrace:
at System.Net.Mail.SmtpClient .Send(Mail Message message)
at WindowsApplication1.Form1. SendEmail( String sender, String recipient, String subject, String body, String attachmentString) in D:\Profiles\wlrw02\My Documents\Visual Studio 2005\Projects\EmailApp\Ema ilApp\Form 1.vb:line 42
at WindowsApplication1.Form1. Button1_Cl ick(Object sender, EventArgs e) in D:\Profiles\wlrw02\My Documents\Visual Studio 2005\Projects\EmailApp\Ema ilApp\Form 1.vb:line 52
at System.Windows.Forms.Contr ol.OnClick (EventArgs e)
at System.Windows.Forms.Butto n.OnClick( EventArgs e)
at System.Windows.Forms.Butto n.OnMouseU p(MouseEve ntArgs mevent)
at System.Windows.Forms.Contr ol.WmMouse Up(Message & m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Contr ol.WndProc (Message& m)
at System.Windows.Forms.Butto nBase.WndP roc(Messag e& m)
at System.Windows.Forms.Butto n.WndProc( Message& m)
at System.Windows.Forms.Contr ol.Control NativeWind ow.OnMessa ge(Message & m)
at System.Windows.Forms.Contr ol.Control NativeWind ow.WndProc (Message& m)
at System.Windows.Forms.Nativ eWindow.De buggableCa llback(Int Ptr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.Unsaf eNativeMet hods.Dispa tchMessage W(MSG& msg)
at System.Windows.Forms.Appli cation.Com ponentMana ger.System .Windows.F orms.Unsaf eNativeMet hods.IMsoC omponentMa nager.FPus hMessageLo op(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Appli cation.Thr eadContext .RunMessag eLoopInner (Int32 reason, ApplicationContext context)
at System.Windows.Forms.Appli cation.Thr eadContext .RunMessag eLoop(Int3 2 reason, ApplicationContext context)
at System.Windows.Forms.Appli cation.Run (Applicati onContext context)
at Microsoft.VisualBasic.Appl icationSer vices.Wind owsFormsAp plicationB ase.OnRun( )
at Microsoft.VisualBasic.Appl icationSer vices.Wind owsFormsAp plicationB ase.DoAppl icationMod el()
at Microsoft.VisualBasic.Appl icationSer vices.Wind owsFormsAp plicationB ase.Run(St ring[] commandLine)
at WindowsApplication1.My.MyA pplication .Main(Stri ng[] Args) in 17d14f5c-a337-4978-8281-53 493378c107 1.vb:line 81
at System.AppDomain.nExecuteA ssembly(As sembly assembly, String[] args)
at System.AppDomain.ExecuteAs sembly(Str ing assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.Hos tingProces s.HostProc .RunUsersA ssembly()
at System.Threading.ThreadHel per.Thread Start_Cont ext(Object state)
at System.Threading.Execution Context.Ru n(Executio nContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHel per.Thread Start()
with an inner exception of this:
"Unable to read data from the transport connection: net_io_connectionclosed."
at System.Net.Mail.SmtpReplyR eaderFacto ry.Process Read(Byte[ ] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyR eaderFacto ry.ReadLin es(SmtpRep lyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyR eaderFacto ry.ReadLin e(SmtpRepl yReader caller)
at System.Net.Mail.SmtpReplyR eader.Read Line()
at System.Net.Mail.SmtpConnec tion.GetCo nnection(S tring host, Int32 port)
at System.Net.Mail.SmtpTransp ort.GetCon nection(St ring host, Int32 port)
at System.Net.Mail.SmtpClient .GetConnec tion()
at System.Net.Mail.SmtpClient .Send(Mail Message message)"
I tried the suggestions provided using the system.net.mail, but always get the same error: Inner exception "Unable to read data from the transport connection: net_io_connectionclosed."
I find a lot of data on this error on google, but no resolutions. Any ideas?
System.Net.Mail.SmtpExcept
Message="Failure sending mail."
Source="System"
StackTrace:
at System.Net.Mail.SmtpClient
at WindowsApplication1.Form1.
at WindowsApplication1.Form1.
at System.Windows.Forms.Contr
at System.Windows.Forms.Butto
at System.Windows.Forms.Butto
at System.Windows.Forms.Contr
at System.Windows.Forms.Contr
at System.Windows.Forms.Butto
at System.Windows.Forms.Butto
at System.Windows.Forms.Contr
at System.Windows.Forms.Contr
at System.Windows.Forms.Nativ
at System.Windows.Forms.Unsaf
at System.Windows.Forms.Appli
at System.Windows.Forms.Appli
at System.Windows.Forms.Appli
at System.Windows.Forms.Appli
at Microsoft.VisualBasic.Appl
at Microsoft.VisualBasic.Appl
at Microsoft.VisualBasic.Appl
at WindowsApplication1.My.MyA
at System.AppDomain.nExecuteA
at System.AppDomain.ExecuteAs
at Microsoft.VisualStudio.Hos
at System.Threading.ThreadHel
at System.Threading.Execution
at System.Threading.ThreadHel
with an inner exception of this:
"Unable to read data from the transport connection: net_io_connectionclosed."
at System.Net.Mail.SmtpReplyR
at System.Net.Mail.SmtpReplyR
at System.Net.Mail.SmtpReplyR
at System.Net.Mail.SmtpReplyR
at System.Net.Mail.SmtpConnec
at System.Net.Mail.SmtpTransp
at System.Net.Mail.SmtpClient
at System.Net.Mail.SmtpClient
Hi willmrk;
Have you changed this line of code to reflect the correct smtp sever name for your mail server?
' Change the Smtp server name on the next line
mailSender = New SmtpClient("smtp-server.ny .rr.com", 25)
Fernando
Have you changed this line of code to reflect the correct smtp sever name for your mail server?
' Change the Smtp server name on the next line
mailSender = New SmtpClient("smtp-server.ny
Fernando
ASKER
Yes. I am trying it with my corporate exchange server and also with my yahoo small business smtp server. No dice either way, same error "Unable to read data from the transport connection: net_io_connectionclosed"
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Any tips on how to verify if firewall is blocking or not?
I am using a laptop with a standard corporate image on it. THey may have done some administration stuff to prevent anyone from messing with the firewall settings.
I am using a laptop with a standard corporate image on it. THey may have done some administration stuff to prevent anyone from messing with the firewall settings.
Most firewalls have an icon in the system tray. When you right click on it a context menu open and may have an option to restore control console. For example Zone Alarm Pro has a menu select called "Restore ZoneAlarm Pro Control Center" Which may have log of attempts made to send traffic out and also may have the ability to allow and deny access. Other then that you may see if the network administrator can check it out for you.
have a look at www.systemwebmail.com
Since you found no solution yet, I'll post my code I use in .asp pages (modified a little)
It works fine in a .asp page, I think it works well also in .net apps
Sub SendMail_CDOSYS(ByVal MailBody As String, ByVal strFrom As String, ByVal strTo As String, ByVal strSubject As String, ByVal atchFile As String)
On Error Resume Next
MailBody = Replace(MailBody, vbCrLf & "<br>", "<br>")
MailBody = Replace(MailBody, vbCrLf, "<br>")
'
Dim oCdoMail, oCdoConf As Object, sConfURL As String = ""
oCdoMail = CreateObject("CDO.Message" )
oCdoConf = CreateObject("CDO.Configur ation")
sConfURL = "http://schemas.microsoft.com/cdo/configuration/"
'
With oCdoConf
.Fields.Item(sConfURL & "sendusing") = 2
.Fields.Item(sConfURL & "smtpserver") = "yourSmtpPcName.yourDomain .com"
.Fields.Item(sConfURL & "smtpserverport") = 25
.Fields.Update()
End With
'
Dim iBP
With oCdoMail
.From = strFrom
.To = strTo
.Subject = strSubject
.TextBody = MailBody
.HTMLBody = MailBody
If Trim(atchFile) <> "" Then
iBP = oCdoMail.AddAttachment(atc hFile)
End If
.Configuration = oCdoConf
.Send()
End With
'
oCdoConf = Nothing
oCdoMail = Nothing
On Error GoTo 0
End Sub
It works fine in a .asp page, I think it works well also in .net apps
Sub SendMail_CDOSYS(ByVal MailBody As String, ByVal strFrom As String, ByVal strTo As String, ByVal strSubject As String, ByVal atchFile As String)
On Error Resume Next
MailBody = Replace(MailBody, vbCrLf & "<br>", "<br>")
MailBody = Replace(MailBody, vbCrLf, "<br>")
'
Dim oCdoMail, oCdoConf As Object, sConfURL As String = ""
oCdoMail = CreateObject("CDO.Message"
oCdoConf = CreateObject("CDO.Configur
sConfURL = "http://schemas.microsoft.com/cdo/configuration/"
'
With oCdoConf
.Fields.Item(sConfURL & "sendusing") = 2
.Fields.Item(sConfURL & "smtpserver") = "yourSmtpPcName.yourDomain
.Fields.Item(sConfURL & "smtpserverport") = 25
.Fields.Update()
End With
'
Dim iBP
With oCdoMail
.From = strFrom
.To = strTo
.Subject = strSubject
.TextBody = MailBody
.HTMLBody = MailBody
If Trim(atchFile) <> "" Then
iBP = oCdoMail.AddAttachment(atc
End If
.Configuration = oCdoConf
.Send()
End With
'
oCdoConf = Nothing
oCdoMail = Nothing
On Error GoTo 0
End Sub
I am using vb.net 2005, so the system.web.mail library doesnt exist. --> used for web-applications
in 2005, you need to use system.net.mail (see www.systemnetmail.com)
notice that in 2003, we were using system.web.mail even in Windows application.
notice that in 2003, we were using system.web.mail even in Windows application.
ASKER
Well, I think I have resolved my issue, but haven't found the problem. Since I was connecting to my corporate intranet via a VPN, that was preventing my application from working. When I run the application while I'm physically on the intranet, it works fine. There are no firewall icons in my traybar, and windows firewall shows that it is off.
Does anybody have any cludes as to how the VPN could be preventing this from working remotely and how it could be resolved?
Thanks everyone for your help.
Does anybody have any cludes as to how the VPN could be preventing this from working remotely and how it could be resolved?
Thanks everyone for your help.
Hi willmrk;
Glad to hear that the code does work for you. But now you need to find out how to make a connection through the VPN tunnel. When you send an e-mail message from you program it attempts to send that out over the internet connection and not your VPN. It looks like the the smtp sever you are connecting to does not accepts mail to be sent from outside of its local network otherwise it would have worked. You need to get together with the networking people at your company and or the vendor supplying the VPN to find out how to connect with it from you program. Also once you get pass that you may still have a problem because on the other side of the VPN tunnel is a firewall, most likely. I hope that this helps.
Fernando
Glad to hear that the code does work for you. But now you need to find out how to make a connection through the VPN tunnel. When you send an e-mail message from you program it attempts to send that out over the internet connection and not your VPN. It looks like the the smtp sever you are connecting to does not accepts mail to be sent from outside of its local network otherwise it would have worked. You need to get together with the networking people at your company and or the vendor supplying the VPN to find out how to connect with it from you program. Also once you get pass that you may still have a problem because on the other side of the VPN tunnel is a firewall, most likely. I hope that this helps.
Fernando