Robert Prine
Robert Prine

Reputation: 2753

SendGrid is not sending an email

I have been following this tutorial: http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset . I have gone through it three times now and checked through several Stackoverflow posts, but I still don't know what I am missing. Through debugging Visual Studio shows that myMessage has all that it needs (email address to deliver to, message subject, message body, who it is coming from, etc), but I am not actually receiving an email for confirmation when I test it. This is the code I currently have:

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(
                            "[email protected]", "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);
        }
    }
}

AccountController:

[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="[email protected]" /> <!--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>

The code builds and runs with no errors, but I never get the actual email when I test it (I have used two separate gmail accounts and a yahoo account). Any advice/help would be appreciated!

Upvotes: 5

Views: 15522

Answers (1)

Artyom
Artyom

Reputation: 3571

It seems you can use dotNet MailMessage and SmtpClient configured using <system.net> <mailSettings> <smpt> in web.config file like so.

Sending:

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

Configuration for SendGrid in your .config:

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network" from="[email protected]">
            <network host="smtp.sendgrid.net" password="PASS`"
                     userName="[email protected]" port="587" />
        </smtp>
    </mailSettings>
</system.net>

Upvotes: 3

Related Questions