How to send fields of a form by email in the format of a table?

0

My application takes some data that the user fills in the TextBox fields (txtCompany, txtContact, etc ...) and sends them to a preconfigured email. I can send the data through smtp, but are being sent without formatting. How to format the data to be sent in the format of a table, for example:

    
asked by anonymous 04.11.2016 / 18:11

2 answers

3

Use HTML.

At the time of sending the email, pass the generated HTML as email text and enable the message body option as HTML. I do not know what you use to send email, so it gets difficult to improve, if you give more details, I'll help you more. I can tell you that using%% default .NET is just SmtpClient .

To write the HTML code in the code itself can be bad and disorganized, you can use templates for this. If you want to opt for simplicity, you can create an HTML file, place tokens in place of the data (eg mensagem.IsBodyHtml = true ) and replace before sending. You can use PostalMvc and several other libraries.

<table>
    <thead>
        <tr> 
            <th>Empresa</th>
            <!-- seguir criando os TH's -->
        <tr>
    <thead>
    <tbody>
        <tr> 
            <td>Nome da empresa</td>
            <!-- seguir criando os TD's -->
        <tr>
    <tbody>
</table>
    
04.11.2016 / 18:18
1

I do this:

Creating HTML:

I do not like writing HTML in C # code. It is bad to read and maintain in my opinion, especially when it has many attributes and CSS and has to be giving escape in the strings. I create a Resource.resx file (Add New Item, Resource File). So in it I create a string that is a template for HTML.

ThenI'lldothereplacement:

stringstrMensagem=Resource.htmlEmail;strMensagem=strMensagem.Replace("{nome}", txtNome.Text);
strMensagem = strMensagem.Replace("{contato}", txtTelefone.Text);

Send - there are several ways to send as per paid APIs or by SMTP-Client

var email = new MailMessage();
var strSenha = "aaaaa";
using (var smtp = new SmtpClient("smtp.gmail.com", 587))
{
   smtp.Credentials = new NetworkCredential("[email protected]", strSenha);
   smtp.EnableSsl = true;
   email.To.Add(strDestinatario);
   email.IsBodyHtml = true;
   email.Subject = strAssunto;
   email.Body = strMensagem;
   smtp.Send(email);
}

As I said this is the way I like to do it, but you could create the direct HTML in a string. With the new string interpolation of C # 6.0 this gets a bit easier.

string html = "<table>" +
              " <thead>" + 
              "  <tr>" +
              "   <th>Empresa</th>" +
              "   <th>Contato</th>" +
              "  </tr>" +
              " </thead>" +
              " <tbody>" +
              "  <tr>" +
             $"   <td>{txtNome.Text}</td>" +
             $"   <td>{txtTelefone.Text}</td>" +
              "  </tr>" +
              " </tbody>" +
              "</table>";
    
04.11.2016 / 20:15