app.config文件中的SMTP邮件客户端设置C#

时间:2009-12-13 20:14:34

标签: .net console smtp app-config mailsettings

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

这是我到目前为止所做的:

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

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

使用mailSettings对象后我需要做什么?

2 个答案:

答案 0 :(得分:17)

System.Net.Mail.SmtpClient

具体来说,是Send(...)方法。 SmtpClient自动从app / web.config文件中提取详细信息。您无需执行任何操作即可使用配置,而是全部自动处理。

编辑以添加SMTP Web.Config示例:

<system.net>
    <mailSettings>
        <smtp from="foo@bar.com">
            <network host="yoursmtpserver.com" />
        </smtp>
    </mailSettings>
</system.net>

答案 1 :(得分: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文件中提取就好了。