i keep getting this error message
any solutions ?
"smtp server requires a secure connection or the client was not authenticated 5.5.1"
Public Sub SendCode()
GenerateCode()
Dim Mail As New MailMessage
Dim SMTPServer As New SmtpClient("smtp.gmail.com")
Try
SMTPServer.Credentials = New _
Net.NetworkCredential("email#gmail.com", "password")
Mail.From = New MailAddress("email#gmail.com")
Mail.To.Add("email2#gmail.com")
Mail.Subject = "Confirmation Code"
Mail.Body = Me.Firstname & " " & Me.LastN & " This is a NO_REPLY confirmation Email, Confirmation Code:" & Me.ConfirmationCode & ""
SMTPServer.Port = 587
SMTPServer.EnableSsl = True
SMTPServer.Send(Mail)
MsgBox("mail sent")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You need to set port to 465 and SSL/TLS to auto...
I've used this code successfully... https://www.emailarchitect.net/easendmail/kb/vbnet.aspx?cat=2
Related
I am using Postgresql for my database, i want to create an App where the user login their account, i have this logic , and i am getting this error System.NullReferenceException: 'Object reference not set to an instance of an object.' why i am getting this error?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Username = Username_TextBox1.Text
Dim Password = Password_TextBox2.Text
Dim dt As New DataTable
Dim ds = New DataSet
Dim i As Integer
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=YouthRecord;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT * FROM YouthApp_tableuser WHERE `username` " & "='" & Username & "' and " & "password='" & Password & "'", MyCon)
If ds.Tables("YouthApp_tableuser").Rows.Count > 0 Then
For i = 0 To ds.Tables("YouthApp_tableuser").Rows.Count - 1
Username = ds.Tables("YouthApp_tableuser").Rows(i).Item(1).ToString
Password = ds.Tables("YouthApp_tableuser").Rows(i).Item(2).ToString
Next
If (Username = Username_TextBox1.Text And Password = Password_TextBox2.Text) Then
Username = ""
Password = ""
MainForm.Show()
Me.Hide()
Else
MsgBox("Invalid User! Please Enter Correct User Name and Password.", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Invalid!")
Username = ""
Password = ""
End If
End If
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Catch ex As Exception
End Try
this is the error
UPDATE
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=YouthRecord;server=localhost;port=5432;uid=******;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT id, username, password FROM ""YouthApp_tableuser"" where username='" & Username & "' and password='" & Password & "' ", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
If ds.Tables("YouthApp_tableuser").Rows.Count > 0 Then
If (Username = Username_TextBox1.Text And Password = Password_TextBox2.Text) Then
Username = ""
Password = ""
MainForm.Show()
Me.Hide()
Else
MsgBox("Invalid User! Please Enter Correct User Name and Password.", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Invalid!")
Username = ""
Password = ""
End If
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
i get the same error
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=YouthRecord;server=localhost;port=5432;uid=*****;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT id, username, password FROM ""YouthApp_tableuser"" where username='" & Username & "' and password='" & Password & "' ", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
If dt.Rows.Count > 0 Then
If (Username = Username_TextBox1.Text And Password = Password_TextBox2.Text) Then
Username = ""
Password = ""
MainForm.Show()
Me.Hide()
End If
Else
MsgBox("Invalid User! Please Enter Correct User Name and Password.", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Invalid!")
Username = ""
Password = ""
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
invalid attempt to read when reader is closed error. vb.net
I have the code below that I use to login into MySQL but it keeps displaying the error 'invalid attempt to read when reader is closed' and then it logs in. I don't understand what could still be wrong with the code. Kindly assist, it's so frustrating. Thanks.
Try
ConnDB()
command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
Reader = command.ExecuteReader()
If Reader.Read = True Then
ComboBox1.Text = Reader.GetValue(2)
lblUser.Text = Reader.GetValue(3)
End If
If (Reader IsNot Nothing) Then
Reader.Close()
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
If ComboBox1.Text.Length > 0 Then
MainMenu.lblUserName.Text = Me.txtUsername.Text
MainMenu.lblType.Text = Me.ComboBox1.Text
MainMenu.lblOccupation.Text = Me.ComboBox1.Text
MainMenu.lblUser.Text = Me.lblUser.Text
Dim st As String = "Successfully logged in"
LogFunc(txtUsername.Text, st)
Me.Hide()
MainMenu.Show()
Else
MsgBox("Incorrect username or password..Login is Failed...Try again !", MsgBoxStyle.Critical, "Login")
txtUsername.SelectAll()
txtPassword.SelectAll()
txtUsername.Focus()
txtPassword.Text = ""
End If
command.Dispose()
' Reader.Close()
'command.Dispose()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
DisconnMy()
End Try
I expect it to log in successfully without displaying the error.
Sorry, I forgot to add this for my connection string.
Public Sub ConnDB()
con.Close()
Try
con.ConnectionString = "Server = '" & ServerMySQL & "'; " _
& "Port = '" & PortMySQL & "'; " _
& "Database = '" & DBNameMySQL & "'; " _
& "user id = '" & UserNameMySQL & "'; " _
& "password = '" & PwdMySQL & "'"
con.Open()
Catch ex As Exception
MsgBox("The system failed to establish a connection", MsgBoxStyle.Information, "Database Settings")
End Try
End Sub
In general it's not a good idea to use a "global", single connection for everything. Note that connection-pooling is enabled by default which means that .NET will take care of the physical connections. So you should create,open,use and close/dispose the connection where you use it.
I'm pretty sure that this will fix the issue:
Try
Using con As New MySql.Data.MySqlClient.MySqlConnection(MySettings.Default.SqlConnection)
Using command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
con.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
ComboBox1.Text = reader.GetValue(2)
lblUser.Text = reader.GetValue(3)
End If
' NOTE: you dont need to close the reader/command/connection
' if you use the Using-statement, it will use Dispose even in case of an error
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I have a Windows Form app that is not properly validating the user input information. Need some help.
I inserted the Microsoft Login form and am writing code to verify the user credentials. Using an Access DB to store and retrieve info. Two tables - one for email address and another for password.
I verify format of the email addy using regex. This works very well.
I validate the email address is in correct form and verify it is in the table (this works well). Then I attempt to read the password (appears this is not working as expected) and then read both bits of information from the tables. Next, I test to make sure both are present. If both are present control is passed to another form.
My issue is reading/verifying the password.
Here is my Visual Studio VB.net code.
Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Try
If i = 0 Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'Change the following to your access database location
dataFile = "\11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
i = 1
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
'the query:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "'", myConnection)
Dim com As OleDbCommand = New OleDbCommand("SELECT * FROM [Password] WHERE [Password] = '" & txtPassword.Text & "'", myConnection2)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
Dim drp As OleDbDataReader = com.ExecuteReader()
' the following variable is hold true if EmailAddress is found, and false if EmailAddress is not found
Dim userFound As Boolean = False
' the following variable is hold true if Password is found, and false if Password is not found
Dim passwordFound As Boolean = False
' the following variables will hold the EmailAddress and Password if found.
Dim EmailAddressText As String = ""
Dim PasswordText As String = ""
'if found:
While dr.Read()
userFound = True
EmailAddressText = dr("EmailAddress").ToString
End While
While drp.Read()
passwordFound = True
PasswordText = drp("Password").ToString
End While
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
End Sub
Well first your approach isn't really safe due to the fact the the password isn't encrypted and that either there is no link between email and password ideally you would have table for example:
USER
--UID
--Email
PASS
--ID
--UID
--PASS
And you would hash your password for example sha512 furthermore for more security you would use Salt and certificates to secure the database connection.
Then you could do:
Hash current password in textbox and execute:
"SELECT USER.Email FROM USER,PASS WHERE USER.Email='TEXTBOX_EMAIL' AND USER.UID = PASS.UID"
Check if you have result if yes your connected.
However I tried to correct a bit what you did in the above code. Having used only SQLClient and not Olecommand i tried to keep what you did so there might be few syntax errors but should be ok:
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Dim passwordFound As Boolean
Dim userFound As Boolean
Using con As New SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =\ 11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb")
'Using to make sure connection is disposed
'Open connection
con.Open()
'Prepare sql
Dim command As New OleDbCommand("SELECT [emailAddress] FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "';", con)
'Create the reader
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim Id As String = ""
' Call Read before accessing data.
While reader.Read()
'Get data
Id = reader(0)
End While
'Close Reader
reader.Close()
If Id <> "" Then
'User found
userFound = True
'Prepare the second sql
Dim command2 As New OleDbCommand("SELECT [Password] FROM [Password] WHERE [Password] = '" & txtPassword.Text & "';", con)
'Prepare second reader
Dim reader2 As OleDbDataReader = command.ExecuteReader()
Dim Pass As String = ""
' Call Read before accessing data.
While reader2.Read()
'Get tdata
Pass = reader2(0)
End While
reader.Close()
If Pass <> "" Then
'Pass found
passwordFound = True
Else
passwordFound = False
End If
Else
userFound = False
End If
'Close connection
con.Close()
'Clear connection pool
SqlConnection.ClearPool(con)
End Using
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
Decided to combine the email and passwords into one table. Made everything easier for now. Thanks for your help and suggestions.
I have code which allows me to send an email to a customer using customer details in my database.
Try
mysqlconn.Open()
GetEmailCredentials(credentials)
query = "SELECT First_name, surname, email_address FROM customer,booking WHERE booking.BookingID='" & y & "' AND customer.customerID=booking.customerID"
command = New MySqlCommand(query, mysqlconn)
MsgBox("ref1")
reader = command.ExecuteReader
MsgBox("ref2")
While reader.Read()
MsgBox("ref3")
Try
MsgBox(reader.GetString("email_address") & reader.GetString("First_name") & reader.GetString("surname"))
MsgBox("ref4")
Dim emailmessage As New MailMessage()
emailmessage.From = New MailAddress(credentials(0))
emailmessage.To.Add(reader.GetString("email_address"))
emailmessage.Subject = "EHCC Booking"
emailmessage.Body = "Hello " & reader.GetString("First_name") & " " & reader.GetString("surname") & Environment.NewLine & "One of your bookings has been deleted." & Environment.NewLine & "Please contact me for further details."
Dim smtp As New SmtpClient("smtp.gmail.com")
smtp.Port = 587
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential(credentials(0), credentials(1))
smtp.Send(emailmessage)
MsgBox("ref5")
Catch ex As Exception
errors.Enqueue("Email details are incorrect")
End Try
mysqlconn.Close()
End While
Catch ex As MySqlException
errors.Enqueue(ex.Message)
Finally
mysqlconn.Dispose()
End Try
I keep on getting the error message 'Invalid attempt to Read when reader is closed'.
I get all of the reference message boxes popping up, along with the one that outputs the results of the query. The query orks fine so i have no idea whats happening. I can't see anywhere where i have closed the reader, until i have closed the mysqlconnection.
Im sorry if my explanation is clear.
Change this
While reader.Read()
...
mysqlconn.Close()
End While
To this
While reader.Read()
...
End While
mysqlconn.Close()
Is there a way in VB.Net to "Ping" an email address to see if that email is a real one that does not give any errors?
If yes, can you show what the VB.Net coding looks like to implement this?
I plan to use this in an app that requires the Customer email and it would be nice to validate it as the call taker enters it into a form before saving the Customer details.
Here is the code we are using to send an email promotion to all of the customers in our customer table:
Private Sub RibbonButtonSendTestEmail_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButtonSendTestEmail.Click
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
Dim strSqlStatement As String = "Select CustomerName, Email " & _
"From Customers "
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
With objSqlCommand
' Open the SqlConnection before executing the query.
'---------------------------------------------------
Cursor = Cursors.WaitCursor
ObjConnection.Open()
Dim objDataReader As SqlDataReader = .ExecuteReader()
' Go through all the customers and send out the promotion emails.
'----------------------------------------------------------------
If objDataReader.HasRows Then
SmtpServer.Host = TextBoxSMTPServer.Text
SmtpServer.Port = TextBoxPort.Text
If TextBoxUseSSL.Text = "Yes" Then
SmtpServer.EnableSsl = True
Else
SmtpServer.EnableSsl = False
End If
If TextBoxUseDefaultCredentials.Text = "Yes" Then
SmtpServer.UseDefaultCredentials = True
Else
SmtpServer.UseDefaultCredentials = False
End If
SmtpServer.Credentials = New Net.NetworkCredential(TextBoxUserName.Text, TextBoxPassword.Text)
While objDataReader.Read()
Try
mail.To.Add(objDataReader("Email").ToString)
mail.From = New MailAddress(TextBoxEmailFrom.Text)
mail.Subject = "Promotion: " & TextBoxID.Text
mail.Body = "Dear " & objDataReader("CustomerName") & "," & vbCrLf & vbCrLf & TextBoxPromotionBodyText.Text
SmtpServer.Send(mail)
Catch exSMTP As SmtpException
MessageBox.Show("Sorry, I could not send an email for: " & _
vbCrLf & objDataReader("CustomerName") & "." & vbCrLf & _
"Please make sure it is correct.", _
"Error")
Catch exFormat As FormatException
MessageBox.Show("Sorry, this customer's email is not properly formatted: " & _
vbCrLf & objDataReader("CustomerName") & "." & vbCrLf & _
"Please make sure it is correct.", _
"Error")
End Try
End While
LabelEmail.Text = "Sent email promotions to the customers."
End If
objDataReader.Close()
ObjConnection.Close()
Cursor = Cursors.Default
End With ' objSqlCommand
End Using ' objSqlCommand
End Sub
Yes it's perfectly possible:
1 DNS Lookup the MX records for the domain
There may be multiples, you can pick anyone, although technically the one with the lowest preference indicator is the prefered one.
2 TCP Connect to the mail server (port 25)
Say hello: HELO
Identify yourself: mail from:<test#example.com>
Say who you're writing to: rcpt to<testaddress#example.com>
At this point the server will reply with a response, you'll get an OK or a 550 error with a message (like: The email account that you tried to reach does not exist)
Disconnect and the message will be dropped.
But dude, you want the VB code to do this? You just need a DNS talking piece and TCP connection building piece (or likely there are some SMTP libraries out there that'll do all this for you - or provide you with inspiration to figure it out yourself). Don't forget you can probably find a C# code example that does it and use Visual Studio's conversion tool to switch it to VB.
Note
Many domains have black holes/catch alls... the former will accept any email address and just delete it if it's invalid, the latter will accept any email address and forward them to a central account (no guarantees as to what happens then... sell the sender's address to spammers?) In both cases you won't get the 550 message, so you can never be certain.
There most reliable way to do this is to send a test email and have the recipient verify receipt by clicking on a link, which you then read and mark the email as active.
You should do primitive checks on the syntax of the email using regular expressions, but beyond that the most reliable way to validate an email is to attempt delivery and confirm the receipt.