2012-08-01 57 views
1

MailDefinition類僅用於ASP嗎?它似乎有我需要的一切,但顯然我需要在Web.Config文件中添加SMTP服務器信息。我想在WinForms應用程序中使用這個類。這可能嗎?MailDefinition類僅用於ASP嗎?

謝謝

+0

爲什麼要使用MailDefinition類?你可以使用System.Net的MailMessage類嗎? – Anuraj 2012-08-01 16:11:52

+0

MailDefinition允許使用外部HTML文件,並且可以隨時編輯HTML模板的外觀,而無需重新編譯和部署您的應用程序 – JimDel 2012-08-01 16:21:38

回答

1

當然,你應該可以在WinForms應用程序中使用它。您需要將SMTP主機名傳遞給System.Net.Mail.SmtpClient構造函數。類似這樣的:

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

// namespace etc 

private void SendEmail() 
{ 
    string to = "[email protected],[email protected]"; 

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

    string host = "smtpserver"; // Your SMTP server name. 
    string from = "[email protected]"; 
    int port = -1;    // Your SMTP port number. Defaults to 25. 

    mailDefinition.From = from; 
    mailDefinition.Subject = "Boring email"; 
    mailDefinition.CC = "[email protected],[email protected]"; 

    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); 
    } 
} 
+0

謝謝!我不得不添加使用憑據的能力,但它完美地工作。 – JimDel 2012-08-01 17:16:47

相關問題