How to send mail smtp in local host by VB - asp.net

I have used VB.net for my project, ticketing system, where you add new ticket it should be sending mail to some Emails I have defined in other class
but I have silly problem, which is sending mail through local host.
is there any suggestion from this source code, when I uploaded to specific domain it works, but for localhost not working with me which that I don't receive any mail when I run my project
I want to send mail from localhost
Private Function SendConfirmationEmail(ByVal EmailAddress As String, ByVal Operation As String, ByVal CorreCode As String, ByVal CorrSubj As String, ByVal CutName As String, ByVal phone As String, ByVal CustomerEmail As String) As Boolean
''''''''''''''''''''''Getting Email Setting Information'''''''''''''''''''''''''''''''''''''''
Try
Dim FromMail As String = System.Configuration.ConfigurationManager.AppSettings.GetValues("DefualtMail")(0).ToString()
Dim PassMail As String = System.Configuration.ConfigurationManager.AppSettings.GetValues("DefualtMailPass")(0).ToString
Dim SenderName As String = "Customer Managment Team"
Dim SMTPHost As String = System.Configuration.ConfigurationManager.AppSettings.GetValues("SMTPHost")(0).ToString
''''''''''''''''''''''''''''''''''''Sending Emails'''''''''''''''''''''''''''''''''''''''''''''''''
Dim Mail As New MailMessage
Dim Body As String = ""
Dim Subject As String = Operation
Dim SendTo As String = EmailAddress
''''''''''''''''''''''''''''''''''E-mail'''''''''''''''''''''''''''''''''''''
If SendTo <> vbNullString Then
Mail.To.Clear()
Mail.CC.Clear()
Mail.Bcc.Clear()
Mail.To.Add(SendTo)
Mail.From = New MailAddress(FromMail, "Ticket Code : " + CorreCode)
Mail.IsBodyHtml = True
Dim reader As StreamReader
reader = New StreamReader(Server.MapPath("Index.html"))
Body = reader.ReadToEnd
Body = Body.Replace("MessageSubject", Operation)
Body = Body.Replace("Description", "description : " + CorrSubj)
Body = Body.Replace("customer_info", "Customer Name : " + CutName)
Body = Body.Replace("phone_number", "Customer Phone : " + phone)
Body = Body.Replace("email_address", "Customer address : " + CustomerEmail)
' Body = Body.Replace("PropertyTitle", "Ticket Code :" + CorreCode + " Ticket Description :" + CorrSubj + " Customer info : " + CutName + " phone number : " + phone + " email_address : " + EmailAddress)
Mail.Body = Body
' "<html dir='ltr'><body><h1>Confirmation</h1><br/> Please confirm you email at this link <br/> <a href='108.60.209.97/enmaa/ConfirmEmail.aspx/Enmaa0000" + ApproveId + "'>Confirm</a></body></html>"
Mail.Subject = Subject
'######################################## Sending The EMail########################################################
Dim SMTP As New SmtpClient(SMTPHost)
SMTP.Credentials = New System.Net.NetworkCredential(FromMail, PassMail)
SMTP.Host = SMTPHost
SMTP.Port = 587 '587
SMTP.EnableSsl = True
SMTP.Send(Mail)
End If
Return True

Related

SMTP Email Works until triggering a 404 error in the middle of sending Mail

I have a table for email recipients imma database, and use the "select all" button from the gridview table as trigger to call the mail function. my iteration func to call the 'executeApprove' repeatedly described here :
For Each row In gridApproval.Rows
chkApprove = CType(gridApproval.Rows(i).FindControl("chkApprove"), CheckBox)
If chkApprove.Checked Then
executeApprove(Right(lblTglProses.Text, 8), Left(gridApproval.Rows(i).Cells.Item(2).Text, 3), Session("role"), "APPROVE", Session("userID"), False)
End If
i = i + 1
Next
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me.UpdatePanel1, Me.GetType, "Message", "alert('Error : ' + '" & Replace(Replace(ex.Message.ToString, "'", ""), vbNewLine, "") & "');", True)
End Try
gridApproval.DataBind()
End If
on my executeApprove :
Protected Sub executeApprove(ByVal tanggal As String, ByVal branch As String, ByVal role As String, ByVal status As String, ByVal user As String, ByVal isDone As Boolean)
Dim Title As String
Dim Body As String
Try
conn = run.connect(conn, "open")
cmd = New SqlCommand("usp_status_trial", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandTimeout = 0
cmd.Parameters.Add("#date", SqlDbType.VarChar).Value = tanggal
cmd.Parameters.Add("#branch", SqlDbType.VarChar).Value = branch
cmd.Parameters.Add("#role", SqlDbType.VarChar).Value = role
cmd.Parameters.Add("#status", SqlDbType.VarChar).Value = status
cmd.Parameters.Add("#user", SqlDbType.VarChar).Value = user
reader = cmd.ExecuteReader
If reader.HasRows Then
reader.Read()
result = reader.Item(0).ToString
ScriptManager.RegisterStartupScript(Me.UpdatePanel1, Me.GetType, "Message", "alert('" & result & "');", True)
If result = "APPROVED" Then
If Session("role") = "APP" Then
Title = "Title Email"
Body = "Body Email"
sendMultipleMail(Title, Body)
End If
ElseIf result = "UNAPPROVED" Then
If Session("role") = "APP" Then
Title = "Title Email"
Body = "Body Email"
sendMultipleMail(Title, Body)
End If
End If
If isDone Then
Response.Redirect("~/dashboard.aspx?id=" + Request.QueryString("id"), True)
End If
End If
conn = run.connect(conn, "close")
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me.UpdatePanel1, Me.GetType, "Message", "alert('Error : ' + '" & Replace(Replace(ex.Message.ToString, "'", ""), vbNewLine, "") & "');", True)
End Try
End Sub
and my sendMultipleMail :
Public Sub sendMultipleMail(ByVal subject As String, ByVal body As String)
Dim dsMail As New DataSet
Dim strQuery As New SqlCommand
Dim SendFrom As MailAddress
Dim SendTo As MailAddress
Dim emailClient As SmtpClient
Dim SMTP As String
Dim mailFrom As String
SMTP = getAppParam("SMTPserver") 'got the SMTP
mailFrom = getMailSetting("mailFrom")
strQuery.CommandText = "%'Query for select all the receiver'%"
dsMail = RunQuery(strQuery)
For Each rowMail In dsMail.Tables(0).Rows
SendFrom = New MailAddress(mailFrom)
SendTo = New MailAddress(rowMail("mail_address").ToString())
Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo)
MyMessage.Subject = subject
MyMessage.Body = body
emailClient = New SmtpClient(SMTP)
emailClient.Send(MyMessage)
Next
End Sub
everything works just fine until a few minutes while sending the lot of email (in the middle of calling the func repeatedly), the IIS returning a strange 404 response.
POST http://localhost/myApp/approval?type=all&id=userid 500 (Internal
Server Error) -- MicrosoftAjax.js:6
Uncaught TypeError: Cannot read properties of undefined (reading 'PRM_ServerError')
at Sys.WebForms.PageRequestManager._createPageRequestManagerServerError
(MicrosoftAjaxWebForms.js:6:11462)
at Sys.WebForms.PageRequestManager._onFormSubmitCompleted (MicrosoftAjaxWebForms.js:6:25554)
at Array. (MicrosoftAjax.js:6:307)
at MicrosoftAjax.js:6:51370
at Sys.Net.WebRequest.completed (MicrosoftAjax.js:6:89678)
at XMLHttpRequest._onReadyStateChange (MicrosoftAjax.js:6:84277)
am I made some mistakes?
Thank you for the answer. Error 404 appears just because the SMTP takes a lot of time to send a whole of email to the receiver. so i've been fixing them using
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="3000000000" />
</requestFiltering>
</security>
inside .config file to increase the timeout.

I am trying to send emails through gmail host by using google oauth 2.0, where to use the access code instead of user password to send emails

I am trying to send emails through gmail host by using google oauth 2.0, I am confused where to use the access code instead of user password to send emails,
this code is used to open up the consent screen and ask for permissions,
Dim Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" & googleplus_redirect_url & "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20https://mail.google.com/%20https://www.googleapis.com/auth/gmail.send&client_id=" + googleplus_client_id
Session("loginWith") = "google"
Response.Redirect(Googleurl)
after getting permissions, this is how I obtained access code,
If url <> "" Then
Dim queryString As String = url.ToString()
Dim delimiterChars As Char() = {"="c}
Dim words As String() = queryString.Split(delimiterChars)
Dim code As String = words(1)
If code IsNot Nothing Then
Dim webRequest As HttpWebRequest = CType(webRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
webRequest.Method = "POST"
Parameters = "code=" & code & "&client_id=" & googleplus_client_id & "&client_secret=" + googleplus_client_secret & "&redirect_uri=" + googleplus_redirect_url & "&grant_type=authorization_code"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(Parameters)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.ContentLength = byteArray.Length
Dim postStream As Stream = webRequest.GetRequestStream()
postStream.Write(byteArray, 0, byteArray.Length)
postStream.Close()
Dim response As WebResponse = webRequest.GetResponse()
postStream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(postStream)
Dim responseFromServer As String = reader.ReadToEnd()
Dim serStatus As GooglePlusAccessToken = JsonConvert.DeserializeObject(Of GooglePlusAccessToken)(responseFromServer)
If serStatus IsNot Nothing Then
Dim accessToken As String = String.Empty
accessToken = serStatus.access_token
If Not String.IsNullOrEmpty(accessToken) Then
getgoogleplususerdataSer(accessToken)
End If
End If
End If
End If
and using the below code to send emails:
mm.Subject = LetterSubject.Text
Dim body As String
body = LetterBody.Text
mm.Body = body
Dim smtp As New Mail.SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Port = 587
smtp.UseDefaultCredentials = False
Dim service = New GmailService(New BaseClientService.Initializer With {.HttpClientInitializer = cred})
Dim NetworkCred As New NetworkCredential(SenderEmailAddress.Text, SenderPassword.Text)
smtp.Credentials = NetworkCred
smtp.Send(mm)
Can someone please help me how to use token here to send emails without using the user gmail password?
Imports System
Imports System.Threading.Tasks
Imports Google.Apis.Discovery.v1
Imports Google.Apis.Discovery.v1.Data
Imports Google.Apis.Services
Class Program
<STAThread>
Private Shared Sub Main(ByVal args As String())
Console.WriteLine("Discovery API Sample")
Console.WriteLine("====================")
Try
New Program().Run().Wait()
Catch ex As AggregateException
For Each e In ex.InnerExceptions
Console.WriteLine("ERROR: " & e.Message)
Next
End Try
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Async Function Run() As Task
Dim service = New DiscoveryService(New BaseClientService.Initializer With {
.ApplicationName = "Discovery Sample",
.ApiKey = "[YOUR_API_KEY_HERE]"
})
Console.WriteLine("Executing a list request...")
Dim result = Await service.Apis.List().ExecuteAsync()
If result.Items IsNot Nothing Then
For Each api As DirectoryList.ItemsData In result.Items
Console.WriteLine(api.Id & " - " + api.Title)
Next
End If
End Function
End Class
''Your Authentication key should be static
''Dim NetworkUserName As String= "apikey"
' Dim YOUR_API_KEY_HERE As String = "SG.EEyBZDVAS622C6Rt7yu1sw.jwRdfkjJddfsJfgfsyuJuyuHutytr876RuQsffhghdf1d"

How to Send email with High Importance in asp.net VB

How do I set the code below to generate email with high priority in the subject line? Thank you for any guidance.
Private Sub SendEmail(ByVal pharmEmail As String, ByVal backupEmail As String)
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim message As New System.Net.Mail.MailMessage()
Try
Dim fromAddress As New System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings("EmailFromAddr"), WebConfigurationManager.AppSettings("EmailFromName"))
message.From = fromAddress
message.To.Add(pharmEmail)
message.Subject = WebConfigurationManager.AppSettings("EmailSubject")
If (WebConfigurationManager.AppSettings("backupEnabled") = True) Then
message.CC.Add(backupEmail)
End If
message.IsBodyHtml = True
Dim orderURL As New HyperLink
orderURL.Text = "here"
orderURL.NavigateUrl = "http://" & WebConfigurationManager.AppSettings("ServerName") & "/User/ReviewOrder.aspx?orderID=" & webOrderID
message.Body = "An order was created using the account of " + Profile.FirstName.ToString() + " " + Profile.LastName.ToString() + ". " + WebConfigurationManager.AppSettings("EmailBody") + "<a href='" + orderURL.NavigateUrl + "'>here.</a>"
'message.Body = WebConfigurationManager.AppSettings("EmailBody") & " " & orderURL.
smtpClient.Send(message)
Catch ex As Exception
ErrorHandler.WriteError(ex.ToString)
Throw ex
End Try
I believe you can set the Priority property on the MailMessage. See MSDN for more details.

Creating User twice in sql server for new registration

I'm trying to create a new user and everything works fine but it enters the same records twice to my db. I have already tried to kept some breakpoints but couldn't find where am I going wrong.
This is my Registration.aspx code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim msg As MailMessage
Dim UserID As String
Dim ActivationUrl As String = String.Empty
Dim emailId As String = String.Empty
UserID = Guid.NewGuid.ToString
'Create ConnectionString and Inser Statement
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO Users (UserID,UserName,Password,Email,Mobile,Address,CreatedDate)" & " values (#UserID,#UserName,#Password,#Email,#Mobile,#Address,#CreatedDate)"
'Create SQL connection
Dim con As New SqlConnection(connectionString)
'Create SQL Command And Sql Parameters
Dim cmd As New SqlCommand(insertSql, con)
Dim usernumber As New SqlParameter()
usernumber.ParameterName = "#UserID"
usernumber.Value = UserID
cmd.Parameters.Add(usernumber)
Dim username As New SqlParameter()
username.ParameterName = "#Username"
username.Value = txtUserName.Text.ToString()
cmd.Parameters.Add(username)
Dim password As New SqlParameter()
password.ParameterName = "#Password"
password.Value = txtPassword.Text.ToString()
cmd.Parameters.Add(password)
Dim email As New SqlParameter()
email.ParameterName = "#Email"
email.Value = txtEmail.Text.ToString()
cmd.Parameters.Add(email)
Dim mobile As New SqlParameter()
mobile.ParameterName = "#Mobile"
mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(mobile)
Dim address As New SqlParameter()
address.ParameterName = "#Address"
address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(address)
Dim createddate As New SqlParameter()
createddate.ParameterName = "#CreatedDate"
createddate.Value = Date.Now.ToString("MM/dd/yyyy hh:mm:ss tt")
cmd.Parameters.Add(createddate)
Try
con.Open()
cmd.ExecuteNonQuery()
lblMsg.Text = "User Registration successful"
Catch ex As SqlException
Dim errorMessage As String = "Error in registering user"
errorMessage += ex.Message
Throw New Exception(errorMessage)
Finally
con.Close()
End Try
Try
'Sending activation link in the email
msg = New MailMessage()
Dim smtp As New SmtpClient()
emailId = txtEmail.Text.Trim()
'sender email address
msg.From = New MailAddress("voletykiran#gmail.com")
'Receiver email address
msg.[To].Add(emailId)
msg.Subject = "Confirmation email for account activation"
'For testing replace the local host path with your lost host path and while making online replace with your website domain name
ActivationUrl = Server.HtmlEncode("http://localhost:8769/UserRegistration/ActivateAccount.aspx?UserID=" & FetchUserId(emailId) & "&Email=" & emailId)
msg.Body = "Hi " & txtUserName.Text.Trim() & "!" & vbLf & "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!"
msg.IsBodyHtml = True
smtp.Credentials = New NetworkCredential("voletykiran#gmail.com", "india#1a")
smtp.Port = 587
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Send(msg)
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Confirmation Link to activate account has been sent to your email address');", True)
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
ActivationUrl = String.Empty
emailId = String.Empty
con.Close()
End Try
End Sub
Private Function FetchUserId(emailId As String) As String
Dim cmd As New SqlCommand()
cmd = New SqlCommand("SELECT UserID FROM users WHERE Email=#Email", con)
cmd.Parameters.AddWithValue("#Email", emailId)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim UserID As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return UserID
End Function
Private Sub clear_controls()
txtUserName.Text = String.Empty
txtPassword.Text = String.Empty
txtConfirmPassword.Text = String.Empty
txtEmail.Text = String.Empty
txtMobile.Text = String.Empty
txtAddress.Text = String.Empty
txtUserName.Focus()
End Sub
Can anyone say me where am I misleading?

The parameter 'from' cannot be an empty string. Parameter name: from

Ok, so basically I have a comments form on my website. People but comments in the comment box and it emails the comments to my email. The email part works fine and goes through. However, the error comes when I try to clear the form fields. It gives me an error saying:
Error: The parameter 'from' cannot be an empty string.
Parameter name: from
So anyone have any thoughts? like I said the email part works fine its just clearing the fields is giving me trouble
here is the code:
Imports System.Web.Mail
Imports System.Text
Partial Class Pages_ContactUs : Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim body As String = "From: " + YourName.Text + " " + Environment.NewLine + "Email: " + YourEmail.Text + Environment.NewLine + Environment.NewLine + "Message: " + Environment.NewLine + Comments.Text
Dim MM As New System.Net.Mail.SmtpClient
MM.EnableSsl = True
MM.Host = "smtp.gmail.com"
Dim cred As New System.Net.NetworkCredential("myEmail#gmail.com", "myPassword")
MM.Credentials = cred
MM.Send(YourEmail.Text, "myEmail#gmail.com", Subject.Text, body)
ClearFields()
lblEmail.ForeColor = Drawing.Color.Green
lblEmail.Text = "Your message has been sent successfuly"
lblEmail.Visible = True
End Sub
Protected Sub ClearFields()
YourName.Text = ""
YourEmail.Text = ""
Comments.Text = ""
Subject.Text = ""
End Sub
End Class
You must supply it, just make it yours. Basic pattern:
Using SmtpServer As New SmtpClient()
Using mail As New System.Web.Mail.MailMessage()
Try
SmtpServer.UseDefaultCredentials = True
SmtpServer.EnableSsl = True
SmtpServer.Credentials = New Net.NetworkCredential(un, pw)
SmtpServer.Port = 25
SmtpServer.Host = "smtp.address"
mail.From = New MailAddress(sender)
mail.To.Add(some address)
mail.Subject = subject
mail.Body = body
mail.Sender = New MailAddress(sender)
SmtpServer.Send(mail)
Catch
End Try
End Using
End Using

Resources