user1342164 user1342164 - 3 months ago 40
Vb.net Question

System.Net.Mail New MailMessage randomly sending duplicate emails?

I am using the code below to generate an email. For some reason, randomly it will send a duplicate email out. It does not happen all the time, just a couple times a month. Do you see anything with my code that might cause this? It is fired when the user clicks a submit button on the page. Is there something I can add to this to prevent this from happening? TIA

Try
Dim Attachment As String
Attachment = path + myUniqueFileName

Dim mailMessage As MailMessage = New MailMessage
mailMessage.From = New MailAddress("Test@Test.com")
mailMessage.Subject = "Report " + " " + myUniqueFileName
mailMessage.IsBodyHtml = True
mailMessage.To.Add(New MailAddress(Session("EmailAddress")))
mailMessage.Attachments.Add(New Attachment(Attachment))
mailMessage.Body = "Attached is your report"

Dim smtp As SmtpClient = New SmtpClient

smtp.Host = "mail.net"

Dim NetworkCred As System.Net.NetworkCredential = New System.Net.NetworkCredential

smtp.Credentials = New NetworkCredential("test", "test")
smtp.UseDefaultCredentials = False
smtp.Send(mailMessage)

Catch ex As Exception

Dim message As String = ex.ToString
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload=function(){")
sb.Append("alert('")
sb.Append(message)
sb.Append("\n")
sb.Append(String.Format("{0:f2}", Convert.ToDouble(TotalAmount)))
sb.Append("')};")
sb.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())

End Try


Image Button Code:

<asp:ImageButton ID="cmdFinish" runat="server" Height="38px" ImageUrl="~/Images/Finish.png" Width="99px" UseSubmitBehavior="false" OnClientClick="this.disabled = true; this.value = 'Sending...';" Text="Send" />

Answer

I've experienced the same issue before, so I think I might share my solution:

This is my mark-up code for the button to avoid re-clicking it again:

<asp:Button ID="btnSend" runat="server" CssClass="btn btn-primary" Width="150px" UseSubmitBehavior="false" OnClientClick="this.disabled = true; this.value = 'Sending...';" Text="Send" />

Notice OnClientClick="this.disabled = true; this.value = 'Sending...'.

It will disable your button and change its text after clicking it.

Also, to avoid re-saving/resubmission/resending of data when the page is refreshed, I just recalled my form:

Response.Redirect("~/yourForm.aspx")