Question

I always use gmail to save web clips or notes. I simply create a new mail, edit it and save as draft. Over 2 years I've dumped 1000+ messages in my Gmail draft folder. I want to programmatically send all of them to myself. I did some research, and now I'm able to use python or c# to load my gmail inbox messages via IMAP, or create a mail and send it via SMTP. However I'm still not able to read draft messages and send them to myself.

(Why am I using GMail as note storage instead of note apps such as evernote, MS onenote, or Apple notes? Because email is better supported across any platforms or devices. There are usually pre-installed email clients, and it's easier to find or define a "create new mail" keyboard shortcut than an "export to evernote" keyboard shortcut.)

Was it helpful?

Solution

If you use MailKit, here's how you would do it:

using System;
using System.Net;
using System.Threading;

using MailKit.Net.Imap;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            using (var client = new ImapClient ()) {
                var credentials = new NetworkCredential ("jimbo", "password");

                client.Connect (new Uri ("imaps://imap.gmail.com"), CancellationToken.None);
                client.Authenticate (credentials, CancellationToken.None);

                var folder = client.GetFolder (SpecialFolder.Drafts);
                folder.Open (FolderAccess.ReadWrite, CancellationToken.None);

                using (var smtp = new SmtpClient ()) {
                    smtp.Connect (new Uri ("smtps://smtp.gmail.com"), CancellationToken.None);
                    smtp.Authenticate (credentials, CancellationToken.None);

                    var indexes = new int[folder.Count];
                    for (int i = 0; i < folder.Count; i++) {
                        var message = folder.GetMessage (i, CancellationToken.None);

                        // if you haven't already specified a recipient, do it now:
                        message.To.Add (new MailboxAddress ("Jimbo", "jimbo@gmail.com"));

                        smtp.Send (message, CancellationToken.None);
                        indexes[i] = i;
                    }

                    // if you also want to delete the messages on the IMAP server:
                    folder.AddFlags (indexes, MessageFlags.Deleted, true, CancellationToken.None);
                    folder.Close (true, CancellationToken.None);

                    smtp.Disconnect (true, cancellationToken.None);
                }

                client.Disconnect (true, cancellationToken.None);
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top