如何用C#或Python发送所有Gmail草稿
我一直用 Gmail 来保存网页剪辑或笔记。我只需创建一封新邮件,编辑内容,然后保存为草稿。在过去的两年里,我在 Gmail 的草稿文件夹里存了超过 1000 条信息。我想通过编程的方式把这些草稿全部发给自己。我做了一些研究,现在我能用 Python 或 C# 通过 IMAP 加载我的 Gmail 收件箱里的邮件,或者通过 SMTP 创建邮件并发送出去。不过,我还是无法读取草稿邮件并把它们发给自己。
(我为什么选择用 Gmail 来存笔记,而不是使用像 Evernote、微软的 OneNote 或苹果的备忘录这样的笔记应用呢?因为电子邮件在各种平台和设备上支持得更好。通常会预装邮件客户端,而且找到或定义一个“创建新邮件”的快捷键比“导出到 Evernote”的快捷键要简单得多。)
1 个回答
2
如果你使用的是 MailKit 这个库,下面是你可以这样做的方法:
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);
}
}
}
}