views:

36

answers:

2

I am looking for a way to email all the values entered by a user into a form. Does this exist in asp.net ?

here is my email code:

 Dim messagemain As String = emailbody
        Dim message As New MailMessage()
        message.IsBodyHtml = True
        message.From = New MailAddress("[email protected]")
        message.To.Add(New MailAddress("[email protected]"))
        message.Subject = ("Response from form")
        message.Body = (messagemain)
        Dim client As New SmtpClient()
        client.Host = "email.foo.foo"
        client.Send(message)

I usually go through manually and ad all the necessaries to the emailbody var then send, but this form has over 200 fields.

Thanks.

+4  A: 

You may try too looping over the Controls collection of the page and if you find a textbox add its value to the mail body:

var body = new StringBuilder();
foreach (var control in pageInstance.Controls)
{
    if (control is TextBox)
    {
        var value = ((TextBox)control).Text;
        body.AppendFormat("value: {0}<br/>", HttpUtility.HtmlEncode(value));
    }
}
message.Body = body.ToString();

Remark: This will work only if the text boxes are directly placed on the page and not inside some other containers such as panels, ... In order to take this into account you could write a recursive function that visits all the controls.

Darin Dimitrov
Remember to HtmlEncode all values otherwise you are risking some nasty injection attacks into the email.
Dan Diplo
@Dan good point, I've updated my post to reflect your suggestion.
Darin Dimitrov
+2  A: 

Well instead of building it manually this migth help you if you need all values of the form.

var sb = new StringBuilder();
foreach (string key in this.Request.Form.Keys)
    sb.AppendFormat("{0} = {1}<br/>", key, this.Request.Form[key]);
var emailbody = sb.ToString();
Obalix