Here's my problem I have some code and I'm using it to send an e-mail with the last error details but all I want is the (Inner)Exception Message to be displayed in the email with the URL
Here's my code
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Get current exception
Dim err As System.Exception = Server.GetLastError
Dim ErrorDetails As String = err.Exception.Message
Dim ErrorURL As String = Request.Url.ToString()
' Send notification e-mail
Dim Email As MailMessage = _
New MailMessage("email#email.co.uk", email#email.co.uk")
Email.IsBodyHtml = False
Email.Subject = "WEB SITE ERROR"
Email.Body = ErrorDetails & vbcrlf & vbcrlf & ErrorURL
Email.Priority = MailPriority.High
Dim sc As SmtpClient = New SmtpClient("localhost")
sc.Send(Email)
End Sub
Any help would be much appreciated
Thanks
Jamie
Use err.ToString() - this gives you the full strack trace and inner exceptions.
If you really only want the inner exception error message, use err.InnerException.Message
protected void Application_Error(object sender, EventArgs e)
{
MailMessage msg = new MailMessage();
HttpContext ctx = HttpContext.Current;
msg.To.Add(new MailAddress("me#me.com"));
msg.From = new MailAddress("from#me.com");
msg.Subject = "My app had an issue...";
msg.Priority = MailPriority.High;
StringBuilder sb = new StringBuilder();
sb.Append(ctx.Request.Url.ToString() + System.Environment.NewLine);
sb.Append("Source:" + System.Environment.NewLine + ctx.Server.GetLastError().Source.ToString());
sb.Append("Message:" + System.Environment.NewLine + ctx.Server.GetLastError().Message.ToString());
sb.Append("Stack Trace:" + System.Environment.NewLine + ctx.Server.GetLastError().StackTrace.ToString());
msg.Body = sb.ToString();
//CONFIGURE SMTP OBJECT
SmtpClient smtp = new SmtpClient("myhost");
//SEND EMAIL
smtp.Send(msg);
//REDIRECT USER TO ERROR PAGE
Server.Transfer("~/ErrorPage.aspx");
}
Related
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, 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"
Imports System.Net.Mail
Partial Class ch5_proj4_ch5_proj4
Inherits System.Web.UI.Page
Protected Sub EmailBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles EmailBtn.Click
' insert code here
Dim MySmtpClient As New SmtpClient()
Dim MM As New MailMessage()
Try
MySmtpClient.Host = "stmp.gmail.com"
MySmtpClient.Port = 587
MySmtpClient.EnableSsl = True
MySmtpClient.UseDefaultCredentials = True
MySmtpClient.Credentials = New System.Net.NetworkCredential()
'mail message
MM.To.Add(New MailAddress(TextBox2.Text, TextBox1.Text))
Dim fromAddress As New MailAddress(TextBox4.Text, TextBox3.Text)
MM.From = fromAddress
MM.Subject = TextBox4.Text
MM.IsBodyHtml = RadioButtonList1.SelectedValue
MM.Body = txtMessage.Text
MySmtpClient.Send(MM)
Label5.Text = "Email successfully sent."
Catch exc As Exception
Label5.Text = "Send email failed" + exc.Message
End Try
MM = Nothing
MySmtpClient = Nothing
End Sub
End Class
What am I doing wrong? Every time I do it I have an error
"Send email failed Conversion from string "" to type 'Boolean' is not valid."
Please help.
Try to change this MM.IsBodyHtml = RadioButtonList1.SelectedValue to this MM.IsBodyHtml = If(RadioButtonList1.SelectedValue = "True",True,False)
I made this simple mailing application but problem is recipients gets email twice.
This is my code on button click
Protected Sub submit_feedback_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit_feedback.Click
Dim feedback As String = "<b>Client Name :</b><br/>" + ParseOutput.Text + "<br/><br/> <b>Clients Experience :</b><br/>" + brief_details.Text + "<br/><br/> <b>Improvement Needed :</b><br/>" + brief_details2.Text + "<br/><br/> <b>Rating Given :</b><br/>" + rate1.SelectedValue.ToString + "<br/><br/> <b>How do you know about us :</b><br/>" + choice2.SelectedValue.ToString
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient()
mail.To.Add("surajprince20#gmail.com")
mail.From = New MailAddress("something#gmail.com", "SuRaj_ Email Test")
mail.Subject = "Feedback - Reply From Client "
mail.Body = feedback
mail.IsBodyHtml = True
SmtpServer.Port = 25
SmtpServer.Credentials = New System.Net.NetworkCredential("something#gmail.com", "1234")
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
SmtpServer.Send(mail)
Try
SmtpServer.Send(mail)
Response.Write("Successfull")
Catch ex As SmtpException
Response.Write(ex)
End Try
End Sub
It is clear from your code that you are sending the mail twice, have a look into your code:
SmtpServer.Send(mail) '<----- first sending attempt
Try
SmtpServer.Send(mail)'<----- second sending attempt
Response.Write("Successfull")
Catch ex As SmtpException
Response.Write(ex)
End Try
so you need to remove the SmtpServer.Send(mail) which is placed outside the TRY
ie.,
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Try ' <------ eleminate one line
SmtpServer.Send(mail)
Response.Write("Successfull")
Catch ex As SmtpException
Response.Write(ex)
End Try
SmtpServer.Send(mail)
Try
SmtpServer.Send(mail)
you are acutally sending the mail twice
Protected Sub submit_feedback_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit_feedback.Click
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New System.Net.NetworkCredential("something#gmail.com", "1234")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
mail = New MailMessage()
mail.From = New MailAddress("something#gmail.com", "SuRaj_ Email Test")
mail.To.Add("surajprince20#gmail.com")
mail.Subject = "Feedback - Reply From Client "
mail.Body = feedback
SmtpServer.Send(mail)
MsgBox("mail send")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
END SUB
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