Hi I created an app in asp.net which requires user authentication. I've activated the 'Email confirmation' option. This worked fine with a local db, but once on azure, doesn't work. the code for the email confirmation is as follows:
public Task SendAsync(IdentityMessage message)
{
return Task.Factory.StartNew(() =>
{
sendMail(message);
});
}
void sendMail(IdentityMessage message)
{
#region formatter
string html = message.Body;
#endregion
MailMessage msg = new MailMessage();
msg.From = new MailAddress(ConfigurationManager.AppSettings["Email"].ToString());
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Email"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
}
}
I tried sendgrid, but it didn't seem to work, so I used outlook.
This is the code for the Register part :
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)
{
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
ViewBag.Message = "Check your email and confirm your account. You must confirm your email " + "before you can log in.";
return View("Info");
}
else
{ return View("Error"); }
AddErrors(result);
}
and finally the code for the last part
private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
{
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 clicking <a href=\"" + callbackUrl + "\">here</a>");
return callbackUrl;
}
When your code runs in Azure it may not have access to Outlook, this could explain why emails are not being sent.
SendGrid is a recommended method for sending emails from the Azure function, web job, or any app. There is a good explaination of how to use SendGrid here: https://blog.mailtrap.io/azure-send-email/#What_do_I_need_to_send_emails_from_Azure