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

Asked

Viewed 902 times

0

My application takes some data that the user fills in the Textbox fields (txtEmpresa, txtContato, etc...) and sends it to a preconfigured email. I can send the data via smtp, but they are being sent without formatting. How to format data to be sent in a table format, for example:

inserir a descrição da imagem aqui

2 answers

3

Use HTML.

When sending the email, pass the generated HTML as the email text and enable the message body option as HTML. I do not know what you use to send email, so it is difficult to improve, if you give more details, help more. I can say that using the SmtpClient default. NET is just do mensagem.IsBodyHtml = true.

Writing 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, put tokens in place of the data (ex.: ##nome_empresa##) 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>

1

I do so:

Creation of HTML:

I don’t like writing HTML in C#. It gets 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). Then in it I create a string that is template for HTML.

inserir a descrição da imagem aqui

Then I make the replacement:

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

Sending - there are many ways to send as paid Apis or 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 HTML directly in a string. With the new string interpolation of C# 6.0 this is a little 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>";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.