.Net Core 2.0无法发送邮件:更新后SendMailAsync返回false求解决方案
Hey, let's figure out why your SendMailAsync() is returning false after the update. Here are some targeted fixes and checks to get your emails working again:
Fix the asynchronous method handling
Your current code usesIsCompletedSuccessfullyto check if the email sent, but this is a mistake with async operations. This property only tells you the task finished—it doesn't distinguish between success and failure (like if an exception was thrown mid-operation). Plus, you're not actually awaiting the async method, which can lead to race conditions or unhandled errors.Rewrite your
SendMessageAsyncmethod to properly useawaitand error handling:public async Task<bool> SendMessageAsync() { this.Message = new MailMessage(this.MailFrom.ToString(), this.MailTo.ToString(), this.GetSubject(), this.GetMessageBody()); try { await this.Client.SendMailAsync(this.Message); return true; } catch (Exception ex) { // Log the error using your injected ILogger // _logger.LogError(ex, "Failed to send order confirmation email"); return false; } }Don't forget to update the
IEmailinterface to returnTask<bool>instead ofbooltoo, since this is now a proper async method.Verify your SMTP server and credentials
Even though it worked before, updates can sometimes disrupt server connections or credential validity:- Confirm your local SMTP server (localhost:25) is still running and listening on port 25. Test the connection with PowerShell:
Test-NetConnection localhost -Port 25 - Double-check your
NetworkCredentialusername ("postmaster") and password—if you updated your Yandex account password or enabled app-specific passwords, you'll need to sync that here. - Yandex might have changed its SMTP security settings; ensure you're allowed to send via SMTP from your account (some providers require enabling "Less secure apps" or generating app passwords for third-party clients).
- Confirm your local SMTP server (localhost:25) is still running and listening on port 25. Test the connection with PowerShell:
Add logging to catch specific errors
Blindly returningfalsedoesn't tell you why the send failed. Inject anILogger<Email>into your class to log exceptions, which will give you precise details like connection timeouts, authentication failures, or invalid recipient addresses:private readonly ILogger<Email> _logger; public Email(IServiceProvider service, ILogger<Email> logger) { _logger = logger; // Rest of your initialization code... }Log errors in the catch block mentioned earlier—this is the fastest way to pinpoint the root cause.
Validate the recipient email address
Check ifUserEmail = service.GetRequiredService<IHttpContextAccessor>().HttpContext.User.Identity.Nameis actually returning a valid email address. After an update, your identity setup might have changed (e.g.,Identity.Namenow returns a username instead of an email). Log this value to confirm it's correct before creating theMailToaddress.Consider modern email libraries (as a fallback)
If you've exhausted all other options and still have issues with the built-inSmtpClient, libraries like MailKit are more robust, actively maintained, and handle edge cases better than the legacySmtpClient. But I'd recommend fixing the async handling and checking your configuration first before switching libraries.
内容的提问来源于stack exchange,提问作者konstantinos Dms

