【问题标题】:Email confirmation in ASP.NET mvc5 without sendgrid没有 sendgrid 的 ASP.NET mvc5 中的电子邮件确认
【发布时间】:2015-03-23 13:13:17
【问题描述】:

标题几乎说明了这一点。有没有办法在不使用发送网格的情况下将电子邮件确认添加到我的应用程序?我的 Azure 帐户不允许我使用它,说它在我的区域中不可用,我似乎找不到其他解决方案。

【问题讨论】:

  • 如何使用自托管 SMTP 或其他提供商?对于 Identity,您只需实现 IIdentityMessageService 并配置 Identity 即可使用它。一个例子显示在in this thread
  • 我试过了,但总是弹出这个错误:远程证书根据验证程序无效
  • 有什么错误提示吗?
  • 认为那是因为您没有有效的证书。看看this thread 你能做什么。请记住,您不应该在生产中这样做(如线程中所述)。
  • 我已经看过了,但这不是解决方案。另外,它不再起作用了。我怎样才能获得有效的证书?

标签: asp.net-mvc-5


【解决方案1】:

我没有在我的网站中使用 sendgrid 来提供电子邮件确认服务。我认为在流量低的小型网站上使用它没有意义。

我改用 gmail SMTP 服务,效果很好:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Web;

namespace MyProject.MyClasses
{
public class GmailEmailService : SmtpClient
{
    // Gmail user-name
    public string UserName { get; set; }

    public GmailEmailService():
        base( ConfigurationManager.AppSettings["GmailHost"], Int32.Parse(ConfigurationManager.AppSettings["GmailPort"]) )
    {
        //Get values from web.config file:
        this.UserName = ConfigurationManager.AppSettings["GmailUserName"];
        this.EnableSsl = Boolean.Parse( ConfigurationManager.AppSettings["GmailSsl"] );
        this.UseDefaultCredentials = false;
        this.Credentials = new System.Net.NetworkCredential(this.UserName, ConfigurationManager.AppSettings["GmailPassword"]);
    }


}

}

在 Web.Config 文件中添加以下内容:

  <configSections>

      <appSettings>

        <!--Smptp Server (confirmations emails)-->
        <add key="GmailUserName" value="[your user name]@gmail.com"/>
        <add key="GmailPassword" value="[your password]"/>
        <add key="GmailHost" value="smtp.gmail.com"/>
        <add key="GmailPort" value="587"/>
        <add key="GmailSsl" value="true"/>

      </appSettings>

  </configSections>

在 App_Start\IdentityConfig.cs 文件中将 SendAsync 方法更改为以下代码:

public class EmailService : IIdentityMessageService
{
public async Task SendAsync(IdentityMessage message)
{

        MailMessage email = new MailMessage(new MailAddress("noreply@myproject.com", "(do not reply)"), 
            new MailAddress(message.Destination));

        email.Subject = message.Subject;
        email.Body = message.Body;

        email.IsBodyHtml = true;

    using( var mailClient = new MyProject.MyClasses.GmailEmailService() )
    {
        //In order to use the original from email address, uncomment this line:
        //email.From = new MailAddress(mailClient.UserName, "(do not reply)");

        await mailClient.SendMailAsync(email);
    }

}
}

注意:您还必须将其添加到 IdentityConfig.cs 文件中:

using System.Net.Mail;

最后一件事是将 AccountController 文件中的以下内容更新为类似内容:

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            //Comment the following line to prevent log in until the user is confirmed:
            //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

            string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Account confirmation");

            // Uncomment to debug locally 
            // TempData["ViewBagLink"] = callbackUrl;

            ViewBag.errorMessage = "Please confirm the email was sent to you.";
            return View("ShowMsg");
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}


//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
    if (userId == null || code == null)
    {
        return View("Error");
    }
    var result = await UserManager.ConfirmEmailAsync(userId, code);
    return View(result.Succeeded ? "ConfirmEmail" : "Error");
}


private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
{
    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
    // Send an email with this link:
    string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userID, code = code }, protocol: Request.Url.Scheme);
    await UserManager.SendEmailAsync(userID, subject, "Please confirm your account by <a href=\"" + callbackUrl + "\">clicking here</a>");


    return callbackUrl;
}        

一个可能的视图 ShowMsg.cs 文件可以是:

@{
    ViewBag.Title = "Message";
}

<h1 class="text-danger">@ViewBag.Title</h1>
@{
    if (String.IsNullOrEmpty(ViewBag.errorMessage))
    {
        <h3 class="text-danger">An error occurred while processing your request.</h3>
    }
    else
    {
        <h3 class="text-danger">@ViewBag.errorMessage</h3>
    }
}

就是这样!,它对我有用。

附言: 您必须在您的 gmail 帐户中允许“不太安全的应用程序”选项。 follow that gmail link

我使用以下文章来编写该解决方案:

Create a secure ASP.NET MVC 5 web app with..

ASP-NET-MVC-Confirm-Registration-Email

stackoverflow-email-using-gmail-smtp-in-asp-net-mvc-application

adding-two-factor-authentication..

how-to-send-an Anonymous Email using Gmail in ASP.Net

how-to-send-email-using-gmail-smtp-...

【讨论】:

  • 非常感谢。像魅力一样工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2023-03-29
  • 2022-07-29
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
相关资源
最近更新 更多