Advertisement
hubert17

Send email by using MailKit with Gmail

Sep 19th, 2018
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.97 KB | None | 0 0
  1. // Send email by using MailKit with Gmail
  2.  
  3. using (var emailClient = new SmtpClient())
  4. {
  5.     // https://console.developers.google.com
  6.     var secrets = new ClientSecrets
  7.     {
  8.         ClientId = "",
  9.         ClientSecret = ""
  10.     };
  11.  
  12.     // Generating a refresh token - https://www.youtube.com/watch?v=hfWe1gPCnzc
  13.     var token = new TokenResponse { RefreshToken = "YourRefreshToken" };
  14.     var googleCredentials = new UserCredential(new GoogleAuthorizationCodeFlow(
  15.         new GoogleAuthorizationCodeFlow.Initializer
  16.         {
  17.             ClientSecrets = secrets
  18.         }), SmtpUsername, token);
  19.  
  20.     emailClient.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
  21.    
  22.     await googleCredentials.GetAccessTokenForRequestAsync();
  23.     var oauth2 = new SaslMechanismOAuth2(SmtpUsername, googleCredentials.Token.AccessToken);
  24.     emailClient.Authenticate(oauth2);
  25.  
  26.     await emailClient.SendAsync(message); // MimeMessage
  27.     emailClient.Disconnect(true);
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement