Sending a Data List by Email - ASP.NET MVC C#

Asked

Viewed 99 times

0

Good evening, I’m making a web application for college where I need to send a list of data (food) coming from a quote. That is, the user selects the items that will quote and after this sends via email to the desired email, the question is: The sending of the email is being done normally, the problem is that when my email arrives at the Food List, only the following information arrives:

From: [email protected]

For: [email protected]

System.Collections.Generic.List`1[Projectocotacao2.Models.Food]

We appreciate the contact!

When debugging, I see that the items are returning correctly but it is not sent in the email... I thought of making a foreach inside the body of the email but I was not successful, follow the method in the controller:

   [HttpPost]
 public ActionResult EnviarEmail(UsuarioCliente cotacao)
    {

        String email = cotacao.Email_Cliente;
        String assunto = "ASSUNTO EMAIL";

        List<Alimento> a = new List<Alimento>();
        a = AlimentoDAO.RetornarAlimentos();



        WebMail.SmtpUseDefaultCredentials = false;
        WebMail.SmtpServer = "smtp.gmail.com";
        WebMail.SmtpPort = 587;
        WebMail.EnableSsl = true;
        WebMail.UserName = "[email protected]";
        WebMail.Password = "senha";
        WebMail.From = "[email protected]";


        try
        {
            WebMail.Send(to: email,
                from: "[email protected]"",
                   subject: assunto,
                   body: a +
                   "<p> Agradecemos o contato!</p>"
                   );
            return RedirectToAction("Login", "UsuarioCliente");
        }
        catch
        {
            return RedirectToAction("Create", "UsuarioCliente");
        }
    }

The DAO layer:

        public static List<Alimento> RetornarAlimentos()
    {
        return ctx.Alimentos.Include("Categoria").ToList();
    }

I appreciate the help from now on, thank you all very much!

  • because the body is a string type, and you are passing a list, it will not work at all. Test create a string with the data you have in the List that will work

  • Yes, if I assign will work to a string will work... but it turns out I have no way to predict how many products will come from that list... so I have no way to predict how many string’s create

  • "so I can’t predict how many string’s to create", you only need one variable, make one foreach in the list and adds string, or rather, a StringBuilder and uses only this variable

2 answers

1


The error is because you try to concatenate a variable of type List<> with a string. You must assemble a string containing the list information and then throw it into the friend string.

 string alimentos = string.Empty;

for (int i = 0; i < a.Count; i++)
{
   alimentos += string.Format("Nome do alimento: {0}, Categoria do alimento: {1}{2}", a[i].Nome, a[i].Categoria, Environment.NewLine);
}

if (string.IsNullOrEmpty(alimentos))
   alimentos = "Nenhum alimento encontrado";

try
{
   WebMail.Send(to: email,
                from: "[email protected]"",
                subject: assunto,
		body: alimentos +
	       "<p> Agradecemos o contato!</p>"
					);
   return RedirectToAction("Login", "UsuarioCliente");
}
catch
{
   return RedirectToAction("Create", "UsuarioCliente");
}

  • It worked, thank you!

  • Don’t forget to dial as an answer to help other people who have the same question

  • 1

    All right, thank you very much!

0

You can include the JSON serialization library most used in the Dotnet architecture, and serialize your list in a string, here’s an example:

using Newtonsoft.Json;

string suaListaSerializada = JsonConvert.SerializeObject(suaLista);

I hope I’ve helped.

  • Error after serializing: Server Error in Application/'. Self referencing loop Detected with type 'Projectocotacao2.Models.Food'. Path '[0].estabelecimento.alimentos'. Description: An untreated exception occurred during the execution of the current web request. Examine stack tracking for more information about the error and where it originated in the code. Exception Details: Newtonsoft.Json.Jsonserializationexception: Self referencing loop Detected with type 'Projectocotacao2.Models.Food'. Path '[0].estabelecimento.alimentos'. Error of Origin:

Browser other questions tagged

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