Mostrar mensagens com a etiqueta Exchange Web Services. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta Exchange Web Services. Mostrar todas as mensagens

15 de setembro de 2011

Enviar uma mensagem com TO, CC, BCC e Anexos (Exchange On-Line)

Para utilizar este método necessita saber como fazer o BINDING

 

/// <summary>
/// Envia Mensagem.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="mailTo">The mail to.</param>
/// <param name="mailCc"></param>
/// <param name="mailBcc"></param>
/// <param name="attachments"></param>
public static bool SendNewMessage(ExchangeService service,
string subject, string body,
List<string> mailTo,
List<string> mailCc,
List<string> mailBcc,
List<string> attachments)
{
// Create an e-mail message and identify the Exchange service.
EmailMessage message = new EmailMessage(service)
{
/* Subject*/
Subject = subject, /* Body*/
Body = new MessageBody(body)
};

// Recipients
foreach (string recipientes in mailTo)
{
message.ToRecipients.Add(recipientes);
}

// Recipients
foreach (string recipientes in mailCc)
{
message.CcRecipients.Add(recipientes);
}

// Recipients
foreach (string recipientes in mailBcc)
{
message.BccRecipients.Add(recipientes);
}

// Recipients
foreach (string att in attachments)
{
message.Attachments.AddFileAttachment(att);
}
// Send the mail. This makes a trip to the EWS server.
message.SendAndSaveCopy();
return true;
}



Obter uma mensagem renderizada com imagens do Exchange On-Line

Para utilizar este método necessita saber como fazer o BINDING e terá de ter disponível o ID da sua mensagem

 

using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;
using BodyType = Microsoft.Exchange.WebServices.Data.BodyType;
/// <summary>
/// Les the menssagem por id.
/// </summary>
/// <param name="messId">The mess id.</param>
/// <returns></returns>
public static string LeMenssagemPorId(string messId)
{
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties)
{
RequestedBodyType = BodyType.HTML
};
Item mess = Item.Bind(GetBinding(), messId, psPropSet);
mess.Body.BodyType = BodyType.HTML;

string sHTMLCOntent = mess.Body.Text;

FileAttachment[] attachments = null;

if (mess.Attachments.Count != 0)
{
attachments = new FileAttachment[mess.Attachments.Count];
for (int i = 0; i < mess.Attachments.Count; i++)
{
try
{
if (mess.Attachments[i].IsInline)
{
string sType = mess.Attachments[i].ContentType.ToLower();
if (sType.Contains("image"))
{
attachments[i] = (FileAttachment)mess.Attachments[i];
attachments[i].Load();
string sId = attachments[i].ContentId;
sType = sType.Replace("image/", "");
string oldString = "cid:" + sId;
string imagem =
Convert.ToBase64String(attachments[i].Content);
sHTMLCOntent = sHTMLCOntent.Replace(oldString,
"data:image/" + sType + ";base64," + imagem);
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Erro: " + ex.Message);
}
}
}



Criar o BINDING Para um serviço Exchange On-line

Visto que estou a usar o Exchange Web Services Managed abordagem API, você terá de fazer download da mesma aqui e adicionar o "Microsoft.Exchange.WebServices.dll" ao seu projeto. Se você tem o seu domínio hospedado na sua empresa ou em outro lugar provavelmente você vai precisar de um CNAME no seu servidor, a fim de resolver o AutoDiscovery para o Exchange On-Line para que você possa usar Binding. Este CNAME irá criar uma ponte entre o seu servidor para o Exchange On-Line, algo como isto:

Tipo: MX Host: yourhost.com MX Server: 99999999.mail.outlook.com TTL: 3.600 ou 1 hora Prioridade: 0

Outro método é impedir que o AutoDiscovery vá à Active Directory:

 

// Previne o AutodiscoverService de
// olhando para o local do Active Directory
// Para a Web do Exchange Serviços SCP.
ads.EnableScpLookup = false;

 


Se você estiver em uma rede com um proxy, como ISA, você poderá ter que passar por um Proxy WebRequest caso contrário você terá o erro abaixo:

407 Autenticação de proxy necessária (Forefront TMG requer autorização para atender a solicitação. O acesso ao
filtro de proxy da Web é negado.)

Adicione o seguinte código para passar um Proxy Request


// Configurar o proxy
webproxy de proxy = new webproxy ("proxy-valido", "porta-valida");
proxy.Credentials = new
NetworkCredential ("utilizador-valido", "senha-valida", "dominio_valido");
service.webproxy = proxy;

 


Autodiscover Response (POX)

CRIAR O BINDING PARA EXCHANGE ONLINE SERVICES – OFFICE 365, LIVE@EDU


using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;

public static ExchangeService GetBinding()
{
try
{
//Create Service
ExchangeService service = new
ExchangeService(ExchangeVersion.Exchange2010_SP1);
//Assign Credentials
service.Credentials = new
WebCredentials("admin@contoso.com", "password");
// Create an instance of the AutodiscoverService.
AutodiscoverService ads = new
Autodiscover.AutodiscoverService();
// Enable tracing.
ads.TraceEnabled = true;
// Set the credentials.
ads.Credentials = service.Credentials;
// Prevent the AutodiscoverService from
//looking in the local Active Directory
// for the Exchange Web Services Services SCP.
ads.EnableScpLookup = false;
// Specify a redirection URL validation
//callback that returns true for valid URLs.
ads.RedirectionUrlValidationCallback =
RedirectionUrlValidationCallback;
// Get the Exchange Web Services URL for the user's mailbox.
GetUserSettingsResponse response =
ads.GetUserSettings("admin@contoso.com",
UserSettingName.ExternalEwsUrl);
// Extract the Exchange Web Services URL from the response.
var externalEwsUrl = new
Uri(response.Settings[UserSettingName.ExternalEwsUrl].ToString());
// Set the URL of the ExchangeService object.
service.Url = externalEwsUrl;
return service;
}
catch (AutodiscoverRemoteException ex)
{
Console.WriteLine("Exception thrown: " + ex.Error.Message);
return null;
}
}

static bool RedirectionUrlValidationCallback(String redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;

Uri redirectionUri = new Uri(redirectionUrl);

// Validate the contents of the redirection URL.
//In this simple validation
// callback, the redirection URL is considered
//valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}


 

Se você estiver a utilizar este método no SharePoint 2010, talvez você necessite de executar o método acima numa console application para obter URL EndPoint e usar assim:

 


/// <summary>
/// Gets the binding.
/// </summary>
/// <returns></returns>
public static ExchangeService GetBinding()
{
try
{
//Create Service
ExchangeService service = new
ExchangeService(ExchangeVersion.Exchange2010_SP1);
//Assign Credentials
service.Credentials = new
WebCredentials("admin@contoso.com", "password");
ServicePointManager.ServerCertificateValidationCallback +=
RemoteCertificateValidationHandler;
//Change this line by your EndPoint Url
service.Url = new Uri("https://amsprdXXXX.outlook.com/EWS/Exchange.asmx");
return service;
}
catch (AutodiscoverRemoteException ex)
{
Console.WriteLine("Exception thrown: " + ex.Error.Message);
return null;
}
}

private static bool RemoteCertificateValidationHandler
(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true; //ignore the checks and go ahead
}

11 de abril de 2011

Arquitetura do Exchange Web Services

(1) Quando uma aplicativo cliente solicita informações de armazenamento do Exchange, uma mensagem de solicitação XML compatível com o SOAP padrão é criada e enviada para o servidor Exchange. Quando o Microsoft Exchange server recebe a solicitação, ele verifica as credenciais que são fornecidas pelo cliente e analisa automaticamente o XML para os dados solicitados. O servidor cria uma resposta SOAP que contém dados XML que representa os objetos encriptados e solicita as suas propriedades. Os dados XML são enviados para o aplicativo do cliente em uma resposta HTTP. O aplicativo cliente, em seguida, desserializa o XML e usa os dados para reformar os objetos com rigidez de tipos.

 

A figura a seguir mostra como um aplicativo cliente interage com o servidor de acesso para cliente para aceder às informações de armazenamento do Exchange do servidor de caixa de correio.

 

Web Service Messaging Data Flow Architecture

(1) Fonte

.

9 de abril de 2011

Usar o Autodiscover com o Microsoft Exchange Online

Resumo:

Este artigo fornece informações sobre como usar descoberta automática com o Microsoft Exchange Online. Ele inclui um exemplo de código que mostra como usar o serviço Descoberta Automática.

 
Por Steve Petersen

 
Para usar o Exchange Web Services (EWS) para desenvolver para o Microsoft Exchange Online como parte do Microsoft Office 365, é necessário identificar os pontos de extremidade EWS que o aplicativo cliente deve usar para recuperar as configurações. O serviço Descoberta Automática permite-lhe descobrir esses pontos de extremidade. Neste artigo, descrevo como usar o serviço Descoberta Automática para solicitar informações sobre os pontos de extremidade EWS.

 

FONTE:

http://msdn.microsoft.com/en-us/library/gg591268(v=EXCHG.140).aspx#Y2741 

.

3 de abril de 2011

Onde posso encontrar o Live@Edu SDK em versão Avançada (Level 800)

SDK Avançado de Integração com o Live@Edu

.

Outra forma de inicializar o Exchange Web Service

Exemplo em ASPX no Page_Load()

As Flags de AppSettings são valores que vêm do web.config, podes passa-las directamente alterando os valores no código

 

/// <summary>
/// Page Load Event.
/// </summary>
/// <param name="sender">Control Invoking this event.</param>
/// <param name="e">Event Arguments.</param>
protected void Page_Load(object sender, EventArgs e)
{
//// Initialize EWS service.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials(ConfigurationManager.AppSettings["EmailAddress"],
ConfigurationManager.AppSettings["Password"]);
service.AutodiscoverUrl(ConfigurationManager.AppSettings["EmailAddress"], delegate(string url) { return true; });
}



30 de março de 2011

EWS – Como criar um compromisso simples

O Exchange Web Services é muito potente, neste post vou dar um exemplo de como criar um compromisso simples, útil, rápido e eficaz.

 

// Cria o compromisso.
Appointment appointment = new Appointment(service);

// Define as propriedades do compromisso.
appointment.Subject = "Dentist Appointment";
appointment.Body = "The appointment is with Dr. Smith.";
appointment.Start = new DateTime(2009, 3, 1, 9, 0, 0);
appointment.End = appointment.Start.AddHours(2);

// Guarda o compromisso.
appointment.Save(SendInvitationsMode.SendToNone);


EWS - Como podemos determinar o ID de uma mensagem enviada

Quando enviamos uma mensagem via EWS, é bom ficarmos com o ID da mesma para tratamento com outros métodos, podemos querer gravar no SQL Server por exemplo as propriedades das mensagem, fica aqui um código simples que permite retirar o UniqueID, bem como as outras propriedades da mensagem

 

// Criar a mensagem e define algumas propriedades básicas.
EmailMessage message = new EmailMessage(service);
message.Subject = "Message Subject";
message.Body = "This message was sent by using the EWS Managed API.";
message.ToRecipients.Add("User1@example.com");

// Cria uma propriedade personalizada estendida e adicioná-lo à mensagem
Guid myPropertySetId = new Guid("{20B5C09F-7CAD-44c6-BDBF-8FCBEEA08544}");
ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId,
"MyExtendedPropertyName", MapiPropertyType.String);
message.SetExtendedProperty(myExtendedPropertyDefinition, "MyExtendedPropertyValue");

// Envia a mensagem e salva uma cópia.
message.SendAndSaveCopy();

// Espera um segundo (enquanto o EWS envia e salva a mensagem).
System.Threading.Thread.Sleep(1000);

// Agora, encontra a cópia gravada da mensagem usando a propriedade
ItemView view = new ItemView(5);
SearchFilter searchFilter = new SearchFilter.IsEqualTo(myExtendedPropertyDefinition, "MyExtendedPropertyValue");
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, myExtendedPropertyDefinition);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.SentItems, searchFilter, view);

//Processa os resultados
foreach (Item myItem in findResults.Items)
{
if (myItem is EmailMessage)
{
EmailMessage em = myItem as EmailMessage;
Console.WriteLine(em.Subject);
Console.WriteLine(em.Id.UniqueId);
}
}


27 de março de 2011

EWS Obter as propriedades das mensagens na Caixa de Entrada

Importante, não te esqueças do PageSize por causa da performance, se for necessário vais buscar por exemplo 20 a 20

public static Void GetInboxReceivedMessages(int pageSize)
{
ItemView view = new ItemView(pageSize, 0);
SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
FindItemsResults<Item> findResults = GetService().FindItems(WellKnownFolderName.Inbox, sf, view);

foreach (Item item in findResults.Items)
{
Console.Writeline("Id" + item.Id)
Console.Writeline("Assunto" + item.Subject)
Console.Writeline("Data Recepção" + item.Subjectitem.DateTimeReceived.ToShortDateString())
}
}



EWS Contar mensagens através do WellKnownFolderName

O WellKnownFolderName é denominado como as pastas conhecidas e comuns do Exchange, como Inbox, Sent Items, etc.., é esse folder que queres que vais passar no método seguinte bem como o máximo número de mensagens, pois se tiveres 5000 pode-se tornar lento como é óbvio.

 

Se quiseres as mensagens não lidas passas o parâmetro IsRead para false

 

/// <summary>
/// Obters the mensages lidas pasta.
/// </summary>
/// <param name="folder">The folder.</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns></returns>
public static int ObterMensagesLidasPasta(WellKnownFolderName folder, int pageSize)
{
ItemView view = new ItemView(pageSize, 0);
SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);

FindItemsResults<Item> findResults = GetService().FindItems(folder, sf, view);
return findResults.Items.Count;
}


EWS Como criar um E-mail simples

Eis um método que podes utilizar para enviar um mail simples via Exchange Web Services

Tens de adicionar a referencia ao teu projecto: Microsoft.Exchange.WebServices

/// <summary>
/// Criars the email simples.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="mailTo">The mail to.</param>
public static void CriarEmailSimples(ExchangeService service, string subject,
string body, List<string> mailTo)
{
// Create an e-mail message and identify the Exchange service.
EmailMessage message = new EmailMessage(service)
{
/* Subject*/
Subject = subject, /* Body*/
Body = new MessageBody(body)
};

// Recipients
foreach (string recipientes in mailTo)
{
message.ToRecipients.Add(recipientes);
}

// Send the mail. This makes a trip to the EWS server.
message.SendAndSaveCopy();
}



Exchange Web Services (Instanciar o Serviço) passando o ISA

Em ambientes LIve@edu muitas vezes queremos “puxar” para a nossa aplicação a informação contida no Exchange On-line, para que tal aconteça li muito acerca de Autodiscovery para aqui e Autodiscovery para ali. O problema principal é que quando estamos na nossa Escola/Empresa, e visto os Domínios estarem repartidos na Cloud e na Empresa o mesmo não vai funcionar porque não resolve de dentro, ou seja não passa no ISA, mas para passar no ISA então há que esperar que tal aconteça, e tempo é dinheiro.

 

Tipicamente passa-se o seguinte:

 

This Error event indicates that the Microsoft® Exchange Autodiscover service could not discover the Exchange Availability service that is running in a remote Active Directory® directory service forest. The Exchange Autodiscover service that runs on a Front End server that is running Exchange Server 2007 (also known as Exchange Client Access server) is a Web service that locates a mailbox. The Exchange Availability service is also a Web service that retrieves the Schedule+ Free Busy and Out-of-Office (OOF) data for that specific mailbox. This event may occur when an Exchange 2007 Client Access server and user mailbox are in different Active Directory forests. Because the Exchange Autodiscover service cannot directly connect to a mailbox that resides in a remote Active Directory forest, it requests that the Exchange Availability service that is running in the remote Active Directory forest retrieve the requested information locally.

 

CORRECÇÃO

Vou corrigir esta parte porque esta solução não é suportada pela Microsoft e pode gerar erro no Exchange Online INTERNAL SERVER ERROR, aqui vai a solução final.

A TER EM ATENÇÃO

As definições de PROXY são a da tua máquina host de domínio não de uma ligação de VM

 

A Solução que eu encontrei foi resolver o Autodiscovery de fora e apanhar o Link, sendo assim já podemos instanciar o Serviço desta forma, para o fazeres basta invocares o método GetService().Xpto

Tens de adicionar a referencia ao teu projecto: Microsoft.Exchange.WebServices

 

/// <summary>
/// Gets the service.
/// </summary>
/// <returns></returns>
public static ExchangeService GetService()
{
// Get User and Pass for Super User Live@Edu
string sUser = GetUrl.sUser;
string sPass = GetUrl.sPass;

// Create the binding.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010)
{ /* Define credentials.*/
Credentials = new WebCredentials(sUser, sPass),
Url = new Uri("https://OTeuServerNaCloud.outlook.com/EWS/Exchange.asmx")
};
return service;
}



EXEMPLO 




Credentials = new NetworkCredential(UserXPTO, PassXPTO, Microsoft)



Código Complero




public static ExchangeService GetBinding()
{
// Create the binding.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
//Proxy
IWebProxy proxy = new WebProxy(GetUrl.ProxyAddress, true)
{
Credentials = new NetworkCredential(GetUrl.ProxyUser, GetUrl.ProxyPass,
GetUrl.ProxyDomain)
};

WebRequest.DefaultWebProxy = proxy;
service.Credentials = new WebCredentials("admin@dominio.pt", "999999");

try
{
// Use the AutodiscoverUrl method to locate the service endpoint.
service.AutodiscoverUrl("admin@dominio.pt", RedirectionUrlValidationCallback);
}
catch (AutodiscoverRemoteException ex)
{
Console.WriteLine("Exception thrown: " + ex.Error.Message);
}
return service;
}

static bool RedirectionUrlValidationCallback(String redirectionUrl)
{
// Perform validation.
// Validation is developer dependent to ensure a safe redirect.
return true;
}

Like