Trabalhando com Mensagens do Servidor IMAP
Obtendo as informações de identificação para mensagens recebidas de uma caixa de correio
Ao recuperar e processar mensagens de e-mail, você pode buscar os detalhes dessas mensagens usando seus números de sequência. Os seguintes recursos são utilizados para interagir com uma caixa de correio IMAP:
-
Aspose.Email.MailboxInfo
class - Representa informações de identificação sobre a mensagem em uma caixa de correio.-
Aspose.Email.MailboxInfo.SequenceNumber
property - O número de sequência de uma mensagem. -
Aspose.Email.MailboxInfo.UniqueId
property - O id único de uma mensagem.
-
-
Aspose.Email.MailMessage.ItemId
property - Representa informações de identificação sobre a mensagem em uma caixa de correio.
O exemplo de código abaixo mostra como obter informações de identificação sobre mensagens:
using (var client = new ImapClient(imapHost, port, emailAddress, password, securityOption))
{
var msgs = client.ListMessages("INBOX").Take(5);
var seqIds = msgs.Select(t => t.SequenceNumber);
var msgsViaFetch = client.FetchMessages(seqIds);
for (var i = 0; i < 5; i++)
{
var thisMsg = msgsViaFetch[i];
Console.WriteLine($"Message ID:{seqIds.ElementAt(i)} SequenceNumber: {thisMsg.ItemId.SequenceNumber} Subject:{thisMsg.Subject}");
}
}
Listando IDs de Mensagens MIME do Servidor
ImapMessageInfo fornece o MIME MessageId para identificação de mensagens sem extrair a mensagem completa. O seguinte exemplo de código mostra como listar o messageId MIME.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
ImapClient client = new ImapClient(); | |
client.Host = "domain.com"; | |
client.Username = "username"; | |
client.Password = "password"; | |
try | |
{ | |
ImapMessageInfoCollection messageInfoCol = client.ListMessages("Inbox"); | |
foreach (ImapMessageInfo info in messageInfoCol) | |
{ | |
// Display MIME Message ID | |
Console.WriteLine("Message Id = " + info.MessageId); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} |
Listando Mensagens do Servidor
Aspose.Email fornece uma variante sobrecarregada de 2 membros do ListMessages() para recuperar um número específico de mensagens com base em uma consulta. O seguinte exemplo de código mostra como listar Mensagens.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
imapClient.SelectFolder("Inbox"); | |
ImapQueryBuilder builder = new ImapQueryBuilder(); | |
MailQuery query = | |
builder.Or( | |
builder.Or( | |
builder.Or( | |
builder.Or( | |
builder.Subject.Contains(" (1) "), | |
builder.Subject.Contains(" (2) ")), | |
builder.Subject.Contains(" (3) ")), | |
builder.Subject.Contains(" (4) ")), | |
builder.Subject.Contains(" (5) ")); | |
ImapMessageInfoCollection messageInfoCol4 = imapClient.ListMessages(query, 4); | |
Console.WriteLine((messageInfoCol4.Count == 4) ? "Success" : "Failure"); |
Listando Mensagens do Servidor Recursivamente
O protocolo IMAP suporta listar mensagens recursivamente de uma pasta de caixa de correio. Isso ajuda a listar mensagens de subpastas de uma pasta também. O seguinte exemplo de código mostra como listar mensagens recursivamente.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Create an imapclient with host, user and password | |
ImapClient client = new ImapClient(); | |
client.Host = "domain.com"; | |
client.Username = "username"; | |
client.Password = "password"; | |
client.SelectFolder("InBox"); | |
ImapMessageInfoCollection msgsColl = client.ListMessages(true); | |
Console.WriteLine("Total Messages: " + msgsColl.Count); |
Listando Mensagens com MultiConnection
ImapClient fornece uma propriedade UseMultiConnection que pode ser usada para criar várias conexões para operações pesadas. Você também pode definir o número de conexões a serem usadas durante o modo de multi-conexão usando ImapClient.ConnectionsQuantity. O seguinte exemplo de código demonstra o uso do modo multi-conexão para listar mensagens e compara seu desempenho com o modo de conexão única.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
ImapClient imapClient = new ImapClient(); | |
imapClient.Host = "<HOST>"; | |
imapClient.Port = 993; | |
imapClient.Username = "<USERNAME>"; | |
imapClient.Password = "<PASSWORD>"; | |
imapClient.SupportedEncryption = EncryptionProtocols.Tls; | |
imapClient.SecurityOptions = SecurityOptions.SSLImplicit; | |
imapClient.SelectFolder("Inbox"); | |
imapClient.ConnectionsQuantity = 5; | |
imapClient.UseMultiConnection = MultiConnectionMode.Enable; | |
DateTime multiConnectionModeStartTime = DateTime.Now; | |
ImapMessageInfoCollection messageInfoCol1 = imapClient.ListMessages(true); | |
TimeSpan multiConnectionModeTimeSpan = DateTime.Now - multiConnectionModeStartTime; | |
imapClient.UseMultiConnection = MultiConnectionMode.Disable; | |
DateTime singleConnectionModeStartTime = DateTime.Now; | |
ImapMessageInfoCollection messageInfoCol2 = imapClient.ListMessages(true); | |
TimeSpan singleConnectionModeTimeSpan = DateTime.Now - singleConnectionModeStartTime; | |
double performanceRelation = singleConnectionModeTimeSpan.TotalMilliseconds / multiConnectionModeTimeSpan.TotalMilliseconds; | |
Console.WriteLine("Performance Relation: " + performanceRelation); |
Obter Mensagens em ordem decrescente
Aspose.Email fornece o método ImapClient.ListMessagesByPage
que lista mensagens com suporte para paginação. Algumas sobrecargas de ImapClient.ListMessagesByPage
aceitam PageSettings
como parâmetro. PageSettings
fornece uma propriedade AscendingSorting
que, quando definida como false, retorna e-mails em ordem decrescente.
O seguinte código de exemplo demonstra o uso da propriedade AscendingSorting da classe PageSettings para alterar a ordem dos e-mails.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
ImapClient imapClient = new ImapClient(); | |
imapClient.Host = "<HOST>"; | |
imapClient.Port = 993; | |
imapClient.Username = "<USERNAME>"; | |
imapClient.Password = "<PASSWORD>"; | |
imapClient.SupportedEncryption = EncryptionProtocols.Tls; | |
imapClient.SecurityOptions = SecurityOptions.SSLImplicit; | |
PageSettings pageSettings = new PageSettings { AscendingSorting = false }; | |
ImapPageInfo pageInfo = imapClient.ListMessagesByPage(5, pageSettings); | |
ImapMessageInfoCollection messages = pageInfo.Items; | |
foreach (ImapMessageInfo message in messages) | |
{ | |
Console.WriteLine(message.Subject + " -> " + message.Date.ToString()); | |
} |
Buscar Mensagens do Servidor e Salvar no disco
A classe ImapClient pode buscar mensagens de um servidor IMAP e salvar as mensagens no formato EML em um disco local. Os seguintes passos são necessários para salvar as mensagens no disco:
- Crie uma instância da classe ImapClient.
- Especifique um hostname, porta, nome de usuário e senha no construtor do ImapClient constructor.
- Selecione a pasta usando o método SelectFolder().
- Chame o método ListMessages para obter o objeto ImapMessageInfoCollection.
- Itere pela coleção ImapMessageInfoCollection, chame o método SaveMessage() e forneça o caminho de saída e o nome do arquivo.
O seguinte exemplo de código mostra como buscar mensagens de e-mail de um servidor e salvá-las.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Select the inbox folder and Get the message info collection | |
client.SelectFolder(ImapFolderInfo.InBox); | |
ImapMessageInfoCollection list = client.ListMessages(); | |
// Download each message | |
for (int i = 0; i < list.Count; i++) | |
{ | |
// Save the EML file locally | |
client.SaveMessage(list[i].UniqueId, dataDir + list[i].UniqueId + ".eml"); | |
} |
Salvando Mensagens no Formato MSG
No exemplo acima, os e-mails são salvos no formato EML. Para salvar e-mails no formato MSG, o método ImapClient.FetchMessage() precisa ser chamado. Ele retorna a mensagem em uma instância da classe MailMessage. O método MailMessage.Save() pode então ser chamado para salvar a mensagem em MSG. O seguinte exemplo de código mostra como salvar mensagens no formato MSG.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// The path to the file directory. | |
string dataDir = RunExamples.GetDataDir_IMAP(); | |
// Create an imapclient with host, user and password | |
ImapClient client = new ImapClient("localhost", "user", "password"); | |
// Select the inbox folder and Get the message info collection | |
client.SelectFolder(ImapFolderInfo.InBox); | |
ImapMessageInfoCollection list = client.ListMessages(); | |
// Download each message | |
for (int i = 0; i < list.Count; i++) | |
{ | |
// Save the message in MSG format | |
MailMessage message = client.FetchMessage(list[i].UniqueId); | |
message.Save(dataDir + list[i].UniqueId + "_out.msg", SaveOptions.DefaultMsgUnicode); | |
} |
Busca em Grupo de Mensagens
ImapClient fornece um método FetchMessages que aceita um iterável de Números de Sequência ou ID Único e retorna uma lista de MailMessage. O seguinte exemplo de código demonstra o uso do método FetchMessages para buscar mensagens por Números de Sequência e ID Único.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
ImapClient imapClient = new ImapClient(); | |
imapClient.Host = "<HOST>"; | |
imapClient.Port = 993; | |
imapClient.Username = "<USERNAME>"; | |
imapClient.Password = "<PASSWORD>"; | |
imapClient.SupportedEncryption = EncryptionProtocols.Tls; | |
imapClient.SecurityOptions = SecurityOptions.SSLImplicit; | |
ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages(); | |
Console.WriteLine("ListMessages Count: " + messageInfoCol.Count); | |
int[] sequenceNumberAr = messageInfoCol.Select((ImapMessageInfo mi) => mi.SequenceNumber).ToArray(); | |
string[] uniqueIdAr = messageInfoCol.Select((ImapMessageInfo mi) => mi.UniqueId).ToArray(); | |
IList<MailMessage> fetchedMessagesBySNumMC = imapClient.FetchMessages(sequenceNumberAr); | |
Console.WriteLine("FetchMessages-sequenceNumberAr Count: " + fetchedMessagesBySNumMC.Count); | |
IList<MailMessage> fetchedMessagesByUidMC = imapClient.FetchMessages(uniqueIdAr); | |
Console.WriteLine("FetchMessages-uniqueIdAr Count: " + fetchedMessagesByUidMC.Count); |
Listando Mensagens com Suporte a Paginação
Em cenários onde o servidor de e-mail contém um grande número de mensagens na caixa de correio, muitas vezes é desejado listar ou recuperar as mensagens com suporte a paginação. A API Aspose.Email ImapClient permite recuperar as mensagens do servidor com suporte a paginação.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
///<summary> | |
/// This example shows the paging support of ImapClient for listing messages from the server | |
/// Available in Aspose.Email for .NET 6.4.0 and onwards | |
///</summary> | |
using (ImapClient client = new ImapClient("host.domain.com", 993, "username", "password")) | |
{ | |
try | |
{ | |
int messagesNum = 12; | |
int itemsPerPage = 5; | |
MailMessage message = null; | |
// Create some test messages and append these to server's inbox | |
for (int i = 0; i < messagesNum; i++) | |
{ | |
message = new MailMessage( | |
"from@domain.com", | |
"to@domain.com", | |
"EMAILNET-35157 - " + Guid.NewGuid(), | |
"EMAILNET-35157 Move paging parameters to separate class"); | |
client.AppendMessage(ImapFolderInfo.InBox, message); | |
} | |
// List messages from inbox | |
client.SelectFolder(ImapFolderInfo.InBox); | |
ImapMessageInfoCollection totalMessageInfoCol = client.ListMessages(); | |
// Verify the number of messages added | |
Console.WriteLine(totalMessageInfoCol.Count); | |
////////////////// RETREIVE THE MESSAGES USING PAGING SUPPORT//////////////////////////////////// | |
List<ImapPageInfo> pages = new List<ImapPageInfo>(); | |
PageSettings pageSettings = new PageSettings(); | |
ImapPageInfo pageInfo = client.ListMessagesByPage(itemsPerPage, 0, pageSettings); | |
Console.WriteLine(pageInfo.TotalCount); | |
pages.Add(pageInfo); | |
while (!pageInfo.LastPage) | |
{ | |
pageInfo = client.ListMessagesByPage(itemsPerPage, pageInfo.NextPage.PageOffset, pageSettings); | |
pages.Add(pageInfo); | |
} | |
int retrievedItems = 0; | |
foreach (ImapPageInfo folderCol in pages) | |
retrievedItems += folderCol.Items.Count; | |
Console.WriteLine(retrievedItems); | |
} | |
finally | |
{ | |
} | |
} |
Listando os Anexos da Mensagem
Para obter informações sobre anexos, como nome e tamanho, sem buscar os dados do anexo, tente as seguintes APIs:
- Aspose.Email.Clients.Imap.ImapAttachmentInfo - Representa informações de um anexo.
- Aspose.Email.Clients.Imap.ImapAttachmentInfoCollection - Representa uma coleção da classe ImapAttachmentInfo.
- Aspose.Email.Clients.Imap.ListAttachments(int sequenceNumber) - Obtém informações para cada anexo em uma mensagem.
O exemplo de código com os passos abaixo mostrará como usar as APIs:
-
Chame o método ListMessages() no objeto imapClient. Este método retornará um ImapMessageInfoCollection contendo informações sobre as mensagens na caixa de correio.
-
Itere através de cada mensagem na messageInfoCollection usando um loop foreach.
-
Chame o método ListAttachments() no objeto imapClient, passando a propriedade SequenceNumber do objeto de mensagem como parâmetro. Este método retornará uma ImapAttachmentInfoCollection contendo informações sobre os anexos na mensagem.
-
Itere através de cada anexo na attachmentInfoCollection usando um loop foreach.
-
Dentro do loop interno, você pode acessar as informações sobre cada anexo usando as propriedades do objeto attachmentInfo. Neste exemplo, o nome e o tamanho de cada anexo são registrados no console usando
Console.WriteLine()
.Console.WriteLine("Attachment: {0} (size: {1})", attachmentInfo.Name, attachmentInfo.Size);
var messageInfoCollection = imapClient.ListMessages();
foreach (var message in messageInfoCollection)
{
var attachmentInfoCollection = imapClient.ListAttachments(message.SequenceNumber);
foreach (var attachmentInfo in attachmentInfoCollection)
{
Console.WriteLine("Attachment: {0} (size: {1})", attachmentInfo.Name, attachmentInfo.Size);
}
}
Obtendo Pastas e Lendo Mensagens Recursivamente
Neste artigo, a maioria dos recursos do ImapClient são usados para criar um aplicativo que lista todas as pastas e subpastas recursivamente de um servidor IMAP. Ele também salva as mensagens em cada pasta e subpasta em formato MSG em um disco local. No disco, pastas e mensagens são criadas e salvas na mesma estrutura hierárquica que no servidor IMAP. O seguinte exemplo de código mostra como obter as mensagens e as informações das subpastas recursivamente.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
public static void Run() | |
{ | |
// Create an instance of the ImapClient class | |
ImapClient client = new ImapClient(); | |
// Specify host, username, password, Port and SecurityOptions for your client | |
client.Host = "imap.gmail.com"; | |
client.Username = "your.username@gmail.com"; | |
client.Password = "your.password"; | |
client.Port = 993; | |
client.SecurityOptions = SecurityOptions.Auto; | |
try | |
{ | |
// The root folder (which will be created on disk) consists of host and username | |
string rootFolder = client.Host + "-" + client.Username; | |
// Create the root folder and List all the folders from IMAP server | |
Directory.CreateDirectory(rootFolder); | |
ImapFolderInfoCollection folderInfoCollection = client.ListFolders(); | |
foreach (ImapFolderInfo folderInfo in folderInfoCollection) | |
{ | |
// Call the recursive method to read messages and get sub-folders | |
ListMessagesInFolder(folderInfo, rootFolder, client); | |
} | |
// Disconnect to the remote IMAP server | |
client.Dispose(); | |
} | |
catch (Exception ex) | |
{ | |
Console.Write(Environment.NewLine + ex); | |
} | |
Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server."); | |
} | |
/// Recursive method to get messages from folders and sub-folders | |
private static void ListMessagesInFolder(ImapFolderInfo folderInfo, string rootFolder, ImapClient client) | |
{ | |
// Create the folder in disk (same name as on IMAP server) | |
string currentFolder = RunExamples.GetDataDir_IMAP(); | |
Directory.CreateDirectory(currentFolder); | |
// Read the messages from the current folder, if it is selectable | |
if (folderInfo.Selectable) | |
{ | |
// Send status command to get folder info | |
ImapFolderInfo folderInfoStatus = client.GetFolderInfo(folderInfo.Name); | |
Console.WriteLine(folderInfoStatus.Name + " folder selected. New messages: " + folderInfoStatus.NewMessageCount + ", Total messages: " + folderInfoStatus.TotalMessageCount); | |
// Select the current folder and List messages | |
client.SelectFolder(folderInfo.Name); | |
ImapMessageInfoCollection msgInfoColl = client.ListMessages(); | |
Console.WriteLine("Listing messages...."); | |
foreach (ImapMessageInfo msgInfo in msgInfoColl) | |
{ | |
// Get subject and other properties of the message | |
Console.WriteLine("Subject: " + msgInfo.Subject); | |
Console.WriteLine("Read: " + msgInfo.IsRead + ", Recent: " + msgInfo.Recent + ", Answered: " + msgInfo.Answered); | |
// Get rid of characters like ? and :, which should not be included in a file name and Save the message in MSG format | |
string fileName = msgInfo.Subject.Replace(":", " ").Replace("?", " "); | |
MailMessage msg = client.FetchMessage(msgInfo.SequenceNumber); | |
msg.Save(currentFolder + "\\" + fileName + "-" + msgInfo.SequenceNumber + ".msg", SaveOptions.DefaultMsgUnicode); | |
} | |
Console.WriteLine("============================\n"); | |
} | |
else | |
{ | |
Console.WriteLine(folderInfo.Name + " is not selectable."); | |
} | |
try | |
{ | |
// If this folder has sub-folders, call this method recursively to get messages | |
ImapFolderInfoCollection folderInfoCollection = client.ListFolders(folderInfo.Name); | |
foreach (ImapFolderInfo subfolderInfo in folderInfoCollection) | |
{ | |
ListMessagesInFolder(subfolderInfo, rootFolder, client); | |
} | |
} | |
catch (Exception) { } | |
} |
Recuperando Parâmetros Extras como Informações Resumidas
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
using (ImapClient client = new ImapClient("host.domain.com", "username", "password")) | |
{ | |
MailMessage message = new MailMessage("from@domain.com", "to@doman.com", "EMAILNET-38466 - " + Guid.NewGuid().ToString(), "EMAILNET-38466 Add extra parameters for UID FETCH command"); | |
// append the message to the server | |
string uid = client.AppendMessage(message); | |
// wait for the message to be appended | |
Thread.Sleep(5000); | |
// Define properties to be fetched from server along with the message | |
string[] messageExtraFields = new string[] { "X-GM-MSGID", "X-GM-THRID" }; | |
// retreive the message summary information using it's UID | |
ImapMessageInfo messageInfoUID = client.ListMessage(uid, messageExtraFields); | |
// retreive the message summary information using it's sequence number | |
ImapMessageInfo messageInfoSeqNum = client.ListMessage(1, messageExtraFields); | |
// List messages in general from the server based on the defined properties | |
ImapMessageInfoCollection messageInfoCol = client.ListMessages(messageExtraFields); | |
ImapMessageInfo messageInfoFromList = messageInfoCol[0]; | |
// verify that the parameters are fetched in the summary information | |
foreach (string paramName in messageExtraFields) | |
{ | |
Console.WriteLine(messageInfoFromList.ExtraParameters.ContainsKey(paramName)); | |
Console.WriteLine(messageInfoUID.ExtraParameters.ContainsKey(paramName)); | |
Console.WriteLine(messageInfoSeqNum.ExtraParameters.ContainsKey(paramName)); | |
} | |
} |
Obtendo Informações do Cabeçalho List-Unsubscribe
O cabeçalho List-Unsubscribe contém a URL para se descadastrar de listas de e-mail, como anúncios, boletins informativos, etc. Para obter o cabeçalho List-Unsubscribe, use a propriedade ListUnsubscribe da classe ImapMessageInfo. O seguinte exemplo mostra o uso da propriedade ListUnsubscribe para obter o cabeçalho List-Unsubscribe.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
ImapClient imapClient = new ImapClient(); | |
imapClient.Host = "<HOST>"; | |
imapClient.Port = 993; | |
imapClient.Username = "<USERNAME>"; | |
imapClient.Password = "<PASSWORD>"; | |
imapClient.SupportedEncryption = EncryptionProtocols.Tls; | |
imapClient.SecurityOptions = SecurityOptions.SSLImplicit; | |
ImapMessageInfoCollection messageInfoCol = imapClient.ListMessages(); | |
foreach (ImapMessageInfo imapMessageInfo in messageInfoCol) | |
{ | |
Console.WriteLine("ListUnsubscribe Header: " + imapMessageInfo.ListUnsubscribe); | |
} |