最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - SMTP connection fails - Stack Overflow

programmeradmin6浏览0评论

In my Blazor server application, I want to use OAuth2 authentication instead of basic auth. Using Mailkit and .NET 8.0.

private async Task<string> CreateSmtpClientAndSendMailAsync() 
{
    _smtpClient = new SmtpClient();
    
    try
    {
        _smtpClient.Connect(MySmtpHost, MySmtpPort, SecureSocketOptions.StartTls);
    
        var confidentialClientApplicationBuilder = ConfidentialClientApplicationBuilder.Create("xx").WithClientSecret("xx").WithTenantId("xx").Build();
    
        var scopes = new string[] { "/.default" };
    
        var authToken = await confidentialClientApplicationBuilder.AcquireTokenForClient(scopes).ExecuteAsync();
    
        SaslMechanismOAuth2 oAuth2 = new SaslMechanismOAuth2("xxxxx",authToken.AccessToken);
        _smtpClient.Authenticate(oAuth2);
    
        _smtpClient.Send(_mailMessage);
        _smtpClient.Disconnect(true);

        return Resource.mailSentSuccessfully;
    }
    catch (Exception ex)
    {
        // logging...
    }
}

I successfully get an access token, but then authentication fails

(MailKit.Security.AuthenticationException: '535: 5.7.3 Authentication unsuccessful[...]')

In my Blazor server application, I want to use OAuth2 authentication instead of basic auth. Using Mailkit and .NET 8.0.

private async Task<string> CreateSmtpClientAndSendMailAsync() 
{
    _smtpClient = new SmtpClient();
    
    try
    {
        _smtpClient.Connect(MySmtpHost, MySmtpPort, SecureSocketOptions.StartTls);
    
        var confidentialClientApplicationBuilder = ConfidentialClientApplicationBuilder.Create("xx").WithClientSecret("xx").WithTenantId("xx").Build();
    
        var scopes = new string[] { "https://outlook.office/.default" };
    
        var authToken = await confidentialClientApplicationBuilder.AcquireTokenForClient(scopes).ExecuteAsync();
    
        SaslMechanismOAuth2 oAuth2 = new SaslMechanismOAuth2("xxxxx",authToken.AccessToken);
        _smtpClient.Authenticate(oAuth2);
    
        _smtpClient.Send(_mailMessage);
        _smtpClient.Disconnect(true);

        return Resource.mailSentSuccessfully;
    }
    catch (Exception ex)
    {
        // logging...
    }
}

I successfully get an access token, but then authentication fails

(MailKit.Security.AuthenticationException: '535: 5.7.3 Authentication unsuccessful[...]')

Share Improve this question edited Mar 26 at 8:35 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 26 at 8:32 bbWebDevbbWebDev 811 silver badge7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Make sure that your Outlook account is set up to allow SMTP authentication, and ensure you are passing the correct info for your auth.

发布评论

评论列表(0)

  1. 暂无评论