我在线上看过其他示例,但无法弄清楚如何从MimeMessage对象下载和存储所有附件。我确实调查了WriteTo(),但无法正常工作。还想知道是否会根据原始文件名保存附件,然后在电子邮件中键入内容。这是我到目前为止的内容:
using (var client = new ImapClient())
{
client.Connect(Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
client.AuthenticationMechanisms.Remove(Constant.GoogleOAuth);
client.Authenticate(Constant.GoogleUserName, Constant.GenericPassword);
if (client.IsConnected == true)
{
FolderAccess inboxAccess = client.Inbox.Open(FolderAccess.ReadWrite);
IMailFolder inboxFolder = client.GetFolder(Constant.InboxFolder);
IList<UniqueId> uids = client.Inbox.Search(SearchQuery.All);
if (inboxFolder != null & inboxFolder.Unread > 0)
{
foreach (UniqueId msgId in uids)
{
MimeMessage message = inboxFolder.GetMessage(msgId);
foreach (MimeEntity attachment in message.Attachments)
{
//need to save all the attachments locally
}
}
}
}
}
“常见问题”中的“如何保存附件?”对此进行了全部解释。部分。
这是您在问题中发布的代码的固定版本:
using (var client = new ImapClient ()) {
client.Connect (Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
client.AuthenticationMechanisms.Remove (Constant.GoogleOAuth);
client.Authenticate (Constant.GoogleUserName, Constant.GenericPassword);
client.Inbox.Open (FolderAccess.ReadWrite);
IList<UniqueId> uids = client.Inbox.Search (SearchQuery.All);
foreach (UniqueId uid in uids) {
MimeMessage message = client.Inbox.GetMessage (uid);
foreach (MimeEntity attachment in message.Attachments) {
var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
using (var stream = File.Create (fileName)) {
if (attachment is MessagePart) {
var rfc822 = (MessagePart) attachment;
rfc822.Message.WriteTo (stream);
} else {
var part = (MimePart) attachment;
part.Content.DecodeTo (stream);
}
}
}
}
}
一些注意事项:
client.IsConnected
验证后无需检查。如果未连接,它将在Authenticate()
方法中引发异常。Connect()
如果不成功,它也会在方法中引发异常。IsConnected
如果您真的只是调用了Connect()
2行,则无需检查状态。inboxFolder.Unread
是否甚至不在任何地方使用它?如果您只想下载未读的邮件,请将搜索更改为SearchQuery.NotSeen
,以便只给您提供未读的邮件UID。IMailFolder inboxFolder = client.GetFolder(Constant.InboxFolder);
逻辑,因为您不需要它。如果要使用进行搜索client.Inbox
,则不要使用其他文件夹对象遍历结果。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句