将电子邮件设置移动到Web配置

时间:2015-03-15 17:48:59

标签: c# asp.net asp.net-mvc

我尝试将我的电子邮件设置移至网络配置,但我不知道如何从网络配置中调用该设置。

这是我的新密码网络配置设置:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="&quot;testo&quot; &lt;admin@test.com&gt;" >
      <network host="mail.test.com" userName="admin@test.com" password="waiff75E-" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

这是我之前的代码

const string username = "test@smartguroo.com";
const string password = "password";
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("admin@test.com", loggedinUser.Text + "test");
smtpclient.Host = "mail.test.com";
smtpclient.Port = 25;
mail.From = fromaddress;
mail.To.Add(userEmail.Text);
mail.Subject = ("New post on your wall from " + loggedinUser.Text + " ");
// mail.Attachments.Add(new mail);
mail.IsBodyHtml = true;
mail.Body = "";

2 个答案:

答案 0 :(得分:2)

删除以下行行,因为您希望web.config文件中的设置从配置的角度来驱动它。

smtpclient.EnableSsl = false;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);

只需在SmtpClient

上调用Send方法即可
smtpclient.Send(mail);

所有以前的问题都已配置到您的web.config文件中,正如您所做的那样。 (逐字复制)

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="&quot;testo&quot; &lt;admin@test.com&gt;" >
      <network host="mail.test.com" userName="admin@test.com" password="password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

答案 1 :(得分:0)

在您的网页配置

 </connectionStrings>
   <appSettings>
      <add key="webpages:Version" value="3.0.0.0" />
      <!-- Markup removed for clarity. -->

      <add key="mailAccount" value="xyz" />
      <add key="mailPassword" value="password" />
   </appSettings>
  <system.web>

通过

引用c#
  var credentials = new NetworkCredential(
             ConfigurationManager.AppSettings["mailAccount"],
             ConfigurationManager.AppSettings["mailPassword"]
             );

这是使用this identity tutorial