nescafe2002

[LINQPad] Auto forward from IMAP to SMTP using MailKit

Dec 9th, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.34 KB | None | 0 0
  1. // I use this snippet on a Windows server with LINQPad to
  2. // fetch-and-forward e-mails from my IMAP account to Gmail.
  3.  
  4. // Add reference to: MailKit (using NuGet)
  5.  
  6. var imapHost = "my.imap.host";
  7. var smtpHost = "my.smtp.host";
  8.  
  9. var mappings = new[] {
  10.   new { Login = "user1", Destination = "anything@invalid" },
  11.   new { Login = "user2", Destination = "anything@invalid" },
  12. };
  13.  
  14. var tasks = mappings.Select(mapping => Task.Factory.StartNew(() =>
  15.   {
  16.     while (true)
  17.     {
  18.       int retries = 0;
  19.       using (var imapClient = new ImapClient())
  20.       {
  21.         imapClient.Connect(imapHost, 993, useSsl: true);
  22.         string.Format("[{0}] Connected.", mapping.Login).Dump();
  23.  
  24.         // Remove the XOAUTH2 authentication mechanism since we don't have an OAuth2 token.
  25.         imapClient.AuthenticationMechanisms.Remove("XOAUTH2");
  26.         imapClient.Authenticate(mapping.Login, Util.GetPassword(mapping.Login));
  27.         imapClient.Inbox.Open(FolderAccess.ReadWrite);
  28.  
  29.         CancellationTokenSource done = null;
  30.         imapClient.Inbox.MessagesArrived += (sender, e) => { if (done != null) done.Cancel(); };
  31.  
  32.         while (imapClient.IsConnected)
  33.         {
  34.           using (var smtpClient = new SmtpClient())
  35.           {
  36.             smtpClient.Connect(smtpHost, 465, useSsl: true);
  37.             foreach (var msg in imapClient.Inbox.Fetch(0, -1, MessageSummaryItems.UniqueId).ToArray())
  38.             {
  39.               var message = imapClient.Inbox.GetMessage(msg.UniqueId);
  40.               var sender = message.Sender ?? message.From.OfType<MailboxAddress>().First();
  41.               var recipient = new MailboxAddress(mapping.Destination, mapping.Destination);
  42.               string.Format("[{0}] Forwarded: {1}", mapping.Login, message.Subject).Dump();
  43.               smtpClient.Send(message, sender, new[] { recipient });
  44.               imapClient.Inbox.AddFlags(msg.UniqueId, MessageFlags.Deleted, true);
  45.             }
  46.             imapClient.Inbox.Expunge();
  47.             smtpClient.Disconnect(true);
  48.           }
  49.           done = new CancellationTokenSource();
  50.           imapClient.Idle(done.Token);
  51.           Thread.Sleep(500);
  52.         }
  53.       }
  54.       string.Format("[{0}] Disconnected.", mapping.Login).Dump();
  55.       Thread.Sleep(1000 * (int)Math.Pow(2, retries));
  56.       if (retries <= 5) retries++;
  57.     }
  58.   }));
  59.  
  60. Task.WaitAll(tasks.ToArray());
Advertisement
Add Comment
Please, Sign In to add comment