简体   繁体   中英

Sending email through gmail using SMTP

I am trying to send an email through following code

CODE


    Dim MyMailMessage As New MailMessage()
    'From requires an instance of the MailAddress type
    MyMailMessage.From = New MailAddress("a@gmail.com")
    'To is a collection of MailAddress types
    MyMailMessage.To.Add("a@something.com")
    MyMailMessage.Subject = "GMail Test"
    MyMailMessage.Body = "This is the test text for Gmail email"
    'Create the SMTPClient object and specify the SMTP GMail server
    Dim SMTPServer As New SmtpClient("smtp.gmail.com")
    SMTPServer.Port = 465
    SMTPServer.Credentials = New System.Net.NetworkCredential("a@gmail.com", "*****")
    SMTPServer.EnableSsl = True
    Try
        SMTPServer.Send(MyMailMessage)
        MessageBox.Show("Email Sent")
    Catch ex As SmtpException
        MessageBox.Show(ex.Message)
    End Try

However this code is not working I get following exceptions:

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in System.dll
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in MailSender.exe

And finally delivery of message fails.

Any idea why it is not working?

NOTE : I have tried SMTPServer.Port = 587 too but still its not working

In order to isolate port problem do the following test: Start>run> type there "cmd"> enter. in the black screen type: telnet smtp.gmail.com 465 .
if you get this message:

Connecting To smtp.gmail.com...Could not open connection to the host, on port 465: Connect failed

it means you network administrator closed this port to outside connection. If you get black empty screen it means the connection is OK. if the command telnet is not available for you, you have to add this service (search Google how to add telnet client)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM