Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Multiple Textbox Values in Mail Body using SMTP

Guys I am trying to send mail through SMTP server. I am sending the mail using this code,

using(System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage())
{
    message.To.Add(textBox1.Text); //TextBox1 = Send To
    message.Subject = textBox2.Text; //TextBox2 = Subject
    message.From = new System.Net.Mail.MailAddress("email id");
    message.Body = textBox3.Text; //TextBox3 = Message Body

    using(System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
    {
        smtp.Host = "smtp.server.com";
        smtp.Credentials = new System.Net.NetworkCredential("user", "pass");
        smtp.Send(message);
    }
}

Now this code works perfectly. Now I want to send a whole form in the body of the mail, like selecting values of multiple textboxes. This is the form, I want to send in the mail :

enter image description here

How can I design a message template so that it may send a message with body containing all the values you see in the above form?

like image 525
NewbieProgrammer Avatar asked Feb 27 '14 11:02

NewbieProgrammer


Video Answer


1 Answers

Use StringBuilder and build up a string from all of your textboxes in the desired format and assign it to message.Body

If you want the output to be displayed like your form you can add HTML to the string which will be rendered by the e-mail client, however you cannot use CSS for styling.

As an example:

    private string BuildMessageBody()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("<html>");
        builder.Append("<body>");

        // Custom HTML code could go here (I.e. a HTML table).
        builder.Append(TextBox1.Text); // Append the textbox value

        builder.Append("</body>");
        builder.Append("</html>");

        return builder.ToString();
    }

Then you could do:

message.Body = BuildMessageBody();

Remember to set the IsBodyHtml property to true for your MailMessage:

message.IsBodyHtml = true;

You could get slightly more complicated and iterate over your form for all textbox controls and build the string up this way, which would be a good solution IMO - however this should provide a starting point for what you need to achieve.

like image 52
Darren Avatar answered Oct 13 '22 07:10

Darren