Sending emails from a web form

Hello,

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
        Try
            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.To.Add("recieveraddress")
            mail.Subject = "Test Mail"
            mail.Body = "This is for testing SMTP mail from GMAIL"
            SmtpServer.Send(mail)
            MsgBox("mail send")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

Open in new window


When the button is pressed, I receive the error message:
Screenshot---27-02-2015---17-12-46.png

How can I fix it? Thanks!
German MikulskiAsked:
Who is Participating?
 
JServicesLLCCommented:
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
                
             Try 
                
                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.
0
 
Salah Eddine ELMRABETTechnical Lead Manager (Owner)Commented:
Hi,

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.

Salah
0
 
JServicesLLCCommented:
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

EDIT:
Also you are passing the password instead of "password" correct?
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
German MikulskiAuthor Commented:
Hi,

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)
0
 
JServicesLLCCommented:
I will find it.   I have to finish up a small project and then I will see what I can do.
0
 
Salah Eddine ELMRABETTechnical Lead Manager (Owner)Commented:
Hi,

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

regards.

Salah
0
 
JServicesLLCCommented:
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.
0
 
German MikulskiAuthor Commented:
Salah,

No, I just type the password directly into the code.
0
 
JServicesLLCCommented:
I just edited the code snip to include the Function definition.    ooops.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.