Dinesh
Dinesh

Reputation: 2066

Sending email from VB.net Windows Form

I have written the following code to send an email from a VB.net windows Form. Here is my code

Try
        Dim message As System.Net.Mail.MailMessage
        Dim smtp As New System.Net.Mail.SmtpClient("smtp.gmail.com")
        Dim fromMailAddress As System.Net.Mail.MailAddress
        Dim toMailAddress As System.Net.Mail.MailAddress

        fromMailAddress = New System.Net.Mail.MailAddress("[email protected]")
        toMailAddress = New System.Net.Mail.MailAddress("[email protected]")

        message = New System.Net.Mail.MailMessage()
        message.From = toMailAddress
        message.To.Add(fromMailAddress)
        message.Subject = "TestFromVB"
        message.Body = "Test Message"

        smtp.EnableSsl = True
        smtp.UseDefaultCredentials = False 
        smtp.Credentials = New System.Net.NetworkCredential("[email protected]", "password")
        smtp.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network

        smtp.Send(message)

        MessageBox.Show("sent...") 

    Catch ex As Exception
        MessageBox.Show("error" + ex.Message + "\n" + ex.InnerException.ToString())
    End Try

Whenever i click on a button send, it should send email to the address specified. Bu this code is giving some error saying Unable to connect to remote machine....

Here is the screenshot of exception enter image description here

Can anybody please help me to fix this issue. or Please suggest if you have any working sample.

Upvotes: 1

Views: 13927

Answers (3)

mike100111
mike100111

Reputation: 960

For anyone else who stumbles on this question, besides the port needing to be correct as the other answers pointed out, many times Google will not authenticate from a Vb.net program without changing the setting in your google account to allow less secure connections. link to google settings

Upvotes: 0

codingbadger
codingbadger

Reputation: 43974

I think you need to use a different port number either 587 or 465

As per this GMail document.

  • Incoming Mail (POP3) Server - requires SSL: pop.gmail.com

    • Use SSL: Yes
    • Port: 995
  • Outgoing Mail (SMTP) Server - requires TLS or SSL: smtp.gmail.com

    • Use Authentication: Yes
    • Port for TLS/STARTTLS: 587
    • Port for SSL: 465
    • Account Name: your full email address (including @gmail.com or @your_domain.com)
    • Email Address:your email address ([email protected] or username@your_domain.com)
    • Password: your Gmail password

Upvotes: 4

Ira Rainey
Ira Rainey

Reputation: 5209

GMail uses port 587 for the smtp server. See this code sample:

http://www.fryan0911.com/2009/10/how-to-send-email-via-gmail-smtp-in.html

Upvotes: 0

Related Questions