从 ASP.NET 网页 (Razor) 站点发送Email

作者 Tom FitzMacken

本文介绍如何在使用 ASP.NET 网页 (Razor) 时从网站发送电子邮件。

学习内容:

  • 如何从您的网站发送电子邮件。
  • 如何将文件附加到电子邮件。

这是本文中介绍的 ASP.NET 功能:

  • 帮助 WebMail 程序。

本教程中使用的软件版本

  • ASP.NET 网页 (Razor) 3

本教程还适用于 ASP.NET 网页 2。

从您的网站发送Email消息

可能需要从您的网站发送电子邮件的原因有很多种。 你可以向用户发送确认消息,也可以 (向自己发送通知,例如,新用户已注册。) WebMail 帮助程序使你可以轻松地发送电子邮件。

若要使用 WebMail 帮助程序,必须有权访问 SMTP 服务器。 (SMTP 代表 简单邮件传输协议。) SMTP 服务器是一个电子邮件服务器,它只将邮件转发到收件人的服务器, 它是电子邮件的出站端。 如果你使用网站的托管提供商,他们可能会使用电子邮件设置你,他们可以告诉你 SMTP 服务器名称是什么。 如果你在公司网络中工作,管理员或 IT 部门通常可以提供有关可以使用的 SMTP 服务器的信息。 如果你在家工作,你甚至可以使用普通电子邮件提供商进行测试,后者可以告诉你其 SMTP 服务器的名称。 通常需要:

  • SMTP 服务器的名称。
  • 端口号。 这几乎总是 25。 但是,ISP 可能要求使用端口 587。 如果对电子邮件使用安全套接字层 (SSL) ,则可能需要其他端口。 请与电子邮件提供商联系。
  • 凭据 (用户名、密码) 。

在此过程中,将创建两个页面。 第一页有一个表单,允许用户输入说明,就像他们正在填写技术支持表单一样。 第一页将其信息提交到第二页。 第二页中,代码提取用户的信息并发送电子邮件。 它还会显示一条消息,确认已收到问题报告。

[屏幕截图显示确认已收到问题报告的消息。]

注意

为了简单起见,代码会直接在使用该帮助程序的页面中初始化 WebMail 帮助程序。 但是,对于真实网站,最好将这样的初始化代码放入全局文件中,以便为网站中的所有文件初始化 WebMail 帮助程序。 有关详细信息,请参阅自定义 ASP.NET 网页Site-Wide行为

  1. 创建新网站。

  2. 添加名为 EmailRequest.cshtml 的新页面并添加以下标记:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Request for Assistance</title>
    </head>
    <body>
      <h2>Submit Email Request for Assistance</h2>
      <form method="post" action="ProcessRequest.cshtml">
        <div>
            Your name:
            <input type="text" name="customerName" />
        </div>
    
        <div>
            Your email address:
            <input type="text" name="customerEmail" />
        </div>
    
        <div>
            Details about your problem: <br />
            <textarea name="customerRequest" cols="45" rows="4"></textarea>
        </div>
    
        <div>
            <input type="submit" value="Submit" />
        </div>
      </form>
    </body>
    </html>
    

    请注意, action form 元素的 属性已设置为 ProcessRequest.cshtml。 这意味着表单将提交到该页面,而不是返回到当前页。

  3. 将名为 ProcessRequest.cshtml 的新页面添加到网站,并添加以下代码和标记:

    @{
        var customerName = Request["customerName"];
        var customerEmail = Request["customerEmail"]; 
        var customerRequest = Request["customerRequest"];
        var errorMessage = "";
        var debuggingFlag = false;
        try {
            // Initialize WebMail helper
            WebMail.SmtpServer = "your-SMTP-host";
            WebMail.SmtpPort = 25;
            WebMail.UserName = "your-user-name-here";
            WebMail.Password = "your-account-password";
            WebMail.From = "your-email-address-here";
    
            // Send email
            WebMail.Send(to: customerEmail,
                subject: "Help request from - " + customerName,
                body: customerRequest
            );
        }
        catch (Exception ex ) {
            errorMessage = ex.Message;
        }
    }
    <!DOCTYPE html>
    <html>
    <head>
      <title>Request for Assistance</title>
    </head>
    <body>
      <p>Sorry to hear that you are having trouble, <b>@customerName</b>.</p>
        @if(errorMessage == ""){
          <p>An email message has been sent to our customer service
             department regarding the following problem:</p>
          <p><b>@customerRequest</b></p>
        }
        else{
            <p><b>The email was <em>not</em> sent.</b></p>
            <p>Please check that the code in the ProcessRequest page has 
               correct settings for the SMTP server name, a user name, 
               a password, and a "from" address.
            </p>
            if(debuggingFlag){
                <p>The following error was reported:</p>
                <p><em>@errorMessage</em></p>
            }
        }
    </body>
    </html>
    

    在代码中,获取提交到页面的表单字段的值。 然后调用 WebMail 帮助程序 Send 的方法来创建并发送电子邮件。 在这种情况下,要使用的值由文本组成,这些文本与从表单提交的值连接起来。

    此页的代码位于块内 try/catch 。 例如,如果由于任何原因发送电子邮件的尝试不起作用 (设置不正确) ,则块中的 catch 代码将运行并将 errorMessage 变量设置为已发生的错误。 (有关块或<text>标记的详细信息try/catch,请参阅使用 Razor 语法 ASP.NET 网页编程简介。)

    在页面正文中,如果 errorMessage 变量 (默认) 为空,则用户会看到电子邮件已发送的消息。 errorMessage如果该变量设置为 true,则用户会看到一条消息,指出发送消息时出现问题。

    请注意,在显示错误消息的页面部分,还有一个额外的测试: if(debuggingFlag)。 如果发送电子邮件时遇到问题,可以将此变量设置为 true。 如果 debuggingFlag 为 true,并且发送电子邮件时出现问题,则显示其他错误消息,显示 ASP.NET 在尝试发送电子邮件时报告的任何内容。 不过,公平警告:ASP.NET 无法发送电子邮件时报告的错误消息可能是一般的。 例如,如果 ASP.NET 无法联系 SMTP 服务器 (,因为服务器名称) 错误,则错误为 Failure sending mail

    注意

    重要 当从代码) (ex 异常对象收到错误消息时, 不要 将该消息例行传递给用户。 异常对象通常包括用户不应看到的信息,甚至可能是安全漏洞。 这就是此代码包含用作显示错误消息的开关的变量 debuggingFlag 的原因,以及默认情况下变量设置为 false 的原因。 应将变量设置为 true (因此 仅在 发送电子邮件时遇到问题且需要调试时才显示错误消息) 。 修复任何问题后,请重新设置为 debuggingFlag false。

    修改代码中的以下电子邮件相关设置:

    • 将 设置为 your-SMTP-host 有权访问的 SMTP 服务器的名称。

    • 设置为 your-user-name-here SMTP 服务器帐户的用户名。

    • 将 设置为 your-account-password SMTP 服务器帐户的密码。

    • 将 设置为 your-email-address-here 你自己的电子邮件地址。 这是从中发送邮件的电子邮件地址。 (某些电子邮件提供商不允许你指定其他 From 地址,并将使用你的用户名作为 From 地址。)

      提示

      配置Email设置

      有时,确保对 SMTP 服务器、端口号等具有正确的设置可能很困难。 下面是一些提示:

      • SMTP 服务器名称通常类似于 smtp.provider.comsmtp.provider.net。 但是,如果将站点发布到托管提供程序,则此时的 SMTP 服务器名称可能是 localhost。 这是因为在发布并且站点在提供程序的服务器上运行后,从应用程序的角度来看,电子邮件服务器可能是本地服务器。 服务器名称的此更改可能意味着必须在发布过程中更改 SMTP 服务器名称。
      • 端口号通常为 25。 但是,某些提供程序要求使用端口 587 或其他某些端口。
      • 请确保使用正确的凭据。 如果已将网站发布到托管提供商,请使用提供商专门指示的电子邮件凭据。 这些凭据可能与用于发布的凭据不同。
      • 有时根本不需要凭据。 如果使用个人 ISP 发送电子邮件,则电子邮件提供商可能已经知道你的凭据。 发布后,可能需要使用与在本地计算机上测试时不同的凭据。
      • 如果电子邮件提供商使用加密,则必须将 设置为 WebMail.EnableSsltrue
  4. 在浏览器中运行 EmailRequest.cshtml 页。 (在运行页面之前,请确保在 “文件” 工作区中选择该页面。)

  5. 输入姓名和问题说明,然后单击“ 提交 ”按钮。 你将重定向到 ProcessRequest.cshtml 页面,该页面将确认你的邮件并向你发送电子邮件。

    [屏幕截图显示了“处理请求”页。]

使用 Email 发送文件

还可以发送附加到电子邮件的文件。 在此过程中,将创建一个文本文件和两个 HTML 页面。 你将使用文本文件作为电子邮件附件。

  1. 在网站中,添加新文本文件并将其命名 为MyFile.txt

  2. 复制以下文本并将其粘贴到 文件中:

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  3. 创建名为 SendFile.cshtml 的页面并添加以下标记:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Attach File</title>
    </head>
    <body>
      <h2>Submit Email with Attachment</h2>
      <form method="post" action="ProcessFile.cshtml">
        <div>
            Your name:
            <input type="text" name="customerName" />
        </div>
    
        <div>
            Your email address:
            <input type="text" name="customerEmail" />
        </div>
    
        <div>
            Subject line: <br />
            <input type="text" size= 30 name="subjectLine" />
        </div>
    
        <div>
            File to attach: <br />
            <input type="text" size=60 name="fileAttachment" />
        </div>
    
        <div>
            <input type="submit" value="Submit" />
        </div>
      </form>
    </body>
    </html>
    
  4. 创建名为 ProcessFile.cshtml 的页面并添加以下标记:

    @{
        var customerName = Request["customerName"];
        var customerEmail = Request["customerEmail"]; 
        var customerRequest = Request["customerRequest"];
        var subjectLine = Request["subjectLine"];
        var fileAttachment = Request["fileAttachment"];
        var errorMessage = "";
        var debuggingFlag = false;
    
        try {
            // Initialize WebMail helper
            WebMail.SmtpServer = "your-SMTP-host";
            WebMail.SmtpPort = 25;
            WebMail.UserName = "your-user-name-here";
            WebMail.Password = "your-account-password";
            WebMail.From = "your-email-address-here";
    
            // Create array containing file name
            var filesList = new string [] { fileAttachment };
    
            // Attach file and send email
            WebMail.Send(to: customerEmail,
                subject: subjectLine,
                body: "File attached. <br />From: " + customerName,
                filesToAttach: filesList);
        }
        catch (Exception ex ) {
            errorMessage = ex.Message;
        }
    }
    <!DOCTYPE html>
    <html>
    <head>
        <title>Request for Assistance</title>
    </head>
    <body>
      <p>Sorry to hear that you are having trouble, <b>@customerName</b>.</p>
        @if(errorMessage == ""){
            <p><b>@customerName</b>, thank you for your interest.</p>
            <p>An email message has been sent to our customer service
               department with the <b>@fileAttachment</b> file attached.</p>
        }
        else{
            <p><b>The email was <em>not</em> sent.</b></p>
            <p>Please check that the code in the ProcessRequest page has 
               correct settings for the SMTP server name, a user name, 
               a password, and a "from" address.
            </p>
            if(debuggingFlag){
                <p>The following error was reported:</p>
                <p><em>@errorMessage</em></p>
            }
        }
    </body>
    </html>
    
  5. 修改示例中代码中的以下电子邮件相关设置:

    • 将 设置为 your-SMTP-host 有权访问的 SMTP 服务器的名称。
    • 设置为 your-user-name-here SMTP 服务器帐户的用户名。
    • 将 设置为 your-email-address-here 你自己的电子邮件地址。 这是从中发送邮件的电子邮件地址。
    • 将 设置为 your-account-password SMTP 服务器帐户的密码。
    • 将 设置为 target-email-address-here 你自己的电子邮件地址。 (与以前一样,你通常会向其他人发送电子邮件,但为了进行测试,你可以将其发送给自己。)
  6. 在浏览器中运行 SendFile.cshtml 页。

  7. 输入你的姓名、主题行和要附加 (MyFile.txt) 的文本文件的名称。

  8. 单击“Submit”按钮。 与以前一样,系统会将你重定向到 ProcessFile.cshtml 页面,该页将确认你的邮件,并向你发送包含附加文件的电子邮件。

其他资源