使用c#html格式发送邮件

时间:2016-02-20 18:48:39

标签: c# email smtpclient

我知道有很多类似的问题,但我似乎无法找到正确的答案。 所以在我的页面中我有CKEditorControl我想使用它的内容并将其作为文本发送。问题是电子邮件是与所有标签一起发送的,并且它们不会被渲染为纯文本。

  public class MailSender
{
    private readonly MailMessage mailMessage;
    private SmtpClient smtpClient;
    private string fromEmail = myMail;
    private string fromPass = myPass;

    public MailSender()
    {
        this.mailMessage = new MailMessage();

        this.mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        this.mailMessage.BodyEncoding = Encoding.UTF8;

        this.mailMessage.From = new MailAddress(MyMail);


    }

    public void Send(string subject, string body, params string[] to)
    {
        this.mailMessage.Body = body;           
        this.mailMessage.Subject = subject;
        this.mailMessage.IsBodyHtml = true;
        foreach (var mail in to)
        {
            this.mailMessage.To.Add(mail);
        }

        using (this.smtpClient = new SmtpClient("smtp.gmail.com", 25))
        {
            this.smtpClient.EnableSsl = true;
            this.smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            this.smtpClient.UseDefaultCredentials = false;
            this.smtpClient.Credentials = new NetworkCredential(this.fromEmail, this.fromPass);
            this.smtpClient.Send(this.mailMessage.From.ToString(), this.mailMessage.To.ToString(), this.mailMessage.Subject, this.mailMessage.Body);
        }

    }
}

这是负责发送电子邮件的班级。

1 个答案:

答案 0 :(得分:1)

这是我写的一段完美适合我的代码

Default.aspx的

<CKEditor:CKEditorControl ID="CKEditor1" BasePath="~/_Samples/ckeditor/" runat="server"></CKEditor:CKEditorControl>
    <asp:Button ID="SaveButton" runat="server" OnClick="SaveButton_Click" Text="Save Me" />

Default.aspx.cs

protected void SaveButton_Click(object sender, EventArgs e)
        {            
            Mail.SendMail("email@gmail.com", "cke", CKEditor1.Text);
        }

Email.cs

public static void SendMail(string To, string Subject, string Body)
        {
            MailMessage message = new MailMessage();
            message.From = new MailAddress(SmtpUserName, SmtpFrom);
            message.To.Add(new MailAddress(To));
            message.Subject = Subject;
            message.Body = Body;
            message.IsBodyHtml = true;
            message.BodyEncoding = Encoding.UTF8;
            message.SubjectEncoding = Encoding.UTF8;

            var client = new SmtpClient(SmtpAddress, SmtpPort)
            {
                Credentials = new NetworkCredential(SmtpUserName, SmtpPassword),
            };

            client.Send(message);            
        }

我使用了丰富的文本编辑器功能,粗体,斜体,颜色......并收到了大胆,斜体和彩色文本的电子邮件。