-1

I am calling a function that sends an email in my asp.net mvc project and I want the body to be able to format as html

Here is my function that sends the email :

 private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
    {
        SmtpClient smtp = new SmtpClient();
        MailMessage msg = new MailMessage
        {
            From = new MailAddress(envoyeur),
            Subject = object,
            Body = text,         
        };

        if (atache != null)
            msg.Attachments.Add(atache);

            msg.To.Add(adrCourriel);
            smtp.Send(msg);


        return;
    }

The email is sent and it works like a charm, but It just shows plain html so I was wondering an argument in my instanciation of MailMessage

Marc-Antoine
  • 23
  • 1
  • 1
  • 9

2 Answers2

2

You just need to add the parameter IsBodyHtml to your instanciation of the MailMessage like this :

 private bool EnvoieCourriel(string adrCourriel, string corps, string objet, string envoyeur, Attachment atache)
    {
        SmtpClient smtp = new SmtpClient();
        MailMessage msg = new MailMessage
        {
            From = new MailAddress(envoyeur),
            Subject = objet,
            Body = corps,
            IsBodyHtml = true
        };

        if (atache != null)
            msg.Attachments.Add(atache);

        try
        {
            msg.To.Add(adrCourriel);
            smtp.Send(msg);
        }
        catch(Exception e)
        {
           var erreur = e.Message;
            return false;
        }

        return true;
    }

I also added a try catch because if there is a problem when trying to send the message you can show an error or just know that the email was not sent without making the application crash

Louis-Roch Tessier
  • 822
  • 1
  • 13
  • 25
0

I think you are looking for IsBodyHtml.

 private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
    {
        SmtpClient smtp = new SmtpClient();
        MailMessage msg = new MailMessage
        {
            From = new MailAddress(envoyeur),
            Subject = object,
            Body = text,
            IsBodyHtml = true
        };

        if (atache != null)
            msg.Attachments.Add(atache);

            msg.To.Add(adrCourriel);
            smtp.Send(msg);


        return;
    }
Chad
  • 872
  • 8
  • 24