Link to home
Start Free TrialLog in
Avatar of willmrk
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
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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(fromAddress)
        message.Subject = subject
        message.IsBodyHtml = False
        message.Body = body

        If Not attachmentString = "" Then
            Dim msgAttach As New Attachment(attachmentString)
            message.Attachments.Add(msgAttach)
        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
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.
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
Avatar of willmrk
willmrk

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.SmtpException was unhandled
  Message="Failure sending mail."
  Source="System"
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage 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\EmailApp\Form1.vb:line 42
       at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in D:\Profiles\wlrw02\My Documents\Visual Studio 2005\Projects\EmailApp\EmailApp\Form1.vb:line 52
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()


with an inner exception of this:

"Unable to read data from the transport connection: net_io_connectionclosed."

   at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
   at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
   at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
   at System.Net.Mail.SmtpReplyReader.ReadLine()
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)"
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
Avatar of willmrk

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
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of willmrk

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.
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.
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.Configuration")
        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(atchFile)
            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.
Avatar of willmrk

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