SendGrid无法发送电子邮件。

3
我一直在跟随这个教程:http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset。我已经重复阅读了三遍,并查看了几篇Stackoverflow的帖子,但我仍然不知道我错过了什么。通过调试,Visual Studio显示myMessage拥有所有必需的元素(要发送的电子邮件地址,消息主题,消息正文,发件人等),但是当我进行测试时,我实际上没有收到确认电子邮件。这是我目前的代码:

IdentityConfig.cs

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        // line below was commented out and replaced upon tutorial request
        //return Task.FromResult(0);
        await configSendGridasync(message);
    }
    // Use NuGet to install SendGrid (Basic C# client lib) 
    private async Task configSendGridasync(IdentityMessage message)
    {
        var myMessage = new SendGridMessage();
        myMessage.AddTo(message.Destination);
        myMessage.From = new System.Net.Mail.MailAddress(
                            "myActualEmail@email.com", "Robert");
        myMessage.Subject = message.Subject;
        myMessage.Text = message.Body;
        myMessage.Html = message.Body;

        var credentials = new NetworkCredential(
                   ConfigurationManager.AppSettings["mailAccount"],
                   ConfigurationManager.AppSettings["mailPassword"]
                   );

        // Create a Web transport for sending email.
        var transportWeb = new Web(credentials);

        // Send the email.
        if (transportWeb != null)
        {
            await transportWeb.DeliverAsync(myMessage);
        }
        else
        {
            Trace.TraceError("Failed to create Web transport.");
            await Task.FromResult(0);
        }
    }
}

账户控制器:

[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)
            {
                // commented below code and RedirectToAction out so it didn't auto log you in.
                //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                //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(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                ViewBag.Message = "Check your email and confirm your account, you must be confirmed before you can log in.";

                return View("Info");

                //return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

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

Web.config:

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />

    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="mailAccount" value="azure_d8aedad6a68a0dc1dc8axxxxxxxxxxxx@azure.com" /> <!--the mailAccount that SendGrid gave me through Azure marketplace to use-->
    <add key="mailPassword" value="xxxxxx" /> <!--password taken out, but I used the one from SendGrid-->
</appSettings>

代码编译和运行没有错误,但是当我测试时,从未收到实际的电子邮件(我已经使用了两个不同的Gmail帐户和一个Yahoo帐户)。欢迎任何建议/帮助!

1
我在本地开发机上使用sendgrid发送邮件时遇到了问题,但是一旦我将其部署到服务器/主机上,它就按预期工作了。(值得一提的是) - Glenn Ferrie
1
不确定您在SendGrid方面有哪些可用的内容,但似乎有某种仪表板。有任何迹象吗? - mxmissile
@GlennFerrie 我想我现在可以尝试部署并查看,但我希望在此之前能有更完整的产品。我已经查看了Azure网站上SendGrid的信息,但并没有找到什么有用的。我会再多找一些资料。感谢您的建议! - Robert Prine
1
@RobertPrine - 当我与SendGrid集成时,使用.NET类型SmtpClient和MailMessage会更加顺利。您需要使用sendgrid smtp主机和sendgrid凭据,并确保使用端口587。这里有更多信息:https://sendgrid.com/docs/Integrate/index.html - Glenn Ferrie
1
您的ISP或本地防火墙可能正在阻止出站流量。 - Glenn Ferrie
1个回答

3

似乎您可以使用 dotNet MailMessageSmtpClient,并通过 web.config 文件中配置的 <system.net> <mailSettings> <smpt> 来发送邮件。

发送:

    var mailMessage = new MailMessage(...);
    var smtpClient = new SmtpClient();
    smtpClient.Send(message);

在您的.config文件中配置SendGrid:

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network" from="MYFROM@example.com">
            <network host="smtp.sendgrid.net" password="PASS`"
                     userName="YOURNAME_AZURE_SENDGRID_USERNAME@azure.com" port="587" />
        </smtp>
    </mailSettings>
</system.net>

感谢@Artyom提供的答案!我对Visual Studio MVC相对较新,正在寻找在哪里放置您建议的更改。我假设我会将.config信息添加到web.config中的<appSettings>而不是我的<appSettings>,但我在放置您的“发送”部分时遇到了麻烦。我假设它将取代大部分IdentityConfig.cs,但是当我尝试切换事物时,我遇到了很多构建错误。如果您可以包括有关如何将我的当前代码与您的代码结合的任何其他详细信息,我将非常感激。再次感谢! - Robert Prine
是的,<system.net> 应该放在 <configuration> 下的 web.config 文件中。"发送" 代码,SmtpClient (请参阅 msdn 获取更多示例)将会放在您的 UserManager.SendEmailAsync 方法中。希望能帮到您!请不要忘记投票支持答案。 - Artyom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接