我已将邮件设置放在app.config中,并可以成功将它们拉入mailSettingsSectionGroup对象。但是,我不确定如何使用这些设置发送消息。
这是我到目前为止所做的:
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MailSettingsSectionGroup mailSettings =
config.GetSectionGroup("system.net/mailSettings") as
System.Net.Configuration.MailSettingsSectionGroup;
使用mailSettings对象后我需要做什么?
答案 0 :(得分:17)
具体来说,是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文件中提取就好了。