Reputation: 123
I'm using this tutorial for account confirmation email but I don't receive any email or any error here is the code :
AuthMessageSenderOptions.cs
public class AuthMessageSenderOptions
{
public string SendGridUser { get; set; }
public string SendGridKey { get; set; }
}
appSettings.json
"AuthMessageSenderOptions": {
"SendGridUser": "MyUserName",
"SendGridKey": "SG.Xa................ MyKey"
},
EmailSender.cs
public class EmailSender : IEmailSender
{
public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
{
Options = optionsAccessor.Value;
}
public AuthMessageSenderOptions Options { get; } //set only via Secret Manager
public Task SendEmailAsync(string email, string subject, string message)
{
return Execute(Options.SendGridKey, subject, message, email);
}
public Task Execute(string apiKey, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("[email protected]", Options.SendGridUser),
Subject = subject,
PlainTextContent = message,
HtmlContent = message
};
msg.AddTo(new EmailAddress(email));
// Disable click tracking.
// See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
msg.SetClickTracking(false, false);
return client.SendEmailAsync(msg);
}
}
Register.cs
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var confirmationLink = Url.Page(nameof(ConfirmEmail), "Account",
new { code, email = user.Email }, Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by" +
$" <a href='{HtmlEncoder.Default.Encode(confirmationLink)}'>clicking here</a>.");
}
I tried also to try it after publish not only locally but still the same
Upvotes: 0
Views: 683
Reputation: 9490
You can get the result of sending the email and also the error message:
var response = await client.SendEmailAsync(msg);
if (response.StatusCode != HttpStatusCode.OK
&& response.StatusCode != HttpStatusCode.Accepted)
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
throw new Exception($"Failed to send mail to {to}, status code {response.StatusCode}, {errorMessage}");
}
Upvotes: 2