0

I'm trying to send automatic email to user to complete registration, I'm testing my app on local host

this is my Register Controller :

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, 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);

            // 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>");

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

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

this is my Email service class

 public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Create the email object first, then add the properties.
        var myMessage = new SendGridMessage();

        // this defines email and name of the sender
        myMessage.From = new MailAddress("no-reply@example.info", "My Example Admin");

        // set where we are sending the email
        myMessage.AddTo(message.Destination);

        myMessage.Subject = message.Subject;

        // make sure all your messages are formatted as HTML
        myMessage.Html = message.Body;

        // Create credentials, specifying your SendGrid username and password.
        var credentials = new NetworkCredential(
             ConfigurationManager.AppSettings["SendGridLogin"],
             ConfigurationManager.AppSettings["SendGridPassword"]
                                                );

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

        // Send the email.
        await transportWeb.DeliverAsync(myMessage);
    }
}

I'm using SendGridSmtpApi 1.3.1 & SendGrid C# cilent library 6.3.4 . Where is the problem , why this don't work ?

joint_ops
  • 312
  • 1
  • 5
  • 20
  • Have you registered an account with SendGrid? – severin Mar 08 '16 at 11:27
  • yes. I have active sendgrid account. – joint_ops Mar 08 '16 at 11:39
  • Ok. I'm not sure if you can send e-mail using just the credentials, you might have to create an ApiKey on your SendGrid account. Personally I send using only the ApiKey, like this: var transportWeb = new SendGrid.Web(); – severin Mar 08 '16 at 11:45
  • Sorry, the braces were just to point to where the ApiKey goes, it's just a regular string value. Like this: var transportWeb = new SendGrid.Web("SG.pPBVADWWawd21Eawdwad"); – severin Mar 08 '16 at 12:20
  • I've implemented this, like so: var apiKey = "apikeystring"; var transportWeb = new SendGrid.Web(apiKey); and it still don't works – joint_ops Mar 08 '16 at 12:38
  • Is the domain you are attempting to send from registered on your SendGrid account? – severin Mar 08 '16 at 12:54

1 Answers1

1

Because you are making an asynchronous call, it is possible your program is exiting before the call a chance to complete. Therefore, the following is necessary if you would like to block until the call is complete, before your program proceeds:

transportWeb.DeliverAsync(message).Wait();

Alternatively, you can "Wait() or Result" from the calling function depending on your desired result.

For more information, check out the following:

What happens while waiting on a Task's Result?

Await on a completed task same as task.Result?

Community
  • 1
  • 1
Elmer Thomas
  • 2,068
  • 2
  • 13
  • 11
  • 1
    While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value. – Benjamin W. Mar 11 '16 at 06:50
  • 1
    Thanks for the follow up Benjamin! I've edited my answer to hopefully be more helpful. – Elmer Thomas Mar 12 '16 at 16:05