【问题标题】:Is the MailDefinition Class only for use with ASP?MailDefinition 类是否仅用于 ASP?
【发布时间】:2012-07-30 13:52:46
【问题描述】:

MailDefinition 类是否仅用于 ASP?它似乎拥有我需要的一切,但显然我需要在 Web.Config 文件中添加 SMTP 服务器信息。我想在 WinForms 应用程序中使用这个类。这可能吗?

谢谢

【问题讨论】:

  • 为什么要使用 MailDefinition 类?您可以使用 System.Net 中的 MailMessage 类吗?
  • MailDefinition 允许使用外部 HTML 文件,还可以让您随时编辑 HTML 模板的外观,而无需重新构建和部署您的应用程序

标签: c# winforms email smtp


【解决方案1】:

当然,您应该可以在 WinForms 应用程序中使用它。您需要将 SMTP 主机名传递给 System.Net.Mail.SmtpClient 构造函数。像这样的:

using System.Net.Mail;
using System.Web.UI.WebControls;

// namespace etc

private void SendEmail()
{
    string to = "to@somewhere.com,to2@somewhere.com";

    MailDefinition mailDefinition = new MailDefinition();
    mailDefinition.IsBodyHtml = false;

    string host = "smtpserver";  // Your SMTP server name.
    string from = "from@somewhere.com";
    int port = -1;               // Your SMTP port number. Defaults to 25.

    mailDefinition.From = from;
    mailDefinition.Subject = "Boring email";
    mailDefinition.CC = "cc@somwhere.com,cc2@somwhere.com";

    List<System.Net.Mail.Attachment> mailAttachments = new List<System.Net.Mail.Attachment>();
    // Add any attachments here

    using (MailMessage mailMessage = mailDefinition.CreateMailMessage(to, null, "Email body", new System.Web.UI.Control()))
    {
        SmtpClient smtpClient = new SmtpClient(host);
        if (port != -1)
        {
            smtpClient.Port = port;
        }
        foreach (System.Net.Mail.Attachment mailAttachment in mailAttachments)
        {
            mailMessage.Attachments.Add(mailAttachment);
        }
        smtpClient.Send(mailMessage);
    }
}

【讨论】:

  • 谢谢!我必须添加使用凭据的功能,但它运行良好。
猜你喜欢
  • 2010-10-19
  • 1970-01-01
  • 2016-01-18
  • 2020-07-21
  • 1970-01-01
  • 2019-06-20
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多