9

我已将邮件设置放在 app.config 中,并且可以成功地将它们拉入 mailSettingsSectionGroup 对象。但是,我不确定如何使用这些设置发送消息。

这是我到目前为止所拥有的:

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

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

接下来我需要做什么才能使用 mailSettings 对象?

4

2 回答 2

20

System.Net.Mail.SmtpClient

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

编辑以添加 SMTPWeb.Config示例:

<system.net>
    <mailSettings>
        <smtp from="foo@bar.com">
            <network host="yoursmtpserver.com" />
        </smtp>
    </mailSettings>
</system.net>
于 2009-12-14T00:20:55.417 回答
5

我有一个自定义类:

    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 文件中提取。

于 2013-04-24T19:12:46.240 回答