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

时间:2013-06-24 23:09:03

标签: 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 Manager中,我试图查看是否为邮件设置了服务器和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时,似乎才会出现错误消息。

我错过了什么?任何人都可以解释本教程如何尝试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框中保留数据/值时遇到问题。更多的研究让我想起了“必需”属性,在这种情况下,这两个属性同时兼具并提供了一个简洁的工具提示。

因此,我删除了以前的代码,该代码保留了文本框值并验证了表单并使用了“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>  

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

如果您想使用剃须刀丰富电子邮件正文,可以使用Mailzory。此外,您可以从here下载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()