简体   繁体   中英

smtp settings being ignored in web.config

I am trying to adjust the mail settings in a .Net Website but the smtp in my web.config are being ignored in favor of smtp settings that appear to be set in a dll file in the bin folder. How do I enforce the mailsettings in the web.config and why does the dll file smtp settings have priority over the web.config settings. The programmer who built this (years ago and now gone) also included smtp settings in C# controller .cs files which I updated to the correct smtp settings but these too are ignored. The smtp settings in the dll are being used in favor. I'm new to .Net websites incidentally. I also established a connection to the website with IIS and set the correct SMTP settings there in the control panel but no joy. The system generated emails I receive to my inbox are all from the wrong mail server. I appreciate your help. Thanks

Web.config mail setting:

 <system.net>
        <mailSettings>
            <smtp from="mail@mysite.com">
                <network host="smtp.sendgrid.net" port="587" userName="user1" password="pass1" />
            </smtp>
        </mailSettings>
    </system.net>

Web Config full:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <directoryBrowse enabled="true" />
    <defaultDocument>
      <files>
        <clear />
        <add value="Default.htm" />
        <add value="Default.asp" />
        <add value="index.htm" />
        <add value="index.pl" />
        <add value="default.html" />
        <add value="Default.cshtml" />
        <add value="index.php" />
        <add value="index.html" />
        <add value="Default.aspx" />
      </files>
    </defaultDocument>
    <httpProtocol>
      <customHeaders>
        <clear />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
  <connectionStrings>

    <add name="ConnectionString" connectionString="Data Source=whatever.com;Initial Catalog=whateverdb;User ID=fakeuser;password=fakepass;Connection Timeout=30;Min Pool Size=20; Max Pool Size=200;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31434BF3856AD364897979E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF38343456AD3647878E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=3GF655651BF3856AD3648787E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3GHGHGH434425856AD387878764E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=GHGHGH66676731BF38567676AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="1200000" />
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <customErrors mode="Off" />
    <trust level="Full" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.net>
    <mailSettings>
    <smtp from="mail@mysite.com">
    <network host="smtp.sendgrid.net" port="587" userName="user1" password="pass1" />
    </smtp>
    </mailSettings>
    </system.net>
</configuration>
<!--ProjectGuid: 80e45822-7574-4225-9e47-31f80GHGHG5567678545ea-->

.cs code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.IO;
using System.Net.Mail;
using System.Timers;

....

public bool SendEmail(string Semailid, string encrypted, string EmailID, string PersonsName, string EmailSubject, string mycourse, string encryptStudent,string Certificettemplete)
        {
            try
            {
                MailMessage Msg = new MailMessage();
                // Sender e-mail address.
                Msg.From = new MailAddress(EmailID);
                // Recipient e-mail address.
                Msg.To.Add(Semailid);
                Msg.Subject = EmailSubject;
                Msg.IsBodyHtml = true;
                Msg.Body = Certificettemplete;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.sendgrid.net"; 
                smtp.Port = 25;
                smtp.Credentials = new System.Net.NetworkCredential("user", "pass");
                smtp.EnableSsl = false;
                smtp.Send(Msg);
                Msg = null;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
                //return false;
            }
        }

You method has hard coded values, so the config is currently irrelevant.

My suggestion:

  1. If the class containing SendMail is specific to SMTP, add/update a constructor that accepts SMTP address, port, username, and password. Save those into private variables within the class. If the class is a generic utility class, I would move the functionality into a specific SMTP class and do the above.
  2. Change your hard coded references to the four fields in SendEmail to use the variables within the class
  3. Change the instantiation ("new SMTP()") to pass in the four parameters that you get from the config.*

*If you are invoking SMTP all over the place, it may be useful to get the value at the start of the program and pass it along as needed.

If you omit these lines it will use the settings in the web.config

smtp.Host = "smtp.sendgrid.net"; 
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential("user", "pass");
smtp.EnableSsl = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM