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

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.

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.

How to send mail smtp in local host by VB

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

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

Global.asax file not giving Exception Message

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");
}

Resources