您好我们有一个业务逻辑层,它有一个电子邮件服务类。在这个类中,我们有一个方法可以创建一个电子邮件(这部分工作和编译很好)。但是,当我们尝试访问应用程序配置文件以便测试该方法时,我们会收到错误消息 - 无法检索应用程序配置邮件设置,并且如果不是,则表示所有值都为空。以下是我们代码的应用配置部分:
<mailSettings>
<smtp deliveryMethod="Network" from="info@example.com">
<network host="localhost" port="25" defaultCredentials="true"/>
</smtp>
</mailSettings>
以下是我们用来连接app.config的代码:
private System.Net.Configuration.MailSettingsSectionGroup mailSettings;
SmtpClient client = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port);
我们在这里做错了什么?
答案 0 :(得分:5)
您的mailSettings
变量未初始化为任何内容 - 它不会神奇地包含您的配置。
您需要使用ConfigurationManager
类来访问它(如果尚未添加,请记住添加对System.Configuration
的引用。)您还需要为以下内容添加using System.Net.Configuration
代码。
SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
if (smtpSection != null)
{
SmtpClient client = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
}
答案 1 :(得分:1)
SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
if (smtpSection != null) {
SmtpClient client = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
}
答案 2 :(得分:1)
<mailSettings>
<smtp>
<network host="smtp.mailserver.com" password="password" userName="username"/>
</smtp>
</mailSettings>
然后 public static bool SendEmail(string sender,string recipient,string subject,string body)
{
try
{
Configuration mConfigurationFile = ConfigurationManager.OpenExeConfiguration("D:\\Projects\\EmailSolution\\Email\\App.config");
MailSettingsSectionGroup mMailSettings = mConfigurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
string mHost = string.Empty;
if (mMailSettings != null)
{
//int mPort = mMailSettings.Smtp.Network.Port;
mHost = mMailSettings.Smtp.Network.Host;
//string mPassword = mMailSettings.Smtp.Network.Password;
//string mUsername = mMailSettings.Smtp.Network.UserName;
}
//Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
SmtpClient mailClient = new SmtpClient(mHost);
//Sends an e-mail message to an SMTP server for delivery.
mailClient.Send(EmailMessage.CreateEmailMessage(sender, recipient, subject, body));
return true;
}