【问题标题】:set body as html when sending email c# [duplicate]发送电子邮件时将正文设置为html c# [重复]
【发布时间】:2017-10-14 11:31:21
【问题描述】:

我正在调用一个在我的 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 实例中的一个论点

【问题讨论】:

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


    【解决方案1】:

    您只需将参数 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
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 2015-09-22
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2013-03-22
      • 2016-05-06
      • 2011-03-26
      相关资源
      最近更新 更多