如何在asp.net中发送邮件

时间:2011-04-20 13:21:30

标签: asp.net

您好 我已编写代码在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# 谢谢。

7 个答案:

答案 0 :(得分:1)

错误“无法识别的配置部分System.net / mailsettings”的原因是由于<mailSettings>的拼写错误(您需要设置上的资本S - xml区分大小写)。

web.config中的此标记应显示为<configuration> ...</configuration>根元素的直接子元素。这是一段简单的代码:

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

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

答案 1 :(得分:0)

这是我的邮件程序类:

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));
        } 
    }
}

答案 2 :(得分:0)

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

来自MSDN

(请参阅顶部的下拉菜单,未列出1)

答案 3 :(得分:0)

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;
            }
        }

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

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 :(得分:0)

查看以下链接,可以帮助您

Send mail in asp.net