We help IT Professionals succeed at work.

Sending emails from a web form


I am trying to make my asp.net web form send an email from @gmail.com to @gmail.com email address. Using code provided below. Obviously, "username@gmail.com" is replaced with the email address that sends an email and etc.

   Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim SmtpServer As New SmtpClient()
            Dim mail As New MailMessage()
            SmtpServer.Credentials = New  _
        Net.NetworkCredential("username@gmail.com", "password")
            SmtpServer.Port = 587
            SmtpServer.Host = "smtp.gmail.com"
            mail = New MailMessage()
            mail.From = New MailAddress("yourusername@gmail.com")
            mail.Subject = "Test Mail"
            mail.Body = "This is for testing SMTP mail from GMAIL"
            MsgBox("mail send")
        Catch ex As Exception
        End Try
    End Sub

Open in new window

When the button is pressed, I receive the error message:

How can I fix it? Thanks!
Watch Question

Salah Eddine ELMRABETTechnical Lead Manager (Owner)


It seem this is authentication problem! have you correctly define the password? also the port you use : 587 is not working I tried a telnet to google SMTP using this port without success.

Basically you can use default smtp port 25 or 465 (secured port).

Best regards.

Have you followed the following steps?

Enable IMAP in your Gmail settings

Sign in to Gmail.
Click the gear in the top right .
Select Settings.
Click Forwarding and POP/IMAP.
Select Enable IMAP.
Click Save Changes.

I have some code laying around somewhere that I have used to send email with gmail if you need it.  Just let me know.   It's in VB.NET

Also you are passing the password instead of "password" correct?



I have tried to use ports your offered, but none of them worked - -25 gave the same error, and 465 was just loading for 15 minutes and did nothing eventually.

Yes, IMAP was enables.
Hm,  pretty sure password is right, I have tried two different email addresses, none works. When I type password in, does it look like "********"? Do In need any additional ''?.. Just in case

And yes, I would like to see your code if you don't mind explaining in breif how it works)
I will find it.   I have to finish up a small project and then I will see what I can do.
Salah Eddine ELMRABETTechnical Lead Manager (Owner)


Do you use texbox type password in the form?? the "*********" you see is it in the web page display when you fill the form or when you edit the script??

try to use plain text texbox and see if you can send the email, if this is the case try to find what happened within you code in the script


I found it.   I am modifying to as I have a whole bunch of application specific items in it.      I will post it here in a few minutes.



No, I just type the password directly into the code.
Private Function SendEmail(ByVal strSendToThisEmailAddress As String, ByVal strEmailSubject As String, ByVal strEmailBody As String) As Boolean
        Dim oUserName       As String     = "GMAIL USERNAME WITHOUT @GMAIL.COM"
        Dim oPassword       As String     = "ENTER YOUR PASSWORD HERE"
        Dim oServerAddress  As String     = "smtp.gmail.com"
        Dim oUseSSL         As Boolean    = True
        Dim oFromEmail      As String     = oUserName & "@gmail.com"
        Dim blnResult       As Boolean    = False

        Dim oSMTP As New SmtpClient()

                Dim message As New MailMessage() 'Create new Mail Message Item
                    message.To.Add(New MailAddress(strSendToThisEmailAddress)) 'This is passed into the function so create a new recipient and add it to the message.
                    message.From = New MailAddress(oFromEmail) 'This is set above so we will use it to crate a new email address object.

                With oSMTP
                    .Host = oServerAddress
                    .EnableSsl = oUseSSL
                    .DeliveryMethod = SmtpDeliveryMethod.Network
                    .Credentials = New NetworkCredential(oUserName, oPassword)
                    .Timeout = 5000
                End With

                With message 'Set the message content and a few other things.              
                    .Subject = strEmailSubject
                    .Body = strEmailBody
                    .IsBodyHtml = True
                    .BodyEncoding = Encoding.Default
                End With
                Me.Cursor = Cursors.WaitCursor

                oSMTP.Send(message) 'Send the message    
                MsgBox("Test Was Successful.  Verify receipt of the email", vbInformation, "Successfully Sent Email")    
                blnResult = True 'Set the result of the function to true so you know if it worked or not.

                Me.Cursor = Cursors.Default 'Stop the busy cursor      

            Catch smtpEx As SmtpException 'This is to catch any SMTP error.

                Me.Cursor = Cursors.Default 'Stop the busy cursor.

                MsgBox("SMTP ERROR:  " & smtpEx.ToString() ,vbCritical)

                blnResult = False 'Didn't work, but you will already know what because you will get a message box, but I recommend disabling that once you get it working.

            Catch Ex As Exception 'This is for any general error that occured that was NOT because of an SMTP error.
                MsgBox("GENERAL FAILURE: " & Ex.ToString() ,vbCritical)   
                blnResult = False 'Didn't work, but you will already know what because you will get a message box, but I recommend disabling that once you get it working.

        End Try  

        Me.Cursor = Cursors.Default 
        Return blnResult 'Return the results of your email message.

End Function

Open in new window

Then to call it:

            If SendEmail("EmailAddressToSendToHere@test.com","This is the Subject","This is the body") then

                  'IT WORKED

            End If

End Function

Open in new window

I just tested it and it worked perfectly.   If you get an error 5.5.1 when you first try it, log into gmail and check your mail.  You will have an email in there saying that your account was accessed and that you need to enable "Less Secure" applications.    Once you do that you will be good to go.  You will want to wait a minute or two.   For a synopsis of this step see: Click Here for Explaination

Let me know if you are still having issues.
I just edited the code snip to include the Function definition.    ooops.