【问题标题】:How to send mail in asp.net如何在asp.net中发送邮件
【发布时间】:2011-04-20 13:21:29
【问题描述】:

嗨 我已经编写了在 asp.net 中发送邮件的代码,如下所示:

        MailMessage mailMessage = new MailMessage();
        mailMessage.From = "xyz@gmail.com";
        mailMessage.To = "abc@gmail.com";
        mailMessage.Subject = "test";
        mailMessage.BodyFormat = MailFormat.Text;
        mailMessage.Body = "this is a test mail...";
        //mailMessage.Priority = MailPriority.High;
        SmtpMail.SmtpServer = "localhost";
        SmtpMail.Send(mailMessage);
        lblStatus.Text = "Your mail was sent";

而我的web.config文件如下

<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
    <configSections>
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                </sectionGroup>
            </sectionGroup>
        </sectionGroup>
    </configSections>
  <system.net>
    <mailsettings>
      <smtp deliverymethod="Network">
        <network host="localhost" port="25" defaultcredentials="true" />
      </smtp>
    </mailsettings>
  </system.net>


  <appSettings>
    <add key="ConnectionString" value="server=W2K8SERVER;database=Quiz;uid=sa;pwd=Alpha#123"/>
    <add key="Delay" value="1800000"/>
  </appSettings>
  <connectionStrings>
    <add name="QuizConnectionString" connectionString="Data Source=W2K8SERVER;Initial Catalog=Quiz;User ID=sa;Password=Alpha#123"
   providerName="System.Data.SqlClient" />
  </connectionStrings>

    <system.web>
        <!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
        <compilation debug="true">
            <assemblies>
                <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            </assemblies>
        </compilation>
        <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
        <authentication mode="Windows"/>
        <!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </controls>
        </pages>
        <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <providerOption name="CompilerVersion" value="v3.5"/>
                <providerOption name="WarnAsError" value="false"/>
            </compiler>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <providerOption name="CompilerVersion" value="v3.5"/>
                <providerOption name="OptionInfer" value="true"/>
                <providerOption name="WarnAsError" value="false"/>
            </compiler>
        </compilers>
    </system.codedom>
    <!-- 
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
            <remove name="ScriptModule"/>
            <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </modules>
        <handlers>
            <remove name="WebServiceHandlerFactory-Integrated"/>
            <remove name="ScriptHandlerFactory"/>
            <remove name="ScriptHandlerFactoryAppServices"/>
            <remove name="ScriptResource"/>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </handlers>
    </system.webServer>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

</configuration>

但它给出的错误:无法识别的配置部分 System.net/mailsettings。 我应该做些什么改变? ASP.NET C# 谢谢。

【问题讨论】:

  • 实际配置文件中是否存在结尾 &lt;/system.net&gt; 标记?
  • 你有本地运行的 smtp 服务器吗?
  • 是否在&lt;system.web&gt;-Section 之外?
  • 我在 之前的 之后添加了该代码
  • 尝试将 mailSettings 块放在配置文件的末尾,就在关闭 &lt;/configuration&gt; 标记之前。

标签: asp.net


【解决方案1】:

错误“Unrecognized configuration section System.net/mailsettings”的原因是&lt;mailSettings&gt;的拼写错误(您需要在设置上使用大写S - xml 区分大小写)。

web.config 中的此标记应显示为&lt;configuration&gt; ...&lt;/configuration&gt; 根元素的直接子元素。这是一个简单的sn-p代码:

<configuration>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="C:\inetpub\wwwroot\MyDevWebsite\aEmailPickupFolder" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

关于 web.config 的这个元素的官方文档可以在MSDN site here 上找到。

【讨论】:

    【解决方案2】:

    尝试在 web.config 文件的配置部分下使用它:

    <system.net>
        <mailsettings>
          <smtp deliverymethod="Network" from="putFromEmail">
            <network host="localhost" port="25" defaultcredentials="true" />
          </smtp>
        </mailsettings>
      </system.net>
    

    【讨论】:

    • 我在 web.config 中使用了发布的代码(在 之后和 之前,但它给出了错误:无法识别的配置部分 System.net/mailsettings
    • 您可以编辑您的问题并发布您的完整 web.config。那我明白了,你一定是做错了什么。
    • 我已经发布了我的 web.config 文件
    • 好像没问题..你能把email放到smpt吗?
    • 来自 smtp 中的电子邮件是什么意思?我添加了 mailmessage.from =emailid
    【解决方案3】:

    这是我的邮件类:

    using System;
    using System.Linq;
    using System.Net.Mail;
    using System.Text;
    using System.Threading;
    
    namespace Utils.Mailer
    {
        public static class MailSender
        {
            /// <summary>
            /// Sends a MailMessage object using the SMTP settings.
            /// </summary>
            public static void SendMailMessage(MailMessage message)
            {
                if (!Settings.Instance.SendEmails)
                {
                    return;
                }
    
                if (message == null)
                    throw new ArgumentNullException("message");
    
                try
                {
                    message.IsBodyHtml = true;
                    message.BodyEncoding = Encoding.UTF8;
                    var smtp = new SmtpClient("myserver");
    
                    // don't send credentials if a server doesn't require it,
                    // linux smtp servers don't like that 
                    if (!string.IsNullOrEmpty("myuser"))
                    {
                        smtp.Credentials = new System.Net.NetworkCredential("myuser", "mypass");
                    }
                    smtp.Port = 25;
                    smtp.EnableSsl = true;
                    smtp.Send(message);
                }
                catch (SmtpException)
                {
                    //OnEmailFailed(message);
                }
                finally
                {
                    // Remove the pointer to the message object so the GC can close the thread.
                    message.Dispose();
                }
            }
    
            /// <summary>
            /// Sends the mail message asynchronously in another thread.
            /// </summary>
            /// <param name="message">The message to send.</param>
            public static void SendMailMessageAsync(MailMessage message)
            {
                ThreadPool.QueueUserWorkItem(state => SendMailMessage(message));
            } 
        }
    }
    

    【讨论】:

      【解决方案4】:

      看起来这个功能/配置部分是在 .NET 2.0 中添加的。确保您站点的应用程序池设置为至少 2.0 框架。 IIS >> 应用程序池 >> 找到分配给您站点的那个,>> 双击 >> .net 框架版本。

      来自MSDN(见顶部下拉菜单,1 未列出)

      【讨论】:

        【解决方案5】:
        public static string sendMail(string to, string title, string subject, string body)
                {
                    try
                    {
                        MailMessage mail = new MailMessage();
                        SmtpClient smtp = new SmtpClient();
                        if (to == "")
                            to = "aevalencia119@gmail.com";
                        MailAddressCollection m = new MailAddressCollection();
                        m.Add(to);
                        mail.Subject = subject;
                        mail.From = new MailAddress( "aevalencia119@gmail.com");
                        mail.Body = body;
                        mail.IsBodyHtml = true;
                        mail.ReplyTo = new MailAddress("aevalencia119@gmail.com");
                        mail.To.Add(m[0]);
                        smtp.Host = "smtp.gmail.com";
                         client.Port = 587;//25
                        smtp.EnableSsl = true;
                        smtp.Credentials = new System.Net.NetworkCredential("aevalencia119@gmail.com", "####");
                        ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; 
        
                        smtp.Send(mail);
        
                        return "done";
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }
                }
        

        【讨论】:

          【解决方案6】:

          看看下面的链接,可能对你有帮助

          Send mail in asp.net

          【讨论】:

          • 请尝试提供答案,因为链接可能会过期。
          • 提供代码示例和简短描述将确保您的帖子对未来用户有用。 ;)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-03-28
          • 2013-08-22
          • 2014-10-31
          • 1970-01-01
          • 2013-04-29
          相关资源
          最近更新 更多