2016-12-28 64 views
0

我在aspnet核心上使用MimeKit,一切都在本地工作,但我得到「身份驗證失敗」當我嘗試在Azure App Service上發送電子郵件時。MimeKit azure gmail - >身份驗證失敗

我必須啓用「允許安全性較低的應用程序」才能使其在本地工作。

這是我使用的代碼:

 using (var client = new SmtpClient()) 
     { 
      await client.ConnectAsync("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); 
      await client.AuthenticateAsync(_emailOptions.Username, _emailOptions.Password); 
      await client.SendAsync(emailMessage); 
      await client.DisconnectAsync(true); 
     } 

我已驗證_emailOptions.Username和_emailOptions.Password是正確的在拋出

 catch (Exception ex) 
     { 
      _log.LogError(new EventId(1), ex, "Username: '{0}', Password: '{1}'", _emailOptions.Username, _emailOptions.Password); 
      throw; 
     } 

的異常記錄他們你有什麼如何解決這個問題的想法?

+0

我想知道你是否在azure和本地應用上使用**相同的用戶名和密碼。 –

+0

是的,我試圖硬編碼的用戶名/密碼。它在本地工作,但不在天藍色。 – user568327

回答

0

我創建一個示例使用MimeKit和MailKit電子郵件框架,以發送電子郵件,我發現代碼工作在本地和蔚藍的罰款,如果我提供有效的用戶名&密碼,並允許安全性較低的應用程序訪問Gmail帳戶(帳戶無法使用兩步驗證)。

using (var client = new SmtpClient()) 
{ 
    MimeMessage mes = new MimeMessage(); 
    mes.From.Add(new MailboxAddress("xxx", "[email protected]")); 
    mes.To.Add(new MailboxAddress("xxx", "[email protected]")); 
    mes.Subject = "hello"; 
    mes.Body = new TextPart("plain") 
    { 
     Text = @"hi, 
     i'm azure! " + DateTime.Now.ToString() 
    }; 

    client.Connect("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); 
    client.Authenticate("username here", "password here"); 
    client.Send(mes); 
    client.Disconnect(true); 
} 

請確保您提供的帳戶是否使用兩步驗證或未啓用安全性較低的應用訪問帳戶。此外,SendGrid是一款基於雲計算的電子郵件服務,您可以試試。

+0

這很奇怪。我們的代碼看起來相同,只是我使用的是異步版本。 – user568327

+0

在啓用雙因素身份驗證並生成特定於應用程序的密碼後,我纔開始工作。自從你的代碼正在工作以後,我給你正確的答案。 – user568327

0

感謝您的指導。我與azure應用程序和Gmail有同樣的問題。閱讀本頁後,我開啓了兩步驗證並生成了應用專用密碼。這也解決了我的問題。