Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // I use this snippet on a Windows server with LINQPad to
- // fetch-and-forward e-mails from my IMAP account to Gmail.
- // Add reference to: MailKit (using NuGet)
- var imapHost = "my.imap.host";
- var smtpHost = "my.smtp.host";
- var mappings = new[] {
- new { Login = "user1", Destination = "anything@invalid" },
- new { Login = "user2", Destination = "anything@invalid" },
- };
- var tasks = mappings.Select(mapping => Task.Factory.StartNew(() =>
- {
- while (true)
- {
- int retries = 0;
- using (var imapClient = new ImapClient())
- {
- imapClient.Connect(imapHost, 993, useSsl: true);
- string.Format("[{0}] Connected.", mapping.Login).Dump();
- // Remove the XOAUTH2 authentication mechanism since we don't have an OAuth2 token.
- imapClient.AuthenticationMechanisms.Remove("XOAUTH2");
- imapClient.Authenticate(mapping.Login, Util.GetPassword(mapping.Login));
- imapClient.Inbox.Open(FolderAccess.ReadWrite);
- CancellationTokenSource done = null;
- imapClient.Inbox.MessagesArrived += (sender, e) => { if (done != null) done.Cancel(); };
- while (imapClient.IsConnected)
- {
- using (var smtpClient = new SmtpClient())
- {
- smtpClient.Connect(smtpHost, 465, useSsl: true);
- foreach (var msg in imapClient.Inbox.Fetch(0, -1, MessageSummaryItems.UniqueId).ToArray())
- {
- var message = imapClient.Inbox.GetMessage(msg.UniqueId);
- var sender = message.Sender ?? message.From.OfType<MailboxAddress>().First();
- var recipient = new MailboxAddress(mapping.Destination, mapping.Destination);
- string.Format("[{0}] Forwarded: {1}", mapping.Login, message.Subject).Dump();
- smtpClient.Send(message, sender, new[] { recipient });
- imapClient.Inbox.AddFlags(msg.UniqueId, MessageFlags.Deleted, true);
- }
- imapClient.Inbox.Expunge();
- smtpClient.Disconnect(true);
- }
- done = new CancellationTokenSource();
- imapClient.Idle(done.Token);
- Thread.Sleep(500);
- }
- }
- string.Format("[{0}] Disconnected.", mapping.Login).Dump();
- Thread.Sleep(1000 * (int)Math.Pow(2, retries));
- if (retries <= 5) retries++;
- }
- }));
- Task.WaitAll(tasks.ToArray());
Advertisement
Add Comment
Please, Sign In to add comment