.net app.config 文件中的 SMTP 邮件客户端设置 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1897593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SMTP Mail client settings in app.config file C#
提问by Caveatrob
I've put mail settings in app.config and can successfully pull them into a mailSettingsSectionGroup object. However, I'm not sure how to send a message using these settings.
我已经将邮件设置放在 app.config 中,并且可以成功地将它们拉入一个 mailSettingsSectionGroup 对象中。但是,我不确定如何使用这些设置发送消息。
This is what I have so far:
这是我到目前为止:
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MailSettingsSectionGroup mailSettings =
config.GetSectionGroup("system.net/mailSettings") as
System.Net.Configuration.MailSettingsSectionGroup;
What do I need to do next to use the mailSettings object?
接下来我需要做什么才能使用 mailSettings 对象?
回答by ChadT
Specifically, the Send(...)method. SmtpClientwill automaticallypull the details from your app/web.config file. You don't need to do anything to use the configuration, it's all handled automatically.
具体来说,Send(...)方法。SmtpClient将自动从您的 app/web.config 文件中提取详细信息。您无需执行任何操作即可使用配置,这一切都是自动处理的。
Edit to add SMTP Web.ConfigExample:
编辑以添加 SMTPWeb.Config示例:
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="yoursmtpserver.com" />
</smtp>
</mailSettings>
</system.net>
回答by Randy
I have a custom Class:
我有一个自定义类:
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)
{
}
}
}
}
}
And this pulls from my app.conf file just fine.
这从我的 app.conf 文件中提取就好了。

