2

(对于完成的结果,请转到底部的编辑/编辑)

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

在早期解决 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 = "username@example.com";
        // WebMail.Password = "your-password";
        // WebMail.From = "your-name-here@example.com";
        // WebMail.EnableSsl = true; (add this if smtp is encrypted)
        // WebMail.SmtpPort = 587;
    }

编辑/编辑

提交以及验证 textarea 框后,我无法在 textarea 框中保留数据/值。更多的研究让我想起了“必需”属性,在这种情况下,它既可以做,也可以提供一个简洁的工具提示。

因此,我删除了保留文本框值并验证表单并使用“必需”属性的先前代码 - 更整洁。

此外,处理代码和成功消息现在已内置到电子邮件请求页面中,因此不再需要 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>  
4

2 回答 2

3

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

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 = "example@gmail.com";
    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
    }
}
于 2013-06-24T23:20:04.150 回答
0

如果你想用剃刀丰富电子邮件正文,你可以使用Mailzory此外,您可以从此处下载 nuget 包。用法很简单:

// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);

var email = new Email(template);

// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";

// send email
var task = email.SendAsync("mailzory@outlook.com", "subject");
task.Wait()
于 2017-09-15T03:21:26.597 回答