c# - ASP.net Razor - 使用 GMail SMTP 从网站发送电子邮件

标签 c# asp.net sql-server razor webmatrix

(要查看最终结果,请前往底部进行编辑/编辑)

正如标题所述,我正在尝试使用 GMail SMTP 从网站发送电子邮件,如 ASP.net 教程中所述:http://www.asp.net/web-pages/tutorials/email-and-search/11-adding-email-to-your-web-site .

尽早解决 ISAPI.dll 处理程序映射错误后,Webmatrix 错误控制台中不再有错误,只有“GET”和“POST”操作的成功标记;但是,网页返回 try catch 错误,“电子邮件未发送......”

在 SQL Server 管理器中,我尝试查看是否为邮件设置了服务器和 sa 管理员角色,但我看不到代理属性,据我所知,因为我有 SQL Management Studio 的 Express 版本。也就是说,如果服务器角色或邮件设置出现问题,肯定会生成错误消息吗?

有人可以快速浏览一下 SMTP 设置和整体代码以找出错误或建议吗?

(顺便说一下,我在示例代码中更改了我的电子邮件地址和密码。我的电子邮件地址在 webmail.username 和 webmail.from 中重复)

谢谢。

这是 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>

**Here is ProcessRequest.cshtml**

        @{
        var customerName = Request["customerName"];
        var customerEmail = Request["customerEmail"]; 
        var customerRequest = Request["customerRequest"];
        var errorMessage = "true";
        var debuggingFlag = false;
        try {
            // Initialize WebMail helper
            WebMail.SmtpServer = "smtp.gmail.com";
            WebMail.EnableSsl = true;
            WebMail.SmtpPort = 465;
            WebMail.UserName = "MY EMAIL ADDRESS.com";
            WebMail.Password = "MYPASSWORD";
            WebMail.From = "MY EMAIL ADDRESS.com";

            // 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>
____________________________________________________

编辑:

感谢 Mike 和 Gokhan 的帮助。今天早上我又仔细看了一遍。果然,昨晚从网页上发来了两封邮件; 因此,在某些时候所有因素都是正确的。

我尝试过端口 25、465 和 587,但是,我遵循的是教程,而不是“代码”。在我看来,该教程有点误导,并引起了困惑 - 我在错误的收件箱中寻找电子邮件。人们可能会认为问题报告通常会发送给主机,而不是报告问题的用户。

此外,即使正在发送电子邮件,仍然显示 try catch 错误。当然,应该通过犯错误来激活错误消息。仅当 [var errorMessage = "true";] 设置为 true 时,错误消息似乎才会出现。

我错过了什么?谁能解释一下本教程的 try catch 方法是如何工作的?

无论如何,这一切都很有效 - 我总是觉得迈克的评论令人放心。

我使用另一个教程将代码缩小到一页,并添加了一些表单验证,然后修改了代码,以便将电子邮件发送给主机而不是用户。

这是新的 EmailRequest.cshtml:

    @{

    Layout = "/_SiteLayout.cshtml";
    Page.Title = "Compare";

    Validation.RequireField("emailAddress", "customerName is required.");
    Validation.RequireField("emailSubject", "customerEmail is required.");
    Validation.RequireField("emailBody", "customerRequest is required."); 

        var message = "";
        var companyname = Request.Form["emailAddress"];
        var contactname = Request.Form["emailSubject"];
        var employeecount = Request.Form["emailBody"];


    try{
        if (IsPost && Validation.IsValid()) {

        // Send email
        WebMail.Send(to:"ADMIN-EMAIL-ADDRESS.COM",
            subject: Request.Form["emailSubject"],

            body: "Help request from -   " + Request.Form["customerName"] + " - " + "Email Subject -   " + Request.Form["emailSubject"]  + " - " + "Customer email -   " + Request.Form["emailAddress"]
           );
           message = "Email sent!";
        }
    }
    catch(Exception ex){
        message = "Email could not be sent!";
    }
}
<!DOCTYPE html>
<html lang="en">
  <head>
     <meta charset="utf-8" />
     <title>Test Email</title>

              <style type="text/css">
          .validation-summary-errors {font-weight:bold; color:red; font-size: 11pt;}
             .validation-summary-valid {
    display: none;
}

         </style>

  </head>
  <body>
    <h1>Test Email</h1>
    <form method="post">
        @Html.ValidationSummary("Errors with your submission:")

       <p>
        <label for="customerName">Name:</label>
        <input type="text" name="customerName" value="@Request.Form["customerName"]"  />


      </p>

      <p>
        <label for="emailAddress">Email address:</label>
        <input type="text" name="emailAddress" value="@Request.Form["emailAddress"]"  />


      </p>
      <p>
        <label for="emailSubject">Subject:</label>
        <input type="text" name="emailSubject" value="@Request.Form["emailSubject"]"  /> 

      </p>
      <p>
        <label for="emailBody">Text to send:</label><br/>
        <textarea name="emailBody" rows="6"></textarea>

      </p>
    <p><input type="submit" value="Send!" /></p>
    @if(IsPost){
        <p>@message</p>
    }
    </form>
  </body>
</html>

最后,这是我昨天没有发布的示例的 _AppStart 代码:

    @{
        WebSecurity.InitializeDatabaseConnection("StarterSite", "UserProfile", "UserId", "Email", true);

        // WebMail.SmtpServer = "mailserver.example.com";
        // WebMail.UserName = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44313721362a25292104213c25293428216a272b29" rel="noreferrer noopener nofollow">[email protected]</a>";
        // WebMail.Password = "your-password";
        // WebMail.From = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="265f4953540b48474b430b4e43544366435e474b564a430845494b" rel="noreferrer noopener nofollow">[email protected]</a>";
        // WebMail.EnableSsl = true; (add this if smtp is encrypted)
        // WebMail.SmtpPort = 587;
    }

编辑/编辑

提交后,我在保留文本区域框中的数据/值以及验证文本区域框时遇到问题。更多的研究让我想起了“required”属性,在这种情况下,它既可以做到这两点,还提供了一个简洁的工具提示。

因此,我删除了之前保留文本框值并验证表单的代码,并使用“required”属性代替 - 更加简洁。

此外,处理代码和成功消息现已内置到电子邮件请求页面中,因此不再需要 ProcessRequest.cshtml 页面。

这是向静态电子邮件地址发送请求的联系表单的完成代码 - 不要忘记您还需要使用 _AppStart 页面代码,除非您在页面中添加邮件服务器身份验证 - 您不需要两者都需要。但是,请注意,在页面中添加服务器电子邮件设置并不安全,因为用户将能够查看它们。我建议使用 _AppStart 页面,因为 Asp.net Razor 中以下划线开头的文件无法在线查看。

@{

    Layout = "/_SiteLayout.cshtml";
    Page.Title = "Compare";

    var message = "";
    var companyname = Request.Form["emailAddress"];
    var contactname = Request.Form["emailSubject"];
    var employeecount = Request.Form["emailBody"];


    try{
        if (IsPost && Validation.IsValid()) {

        // Send email
        WebMail.Send(to:"ADMIN EMAIL.COM",
            subject: Request.Form["emailSubject"],

            body: "Help request from -   " + Request.Form["customerName"] + " - " + "Email Subject -   " + Request.Form["emailSubject"]  + " - " + "Customer email -   " + Request.Form["emailAddress"]
           );
           message = "Email sent!";
        }
    }
    catch(Exception ex){
        message = "Email could not be sent!";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
    <title>Test Email</title>


</head>

  <body>
    <h1>Test Email</h1>

    <form method="post">

       <p>
        <label for="customerName">Name:</label>
        <input type="text" name="customerName"  required />
       </p>

      <p>
        <label for="emailAddress">Email address:</label>
        <input type="text" name="emailAddress" required />
      </p>
      <p>
        <label for="emailSubject">Subject:</label>
        <input type="text" name="emailSubject" required /> 

      </p>

      <p>
        <label for="emailBody">Text to send:</label><br/>
        <textarea name="emailBody" rows="6" required></textarea>
       </p>

    <p><input type="submit" value="Send!" /></p>
    @if(IsPost){
        <p>@message</p>
    }
    </form>
  </body>
</html>  

最佳答案

我很早以前就为一个项目编写过代码。试试这个。

public void SendEmail(string from, string to, string subject, string body)
{
    string host = "smtp.gmail.com";
    int port = 587;

    MailMessage msg = new MailMessage(from, to, subject, body);
    SmtpClient smtp = new SmtpClient(host, port);

    string username = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="67021f060a170b0227000a060e0b4904080a" rel="noreferrer noopener nofollow">[email protected]</a>";
    string password = "1234567890";

    smtp.Credentials = new NetworkCredential(username, password);
    smtp.EnableSsl = true;
    smtp.UseDefaultCredentials = false;

    try
    {    
        smtp.Send(msg);
    }
    catch (Exception exp)
    {
        //Log if any errors occur
    }
}

关于c# - ASP.net Razor - 使用 GMail SMTP 从网站发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17286597/

相关文章:

c# - 这个函数的内存泄漏在哪里?

c# - 基于 XNA Tile 的游戏 : Checking collision between 2 objects using their grid position inside a 2D array

ASP.NET MVC 是发布模型 ID 的更好方法吗?

javascript - 服务器端的用户确认

sql-server - 在 SQL Server 中查询最小值比查询所有行要长很多

sql-server - SQL Server 存储过程语法错误

c# - WPF DataGrid 绑定(bind)困惑

c# - 从 C# 访问硬件或内存

mysql - 外键列未显示在 vs 数据集数据表中

sql - 如何指定不会被转换为 SQL 命令查询参数的常量值 NHibernate 标准