public async Task <SaslMechanismOAuth2> Token() { var clientSecrets = new ClientSecrets { ClientId = Id, ClientSecret = Secret }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(Mail, CancellationToken.None); //if (authCode.ShouldRequestAuthorizationCode(credential.Token)) // await credential.RefreshTokenAsync(CancellationToken.None); // Refresh Token if needed (1h timeout) if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); return(oauth2); }
/// <summary> /// Get OAUTH2 token needed to Authenticate SMTP client /// </summary> /// <PARAM name="userAccount"></PARAM> /// <PARAM name="clientSecrets"></PARAM> /// <PARAM name="accessScopes"></PARAM> /// <returns></returns> public static SaslMechanism GetAuth2Token(string userAccount, ClientSecrets clientSecrets, string[] accessScopes) { var AppFileDataStore = new FileDataStore("CredentialCacheFolder", false); var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = AppFileDataStore, Scopes = accessScopes, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets , accessScopes , userAccount , CancellationToken.None , AppFileDataStore).Result; if (credential.Token.IsExpired(SystemClock.Default)) { credential.RefreshTokenAsync(CancellationToken.None); } // Note: We use credential.UserId here instead of GMail account because the user *may* have chosen a // different GMail account when presented with the browser window during the authentication process. SaslMechanism oauth2; oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); return(oauth2); }
public override async Task AuthenticateAsync(CancellationToken cancellationToken) { var emailAccount = _db.EmailAccounts.FirstOrDefault(ea => ea.Email == Account.Email); if (emailAccount == null) { throw new InvalidOperationException($"No email account with address: {Account.Email}"); } if (string.IsNullOrEmpty(emailAccount.AccessToken) || string.IsNullOrEmpty(emailAccount.RefreshToken)) { throw new InvalidOperationException($"No token granted for email account: {emailAccount.Email}"); } var refreshTokenRequest = new RefreshTokenRequest { ClientId = emailAccount.Username, Secret = emailAccount.Password, Tenant = emailAccount.Email.Split('@')[1], RefreshToken = emailAccount.RefreshToken }; refreshTokenRequest.Scopes.AddRange(M365Helper.EmailScopes); var token = await OAuth2Helper.RefreshTokenAsync(refreshTokenRequest); emailAccount.LastUpdateAccessToken = DateTime.UtcNow; _db.EmailAccounts.Update(emailAccount); await _db.SaveChangesAsync(cancellationToken); var auth = new SaslMechanismOAuth2(emailAccount.Email, token.AccessToken); await Client.AuthenticateAsync(auth, cancellationToken); }
public IActionResult Contact(ContactViewModel contact) { SaslMechanismOAuth2 oauth2 = _googleToken.Token().Result; MimeMessage message = new MimeMessage(); message.From.Add(new MailboxAddress("Contact", "*****@*****.**")); message.To.Add(new MailboxAddress("Me", _config.GetValue <string>("Google:Mail"))); message.Subject = $"[Contact from your website] { contact.Subject }"; BodyBuilder builder = new BodyBuilder { HtmlBody = $"<div><span style='font-weight: bold'>De</span> : {contact.Name} </div>" + $"<div><span style='font-weight: bold'>Mail</span> : {contact.Email}</div>" + $"<div style='margin-top: 30px'>{contact.Message}</div>" }; message.Body = builder.ToMessageBody(); using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587); // use the OAuth2.0 access token obtained above client.Authenticate(oauth2); client.Send(message); client.Disconnect(true); FlashMessage.Confirmation("Mail sent with success"); ModelState.Clear(); return(View()); } }
// Connexion OAuth2 vers une messagerie gmail private async void connexionGmail() { var clientSecrets = new ClientSecrets { ClientId = "294403304718-bptp75nbk64qi2klfvjidqvklmcqp9vm.apps.googleusercontent.com", ClientSecret = "0PuD1zj5uq62HvWZx1t9RrKc" }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(I_Connexion_Login.Text, CancellationToken.None); if (authCode.ShouldRequestAuthorizationCode(credential.Token)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); using (var client = new ImapClient()) { await client.ConnectAsync("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect); // non paramètrable await client.AuthenticateAsync(oauth2); await client.DisconnectAsync(true); } }
private async Task ConfigurarOAuth2Async() { var clientSecrets = new ClientSecrets { ClientId = _configuration["MsjConfiguration:Gmail:ClientId"], ClientSecret = _configuration["MsjConfiguration:Gmail:ClientSecret"] }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore(_configuration["MsjConfiguration:Gmail:CredentialLocation"], true), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(_configuration["MsjConfiguration:Gmail:UserId"], CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } oAuth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); }
/// <summary> /// Odeslání emailu přes GMail /// </summary> /// <param name="email">emailová adresa příjemce</param> /// <param name="subject">předmět mailu</param> /// <param name="text">plain textová podoba obsahu</param> /// <returns>nic</returns> public async Task SendEmailAsync(string email, string subject, string text) { var message = new MimeMessage(); // vytvoření mailové zprávy message.From.Add(new MailboxAddress(_configuration["GmailSender:FromName"], _configuration["GmailSender:From"])); message.To.Add(new MailboxAddress(email, email)); message.Subject = subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.TextBody = text; bodyBuilder.HtmlBody = text; message.Body = bodyBuilder.ToMessageBody(); // GMail OAUTH Flow var clientSecrets = new ClientSecrets { ClientId = _configuration["GmailSender:AppID"], ClientSecret = _configuration["GmailSender:AppSecret"] }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(_configuration["GmailSender:AccountID"], CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); if (Int32.TryParse(_configuration["GmailSender:Port"], out int port) == false) { port = 0; // v konfiguraci je port uveden jako text, potřebujeme ho jako číslo } using (var client = new SmtpClient()) // vytvoření SMTP klienta { await client.ConnectAsync(_configuration["GmailSender:Server"], port, SecureSocketOptions.StartTlsWhenAvailable); await client.AuthenticateAsync(oauth2); await client.SendAsync(message); await client.DisconnectAsync(true); } }
static void AssertSimpleOAuth2(SaslMechanismOAuth2 sasl, string prefix) { const string expected = "dXNlcj11c2VybmFtZQFhdXRoPUJlYXJlciBwYXNzd29yZAEB"; string challenge; Assert.IsTrue(sasl.SupportsInitialResponse, "SupportsInitialResponse"); challenge = sasl.Challenge(string.Empty); Assert.IsTrue(sasl.IsAuthenticated, "IsAuthenticated"); Assert.AreEqual(expected, challenge, "Challenge"); Assert.AreEqual(string.Empty, sasl.Challenge(string.Empty), "Already authenticated."); }
public void TestSimpleOAuth2() { var credentials = new NetworkCredential("username", "password"); SaslMechanismOAuth2 sasl; sasl = new SaslMechanismOAuth2(credentials); AssertSimpleOAuth2(sasl, "NetworkCredential"); sasl = new SaslMechanismOAuth2("username", "password"); AssertSimpleOAuth2(sasl, "user/pass"); }
public void TestArgumentExceptions() { var credentials = new NetworkCredential("username", "password"); var uri = new Uri("smtp://localhost"); SaslMechanism sasl; Assert.Throws <ArgumentNullException> (() => new SaslException(null, SaslErrorCode.MissingChallenge, "message")); sasl = new SaslMechanismCramMd5(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(uri, null)); Assert.Throws <NotSupportedException> (() => sasl.Challenge(null)); sasl = new SaslMechanismDigestMd5(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(uri, null)); Assert.Throws <NotSupportedException> (() => sasl.Challenge(null)); sasl = new SaslMechanismLogin(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, null)); Assert.Throws <NotSupportedException> (() => sasl.Challenge(null)); sasl = new SaslMechanismNtlm(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(uri, null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismOAuth2(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(uri, null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismPlain(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismScramSha1(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(uri, null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismScramSha256(uri, credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(uri, null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); }
public async Task <bool> SendEmailAsync(string destinationMail, string subject, string msg) { if (!InternetAddress.TryParse(destinationMail, out InternetAddress to)) { return(false); } if (!InternetAddress.TryParse(Settings.EmailAddress, out InternetAddress from)) { return(false); } try { MimeMessage message = new MimeMessage(); message.Subject = subject; message.From.Add(from); message.To.Add(to); message.Body = new TextPart(TextFormat.Html) { Text = msg }; message.ReplyTo.Add(from); var cred = await GetCredentials(); using (SmtpClient client = new SmtpClient()) { await client.ConnectAsync(Settings.Domain, Settings.Port, SecureSocketOptions.StartTlsWhenAvailable); var oauth = new SaslMechanismOAuth2(cred.UserId, cred.Token.AccessToken); await client.AuthenticateAsync(oauth); await client.SendAsync(message); await client.DisconnectAsync(true); } return(true); } catch (Exception ex) { Logger.LogError(ex, "An error occured while attempting to send a mail."); } return(false); }
public async Task SendEmail(MimeMessage mimeMessage) { var googleCredentials = GetCredentials(); if (googleCredentials.Token.IsExpired(SystemClock.Default)) { await googleCredentials.RefreshTokenAsync(CancellationToken.None); } using (var client = new SmtpClient()) { client.Connect(ConfigurationManager.AppSettings[gmailSmtpServerSetting], 587, SecureSocketOptions.StartTls); var oauth2 = new SaslMechanismOAuth2(googleCredentials.UserId, googleCredentials.Token.AccessToken); client.Authenticate(oauth2); client.Send(mimeMessage); client.Disconnect(true); } }
private async Task SendEmail(MimeMessage message) { var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes, User = streamworkEmailAddress }.FromCertificate(new X509Certificate2(certificatePath, privateKeyPassword, X509KeyStorageFlags.MachineKeySet))); // Token gets put inside credential. At least cross your f*****g fingers that it does. await credential.RequestAccessTokenAsync(CancellationToken.None); using var client = new SmtpClient(); client.Connect(gmailSmtp, gmailPort); var oauth2 = new SaslMechanismOAuth2(streamworkEmailAddress, credential.Token.AccessToken); client.Authenticate(oauth2); client.Send(message); client.Disconnect(true); }
static async Task OAuthAsync(ImapClient client) { var clientSecrets = new ClientSecrets { ClientId = "XXX.apps.googleusercontent.com", ClientSecret = "XXX" }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new [] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); // Note: For a web app, you'll want to use AuthorizationCodeWebApp instead. var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(GMailAccount, CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } // Note: We use credential.UserId here instead of GMailAccount because the user *may* have chosen a // different GMail account when presented with the browser window during the authentication process. SaslMechanism oauth2; if (client.AuthenticationMechanisms.Contains("OAUTHBEARER")) { oauth2 = new SaslMechanismOAuthBearer(credential.UserId, credential.Token.AccessToken); } else { oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); } await client.AuthenticateAsync(oauth2); }
static async Task AuthenticateAsync(ImapClient client) { var options = new PublicClientApplicationOptions { ClientId = "Application (client) ID", TenantId = "Directory (tenant) ID", RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient" }; var publicClientApplication = PublicClientApplicationBuilder .CreateWithApplicationOptions(options) .Build(); var scopes = new string[] { "email", "offline_access", "https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP //"https://outlook.office.com/POP.AccessAsUser.All", // Only needed for POP //"https://outlook.office.com/SMTP.AccessAsUser.All", // Only needed for SMTP }; var authToken = await publicClientApplication.AcquireTokenInteractive(scopes).WithLoginHint(ExchangeAccount).ExecuteAsync(cancellationToken); await publicClientApplication.AcquireTokenSilent(scopes, authToken.Account).ExecuteAsync(cancellationToken); // Note: We use authToken.Account.Username here instead of ExchangeAccount because the user *may* have chosen a // different Microsoft Exchange account when presented with the browser window during the authentication process. SaslMechanism oauth2; if (client.AuthenticationMechanisms.Contains("OAUTHBEARER")) { oauth2 = new SaslMechanismOAuthBearer(authToken.Account.Username, authToken.AccessToken); } else { oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken); } await client.AuthenticateAsync(oauth2); }
public void TestSimpleOAuth2() { var credentials = new NetworkCredential("username", "password"); var uri = new Uri("smtp://localhost"); SaslMechanismOAuth2 sasl; sasl = new SaslMechanismOAuth2(credentials); AssertSimpleOAuth2(sasl, "NetworkCredential"); sasl = new SaslMechanismOAuth2("username", "password"); AssertSimpleOAuth2(sasl, "user/pass"); sasl = new SaslMechanismOAuth2(uri, credentials); AssertSimpleOAuth2(sasl, "uri/credentials"); sasl = new SaslMechanismOAuth2(uri, "username", "password"); AssertSimpleOAuth2(sasl, "uri/user/pass"); }
private async Task SendMailAsync(MimeMessage message) { using (var client = new SmtpClient()) { var credential = new ServiceAccountCredential(new ServiceAccountCredential .Initializer(_serviceAccount) { Scopes = new[] { "https://mail.google.com/" }, User = _sender }.FromPrivateKey(_serviceAccountPrivateKey)); await credential.RequestAccessTokenAsync(CancellationToken.None); var oauth2 = new SaslMechanismOAuth2(_sender, credential.Token.AccessToken); await client.ConnectAsync("smtp.gmail.com", 587); await client.AuthenticateAsync(oauth2); await client.SendAsync(message); await client.DisconnectAsync(true); } }
public void SendMail(IConfiguration configuration, string subjectTest, string bodyText) { if (string.IsNullOrEmpty(configuration["smtpUser"]) || string.IsNullOrEmpty(configuration["mailAddress"])) { return; } bool modernAuth = true; if (string.IsNullOrEmpty(configuration["smtpClientID"])) { modernAuth = false; } Console.WriteLine($"{DateTime.Now}: Sending email..."); try { string[] addresses = configuration["mailAddress"].Split(','); var message = new MimeMessage(); message.From.Add(new MailboxAddress("StreamCapture", configuration["smtpUser"])); foreach (string address in addresses) { message.To.Add(new MailboxAddress(address, address)); } message.Subject = subjectTest + " (18.04)"; var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = bodyText; message.Body = bodyBuilder.ToMessageBody(); SaslMechanismOAuth2 oauth2 = null; if (modernAuth) { //oauth2 for microsoft graph // // A few notes as this was tough.... // - Setup https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app // - Be sure and add right permissions under API permission for the app (in this case, it was smtp) // - Permissions must be delgated because as of 9/30/21, you couldn't assign smtp to an app // - You must have admin consent enabled (again part of the api permissions screen) // - There's a non-zero chance that in the future, smtp will be deprecated entirely // // https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md // https://github.com/jstedfast/MailKit/issues/989 // NetworkCredential networkCredential = new NetworkCredential(configuration["smtpUser"], configuration["smtpPass"]); var scopes = new string[] { //"email", //"offline_access", //"https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP //"https://outlook.office.com/POP.AccessAsUser.All", // Only needed for POP "https://outlook.office.com/SMTP.Send", // Only needed for SMTP }; //Get oauth2 token for smtp client var app = PublicClientApplicationBuilder.Create(configuration["smtpClientID"]).WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs).Build(); var Task = app.AcquireTokenByUsernamePassword(scopes, networkCredential.UserName, networkCredential.SecurePassword).ExecuteAsync(); Task.Wait(); var authToken = Task.Result; oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken); } //Actually send message now using (var client = new SmtpClient()) { client.Connect(configuration["smtpServer"], Convert.ToInt16(configuration["smtpPort"]), false); if (!modernAuth) //msft is about to turn this option off { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(configuration["smtpUser"], configuration["smtpPass"]); } else { client.Authenticate(oauth2); } client.Send(message); client.Disconnect(true); } } catch (Exception e) { //swallow email exceptions Console.WriteLine($"{DateTime.Now}: ERROR: Problem sending mail. Error: {e.Message}"); } }
public async Task <ImapClient> GetImapClient(string emailAddress) { IMail accountManager = null; GnomeOnlineAccount gnomeAccount = null; var mailAccounts = (await GetAll()).Where(a => a.Interfaces.Contains(dbusMailAccountServiceName)); var dbusSessionConnection = Connection.Session; foreach (var account in mailAccounts) { var dbusAccountManager = dbusSessionConnection.CreateProxy <IMail>(dbusServiceName, account.DbusObjectPath); if (emailAddress == await dbusAccountManager.GetEmailAddressAsync()) { accountManager = dbusAccountManager; gnomeAccount = account; } } if (null == accountManager) { throw new ArgumentException("emailAddress not found in Gnome OnlineAccounts"); } var imapClient = new ImapClient(); var port = 143; if (await accountManager.GetImapUseSslAsync()) { port = 993; } await imapClient.ConnectAsync( await accountManager.GetImapHostAsync(), port ); // Determine authentication-scheme var sessionConnection = Connection.Session; var username = await accountManager.GetImapUserNameAsync(); SaslMechanism cred = null; if (gnomeAccount.Interfaces.Contains(dbusOAuth2BasedAuth) || gnomeAccount.Interfaces.Contains(dbusOAuthBasedAuth)) { var oAuth2Manager = sessionConnection.CreateProxy <IOAuth2Based>(dbusServiceName, gnomeAccount.DbusObjectPath); (var token, var expiry) = await oAuth2Manager.GetAccessTokenAsync(); cred = new SaslMechanismOAuth2(username, token); } else if (gnomeAccount.Interfaces.Contains(dbusPasswordBasedAuth)) { var passwordManager = sessionConnection.CreateProxy <IPasswordBased>(dbusServiceName, gnomeAccount.DbusObjectPath); var password = await passwordManager.GetPasswordAsync("imap-password"); cred = new SaslMechanismLogin(username, password); } else { throw new Exception("Could not extract credentials from Gnome"); } await imapClient.AuthenticateAsync(cred); return(imapClient); }
/// <summary> /// Utilizes MailKit and Google APIs to send an email /// </summary> /// <param name="person">User's Email</param> /// <returns></returns> private async Task EmailContestantAsync(Person person, string email, Event details) { const string GMailAccount = "*****@*****.**"; var clientSecrets = new ClientSecrets { ClientId = Services.AuthKeys.Google_OAuth, ClientSecret = Services.AuthKeys.Google_Client, }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new[] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); // Note: For a web app, you'll want to use AuthorizationCodeWebApp instead. var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(GMailAccount, CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); var message = new MimeMessage(); message.From.Add(new MailboxAddress("Happnin", "*****@*****.**")); message.To.Add(new MailboxAddress($"{person.FullName}", email)); message.Subject = "Please Confirm"; message.Body = new TextPart("plain") { Text = $"Hello {person.FirstName} \n" + $"You have signed up for \n" + $"{details.EventName}\n" + $"on {details.EventDate} \n" + $"\n" + $"Enjoy!\n" + $"Happnin'\n" //somekind of confirm button here }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587); // use the OAuth2.0 access token obtained above client.Authenticate(oauth2); client.Send(message); client.Disconnect(true); } }
private void Monitor(BackgroundWorker bw, int sleepPeriod, int reconnectPeriod, CancellationToken token) { while (!bw.CancellationPending) { try { while (!bw.CancellationPending) { if (GoogleAccessTokenExpireTime < DateTime.Now) { RefreshTokenFromGoogle(); } else { using (var client = new ImapClient()) { // For demo-purposes, accept all SSL certificates client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("imap.gmail.com", 993, true); var oauth2 = new SaslMechanismOAuth2(UserEmail, GoogleAccessToken); client.Authenticate(oauth2); var inbox = client.Inbox; inbox.Open(FolderAccess.ReadWrite); var query = SearchQuery.DeliveredAfter(SetupDate).And(SearchQuery.FromContains(FromEmailAddressForUser).Or(SearchQuery.FromContains(FromEmailAddressForMerchant))).And(SearchQuery.NotSeen); foreach (var uid in inbox.Search(query)) { var message = inbox.GetMessage(uid); PostDonation(((MimeKit.MailboxAddress)message.From[0]).Address, message.Subject); inbox.AddFlags(uid, MessageFlags.Seen, true); if (bw.CancellationPending) { break; } } client.Disconnect(true); this.Invoke(new MethodInvoker(delegate { ucHome1.TbError.Text = ""; ucHome1.TbError.Visible = false; })); if (bw.CancellationPending) { break; } var cancelled = token.WaitHandle.WaitOne(sleepPeriod * 1000); if (cancelled) { break; } } } } } catch (Exception ex) { this.Invoke(new MethodInvoker(delegate { ucHome1.TbError.Text = ex.Message; ucHome1.TbError.Visible = true; })); if (reconnectPeriod == 0) { break; } else { this.Invoke(new MethodInvoker(delegate { ucHome1.TbError.Text += "; Waiting for retry.."; })); var cancelled = token.WaitHandle.WaitOne(reconnectPeriod * 1000); if (cancelled) { break; } } } if (bw.CancellationPending) { break; } } }
public void TestArgumentExceptions() { var credentials = new NetworkCredential("username", "password"); var uri = new Uri("smtp://localhost"); SaslMechanism sasl; Assert.Throws <ArgumentNullException> (() => new SaslException(null, SaslErrorCode.MissingChallenge, "message")); sasl = new SaslMechanismCramMd5(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(uri, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5(null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismCramMd5("username", null)); Assert.Throws <NotSupportedException> (() => sasl.Challenge(null)); sasl = new SaslMechanismDigestMd5(credentials) { Uri = uri }; Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(uri, (string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5(null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismDigestMd5("username", null)); Assert.Throws <NotSupportedException> (() => sasl.Challenge(null)); sasl = new SaslMechanismLogin(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin((Uri)null, Encoding.UTF8, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin((Uri)null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin((Uri)null, Encoding.UTF8, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, Encoding.UTF8, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, Encoding.UTF8, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin((Uri)null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin((Encoding)null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(Encoding.UTF8, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(Encoding.UTF8, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin(null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismLogin("username", null)); Assert.Throws <NotSupportedException> (() => sasl.Challenge(null)); sasl = new SaslMechanismNtlm(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm((Uri)null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm((Uri)null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(uri, (string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm(null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismNtlm("username", null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismOAuth2(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2((Uri)null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2((Uri)null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(uri, (string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2(null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismOAuth2("username", null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismPlain(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain((Uri)null, Encoding.UTF8, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain((Uri)null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain((Uri)null, Encoding.UTF8, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, Encoding.UTF8, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, Encoding.UTF8, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain((Uri)null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain((Encoding)null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(Encoding.UTF8, null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(Encoding.UTF8, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain(null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismPlain("username", null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismScramSha1(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(uri, (string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1((string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha1("username", null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); sasl = new SaslMechanismScramSha256(credentials); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(null, credentials)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(uri, null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(null, "username", "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(uri, (string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(uri, "username", null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256(null)); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256((string)null, "password")); Assert.Throws <ArgumentNullException> (() => new SaslMechanismScramSha256("username", null)); Assert.DoesNotThrow(() => sasl.Challenge(null)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create(null, uri, Encoding.UTF8, credentials)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", null, Encoding.UTF8, credentials)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", uri, null, credentials)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", uri, Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create(null, uri, credentials)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", null, credentials)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", uri, null)); Assert.Throws <ArgumentNullException> (() => SaslMechanism.SaslPrep(null)); }
public ActionResult EnviarEmail(Email model, string[] taginputcc, HttpPostedFileBase[] files) { /* * string pathServer = Server.MapPath("~/App_Data/CotizacionesProject-77144679de36.p12"); * X509Certificate2 cert = new X509Certificate2(pathServer, "notasecret", X509KeyStorageFlags.Exportable); * var credential = new ServiceAccountCredential(new ServiceAccountCredential * .Initializer("*****@*****.**") * { * // Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes * Scopes = new[] { "https://mail.google.com/", "https://www.googleapis.com/auth/userinfo.profile" }, * User = model.EmailDesde * }.FromCertificate(cert));*/ //Recibo la lista de emails CC List <string> emailscc = taginputcc[0].Split(',').ToList <string>(); if (taginputcc.Length > 1) { //es mayor a 1 cuando se envia email masivo emailscc = taginputcc.ToList(); } string nombreCaperta = ""; Cotizacion cotizacion = null; Tienda tienda = db.Tienda.Where(e => e.Id == model.IdTienda).FirstOrDefault(); nombreCaperta = "PDFEmpresas"; cotizacion = tienda.Cotizaciones.Where(c => c.Id == model.IdDocumento).FirstOrDefault(); string fullPathDocumento = null; if (model.NombreDocumento != null && model.NombreDocumento != "") { fullPathDocumento = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/img/" + nombreCaperta + "/" + tienda.Id), model.NombreDocumento); } bool emailEnviadoCorrectamente = false; FileStream stmcheck2Documento = null; try { using (var client = new MailKit.Net.Smtp.SmtpClient()) { var message = new MimeMessage(); message.From.Add(new MailboxAddress(model.EmailDesde, model.EmailDesde)); bool destinatariosValidos = false; if (model.EmailPara != "" && model.EmailPara != null) { message.To.Add(new MailboxAddress(model.NombreDestinatario, model.EmailPara)); destinatariosValidos = true; } string ccsString = ""; //**** Agregar emails a CC **** if (!emailscc[0].Equals("")) { ccsString += " CCs: "; foreach (var cc in emailscc) { ccsString += cc + ";"; message.Cc.Add(new MailboxAddress(cc, cc)); destinatariosValidos = true; } } if (destinatariosValidos == false) { TempData["msgEmail"] = "Error: No se ingresaron destinatarios válidos."; return(RedirectToAction("ResultadoMail", new { msgTest = "a" })); } message.Subject = model.Tema; String mensaje = HttpUtility.HtmlDecode(model.Mensaje); //mensaje = ContenidoEmail.PrepararMensajeAGuardarOEnviar(mensaje); var body = new TextPart("html") { Text = mensaje }; //---------- var multipart = new Multipart("mixed"); multipart.Add(body); //********DOCUMENTO************* if (fullPathDocumento != null) { try { stmcheck2Documento = System.IO.File.OpenRead(fullPathDocumento); } catch (Exception ex) { string m = ex.Message; } var attachmentCotizacion = new MimePart("file", "pdf"); try { attachmentCotizacion.Content = new MimeContent(stmcheck2Documento, ContentEncoding.Default); attachmentCotizacion.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment); attachmentCotizacion.ContentTransferEncoding = ContentEncoding.Base64; attachmentCotizacion.FileName = Path.GetFileName(fullPathDocumento); multipart.Add(attachmentCotizacion); } catch { //logging as needed } } if (files != null) { foreach (HttpPostedFileBase file in files) { if (file == null) { continue; } MimePart attachment = new MimePart(file.ContentType); attachment.Content = new MimeContent(file.InputStream, ContentEncoding.Default); attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment); attachment.ContentTransferEncoding = ContentEncoding.Base64; attachment.FileName = file.FileName; multipart.Add(attachment); } } message.Body = multipart; try { client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls); client.Timeout = 12000; } catch (Exception e) { TempData["msgEmail"] = "Se encontraron problemas de conexión. Por favor, revisar su conexión a internet."; return(RedirectToAction("ResultadoMail", new { msgTest = "4" })); //ViewBag.Message = "El no se ha podido enviar. Por favor, revisar su conexión a internet"; } try { var oauth2 = new SaslMechanismOAuth2(model.EmailDesde, model.Token); client.Authenticate(oauth2); } catch (Exception e) { return(RedirectToAction("ErrorSeguridad", "Email")); } try { client.Send(message); client.Disconnect(true); client.Dispose(); } catch (Exception e) { TempData["msgEmail"] = "Aviso: No se pudo comprobar si se envió el email correctamente. " + "<br />Causa probable es tamaño de los archivos y el tiempo que tomó enviarlos. " + "<br />Por favor comprobar envío en su correo electrónico." + "<br />No se generará un registro de envío en el sistema. Puede crear uno manual de ser necesario."; return(RedirectToAction("ResultadoMail", new { msgTest = "3" })); } //Thread.Sleep(5000); //----------REGISTRO MAIL-------- //RegistroEnvio regEnvio = new RegistroEnvio(plantillaemail, true, "EMAIL", // model.EmailDesde, model.EmailPara + ccsString, catalogo, ""); //regEnvio.TerminarAsociacionRegistro(db, cotizacion); emailEnviadoCorrectamente = true; } } catch (Exception e) { TempData["msgEmail"] = "Error manejando la solicitud: Un problema de conexión a Internet ha impedido enviar el Email, por favor, intente nuevamente."; return(RedirectToAction("ResultadoMail", new { msgTest = "3" })); } if (stmcheck2Documento != null) { stmcheck2Documento.Close(); } //se eliminan los archivos enviados var basePath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/img/" + nombreCaperta + "/"), tienda.Id.ToString()); if (Directory.Exists(basePath)) { string[] fileNames = Directory.GetFiles(basePath); foreach (string fileName in fileNames) { if (fileName == fullPathDocumento) { System.IO.File.Delete(fileName); } } } //Asegurar mantener login abierto Usuario usuario = db.Usuarios.Where(u => u.Id == model.IdUsuario).FirstOrDefault(); if (usuario != null && Session["Id"] == null) { Session["Id"] = usuario.Id; Session["Nombre"] = usuario.NombreUsuario; Session["Rol"] = usuario.RolUsuario; Session["EmpresaId"] = tienda.Id; //FuncionesGlobalesControllers.RefreshSession(this, empresa, user); } if (emailEnviadoCorrectamente) { //ReporteErrores.CrearReporteError(db, // "Email enviado correctamente. user: "******" empresa: " + empresa.Nombre ); TempData["msgEmail"] = "Email enviado correctamente"; return(RedirectToAction("ResultadoMail", new { msgTest = "2" })); } else { TempData["msgEmail"] = "Error manejando la solicitud: Un problema de conexión a Internet ha impedido enviar el Email, por favor, intente nuevamente."; return(RedirectToAction("ResultadoMail", new { msgTest = "1" })); } }
protected void Page_Load(object sender, EventArgs e) { var element = Utils.LoadConfigurationFromWebConfig("Google"); var client = new Google( element.ClientId, element.ClientSecret, element.Scope, element.RedirectUri); //var element = Utils.LoadConfigurationFromWebConfig("WindowsLive"); //var client = new WindowsLive(element.ClientId, element.ClientSecret, element.Scope, element.RedirectUri); var client1 = new SmtpClient(new ProtocolLogger(@"c:\temp\smtp.log")); try { client.HandleAuthorizationCodeResponse(); litAccessToken.Text = client.AccessToken; litState.Text = client.GetStateObject(string.Empty).GetValue("one"); var message = new MimeKit.MimeMessage(); message.From.Add(new MailboxAddress("SK Dutta", "*****@*****.**")); //message.To.Add(new MailboxAddress("SK Dutta", "*****@*****.**")); message.To.Add(new MailboxAddress("Kim Jung", "*****@*****.**")); message.Subject = "Test Subject 210010"; message.Body = new TextPart("plain") { Text = @"Hey" }; using (client1) { client1.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls); var oauth2 = new SaslMechanismOAuth2("*****@*****.**", client.AccessToken); client1.Authenticate(oauth2); client1.Send(message); client1.Disconnect(true); } } catch (Exception ex) { litError.Text = ex.Message; //litError.Text = client1.ProtocolLogger //return; } finally { } //try //{ // UserInfo userInfo = client.GetUserInfo(); // litFullName.Text = userInfo.FullName; // litEmail.Text = userInfo.Email; // ProfilePicture picture = new ProfilePicture(userInfo.PictureUrl, true); // ImageHtml = picture.HtmlPart; // picture.Resize(200); // ImageResizedHtml = picture.HtmlPart; // //DomainUsers googleDomainUsers = new DomainUsers(client.AccessToken); // //litDirectoryString.Text = googleDomainUsers.ToJsonString(); //} //catch (WebException webEx) //{ // HttpError httpError = new HttpError(webEx.Response); // litError.Text = httpError.StatusDescription; //} //catch (Exception ex) //{ // litError.Text = ex.Message; //} //CalendarList calendarList = new CalendarList(client.AccessToken); //litCalendarString.Text = calendarList.ToJsonString(); //ContactsGroup contactGroup = new ContactsGroup(client.AccessToken); //litContactString.Text = contactGroup.ToJsonString(); }