发送电子邮件时将body设置为html#

时间:2017-05-15 15:39:16

标签: c# html asp.net-mvc email

我正在调用一个在我的asp.net mvc项目中发送电子邮件的函数,我希望正文可以格式化为html

以下是我发送电子邮件的功能:

 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;
    }

电子邮件已发送,它的功能就像一个魅力,但它只是显示简单的HTML,所以我想知道我的MailMessage实例中的一个参数

2 个答案:

答案 0 :(得分:2)

您只需要将参数IsBodyHtml添加到MailMessage的实例中,如下所示:

 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;
    }

我还添加了一个try catch,因为如果在尝试发送邮件时出现问题,您可能会显示错误,或者只是知道在未使应用程序崩溃的情况下未发送电子邮件

答案 1 :(得分:0)

我认为您正在寻找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;
    }
相关问题