2009-12-13 53 views
5

我已经将邮件设置放在app.config中,并且可以成功将它们拉入到mailSettingsSectionGroup对象中。但是,我不确定如何使用这些设置发送消息。app.config文件中的SMTP邮件客户端设置C#

这是我到目前为止有:

System.Configuration.Configuration config =  
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

MailSettingsSectionGroup mailSettings = 
config.GetSectionGroup("system.net/mailSettings") as 
System.Net.Configuration.MailSettingsSectionGroup; 

什么我下一步需要使用mailSettings对象呢?

回答

14

System.Net.Mail.SmtpClient

具体地说,Send(...)方法。 SmtpClient将自动从你的app/web.config文件中提取详细信息。您不需要做任何事情来使用配置,它都会自动处理。

编辑,添加SMTP Web.Config例子:

<system.net> 
    <mailSettings> 
     <smtp from="[email protected]"> 
      <network host="yoursmtpserver.com" /> 
     </smtp> 
    </mailSettings> 
</system.net> 
+0

您能否提供一个示例web.config文件或指定SmtpClient将读取的模式? – 2015-08-12 16:14:22

+0

“发件人”是如何自动提取的? – mynkow 2016-04-19 08:36:35

+0

所以我在“from”中指定地址,但是当我在代码中使用另一个地址时,代码中的地址将覆盖config中的地址。如果我在代码中没有指定任何内容(空,空字符串),则会引发错误。 – Greg 2016-11-04 14:31:33

2

我有一个自定义类:

using System; 
    using System.Configuration; 
    using System.Net; 
    using System.Net.Configuration; 
    using System.Net.Mail; 

    namespace MyNameSpace 
    { 
     internal static class SMTPMailer 
     { 
      public static void SendMail(string to, string subject, string body) 
      { 
       Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
       var mailSettings = oConfig.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; 

       if (mailSettings != null) 
       { 
        int port = mailSettings.Smtp.Network.Port; 
        string from = mailSettings.Smtp.From; 
        string host = mailSettings.Smtp.Network.Host; 
        string pwd = mailSettings.Smtp.Network.Password; 
        string uid = mailSettings.Smtp.Network.UserName; 

        var message = new MailMessage 
         { 
          From = new MailAddress(@from) 
         }; 
        message.To.Add(new MailAddress(to)); 
        message.CC.Add(new MailAddress(from)); 
        message.Subject = subject; 
        message.IsBodyHtml = true; 
        message.Body = body; 

        var client = new SmtpClient 
         { 
          Host = host, 
          Port = port, 
          Credentials = new NetworkCredential(uid, pwd), 
          EnableSsl = true 
         }; 

        try 
        { 
         client.Send(message); 
        } 
        catch (Exception ex) 
        { 
        } 
       } 
      } 
     } 
    } 

从我app.conf文件这个拉就好了。