Mostrar mensagens com a etiqueta C#. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta C#. 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
}

2 de abril de 2011

Criar uma Lista de Distribuição Dinâmica (DDL)

image

 

/// <summary>
/// Session runspace instance.
/// </summary>
private readonly SessionRunspace sessionRunspace;

/// <summary>
/// Initializes a new instance of the OutlookLiveGroups class.
/// </summary>
/// <param name="sessionRunspace">Session runspace instance.</param>
public OutlookLiveGroups(SessionRunspace sessionRunspace)
{
if (sessionRunspace == null)
{
throw new ArgumentOutOfRangeException("sessionRunspace");
}

this.sessionRunspace = sessionRunspace;
}

/// <summary>
/// Method to create Dynamic distribution list (DDL)
/// </summary>
/// <param name="ddlName">Name of the DDL</param>
/// <param name="filterExp">filter expression</param>
/// <returns>true if success</returns>
public bool CreateDDL(string ddlName, string filterExp)
{
if (string.IsNullOrEmpty(ddlName))
{
throw new ArgumentOutOfRangeException("ddlName");
}

if (string.IsNullOrEmpty(filterExp))
{
throw new ArgumentOutOfRangeException("filterExp");
}

try
{
var command = new PSCommand();
command.AddScript(string.Format(GroupsScripts.CreateDdlScript, ddlName, filterExp));
this.sessionRunspace.ExecuteCommand(command);
return true;
}
catch
{
return false;
}
}



Criar Mailbox on Premisse

Para ambientes onde o utilizador da AD é diferente do Live@edu

/// <summary>
/// Script names used by mailbox.
/// </summary>
internal static class MailBoxScripts
{
/// <summary>
/// Name of Script used to create on-premise exchange mailbox.
/// </summary>
internal const string CreateOnPremiseExchangeMailBoxScript =
@"New-Mailbox -Name '{0}' -Alias '{1}' -OrganizationalUnit '{2}' -UserPrincipalName '{3}'
-SamAccountName '{4}' -FirstName '{5}' -Initials '{6}' -LastName '{7}'
-Password:(ConvertTo-SecureString {8} -AsPlainText –Force) -ResetPasswordOnNextLogon $false
Set-Mailbox {9} -CustomAttribute1 '{10}' -CustomAttribute2 '{11}'"
;
}



Como definir Scripts PowerShell para passar em C#

Exemplo para Scripts de Domínio

/// <summary>
/// Script names used by Domains namespace.
/// </summary>
internal static class DomainScripts
{
/// <summary>
/// Name of script used to set bad word blocker
/// </summary>
internal const string BlockBadWordsScript = "Set-SupervisionPolicy -BadWordsPolicyEnabled: $true -BadWordsList:'{0}'";

/// <summary>
/// Name of script used to disable bad word blocker
/// </summary>
internal const string DisableBlockBadWordsScript = "Set-SupervisionPolicy -BadWordsPolicyEnabled: $false";

/// <summary>
/// Name of script used to enable/disable Outlook Web Access Instant Messaging feature
/// </summary>
internal const string DisableInstantMessagingScript = "set-owamailboxpolicy -Identity:'{0}' -instantmessagingenabled:$false";

/// <summary>
/// Name of script used to enable/disable Outlook Web Access Text Messaging feature
/// </summary>
internal const string DisableTextMessagingScript = "set-owamailboxpolicy -Identity:'{0}' -textmessagingenabled:$false";

/// <summary>
/// Name of script used to enable/disable Outlook Web Access Instant Messaging feature
/// </summary>
internal const string EnableInstantMessagingScript = "set-owamailboxpolicy -Identity:'{0}' -instantmessagingenabled:$true";

/// <summary>
/// Name of script used to enable/disable Outlook Web Access Text Messaging feature
/// </summary>
internal const string EnableTextMessagingScript = "set-owamailboxpolicy -Identity:'{0}' -textmessagingenabled:$true";

/// <summary>
/// Name of script used to get mailbox policy
/// </summary>
internal const string GetMailboxPolicyScript = "Get-OwaMailboxPolicy -identity {0}";

/// <summary>
/// Name of script used to view the blocked bad words
/// </summary>
internal const string ListBadWordsScript = "Get-SupervisionPolicy -DisplayDetails";
}



PowerShell e C#, Criar, Importar e Fechar Sessões Outlook Live

 

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;

/// <summary>
/// Powershell commands to create, import, exit session.
/// </summary>
internal class OutlookLiveSession
{
/// <summary>
/// Powreshell Runspace instance.
/// </summary>
private readonly Runspace runspace;

/// <summary>
/// Initializes a new instance of the OutlookLiveSession class.
/// </summary>
/// <param name="runspace">Runspace instance.</param>
public OutlookLiveSession(Runspace runspace)
{
if (runspace == null)
{
throw new ArgumentOutOfRangeException("runspace");
}

this.runspace = runspace;
}

#region Methods

/// <summary>
/// Create outlook live session
/// </summary>
/// <param name="userName">The user name to authenticate the session.</param>
/// <param name="password">The password to authenticate the session.</param>
/// <param name="connectionUri">Uri for creating the connection.</param>
/// <returns>Powershell Session instance.</returns>
public PSSession CreateSession(string userName, SecureString password, string connectionUri)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentOutOfRangeException("userName");
}

if (password == null)
{
throw new ArgumentOutOfRangeException("password");
}

if (string.IsNullOrEmpty(connectionUri))
{
throw new ArgumentOutOfRangeException("connectionUri");
}

this.runspace.SetCredential(userName, password);

var command = new PSCommand();
command.AddScript(string.Format(SessionScripts.NewSessionScript, connectionUri));
var result = this.runspace.ExecuteCommand<PSSession>(command);
return result[0];
}

/// <summary>
/// Import Powershell Session.
/// </summary>
/// <param name="session">Powershell Session.</param>
public void ImportSession(PSSession session)
{
if (session == null)
{
throw new ArgumentOutOfRangeException("session");
}

var command = new PSCommand();
command.AddCommand(SessionScripts.ImportSessionScript);
command.AddParameter(Constants.Session, session);
this.runspace.ExecuteCommand(command);
}

/// <summary>
/// Exit Powershell Session.
/// </summary>
/// <param name="session">Powershell Session.</param>
public void ExitSession(PSSession session)
{
if (session == null)
{
throw new ArgumentOutOfRangeException("session");
}

var command = new PSCommand();
command.AddCommand(SessionScripts.ExitSessionScript);
command.AddParameter(Constants.Session, session);
this.runspace.ExecuteCommand(command);
}

#endregion
}



Criar novo ALIAS, definir ALIAS como primário

image

Em baixo está o código para criar um novo alias para um utilizador. Um alias de proxy não cria uma nova caixa de correio. Ele apenas associa o alias de proxy com uma caixa de correio existente.

Criar um novo ALIAS para um utilizadoe existente

Define um ALIAS como primário para utilizadoe existente

 

// Script to create a new alias for an exisiting user.
string addProxyEmailAddressScript = @"$user = '{0}'
$mailbox = Get-Mailbox -identity $user
$mailbox.EmailAddresses += '{1}'
set-mailbox -identity $user -EmailAddresses $mailbox.EmailAddresses"
;
// Exisiting user.
string userEmailAddress = "saramarshal@contosouniversity.net";
// New alias.
string proxyEmailAddress = "sara.marshal@contosouniversity.net";

// Create new alias
PowerShell ps = PowerShell.Create();
PSCommand command = newPSCommand();
command.AddScript(string.Format(addProxyEmailAddressScript, userEmailAddress, proxyEmailAddress));
ps.Commands = command;





// Script to set primary alias for an exisiting user.
string updatePrimaryEmaillAddressScript = "Set-mailbox {0} -EmailAddresses SMTP:{1}";
// Current primary alias for an exisiting user.
string currentPrimaryAlias = "saramarshal@contosouniversity.net";
// Primary alias to be set.
string setToPrimaryAlias = "sara.marshal@contosouniversity.net";

// Set primary alias
PowerShell ps = PowerShell.Create();
PSCommand command = newPSCommand();
command.AddScript(string.Format(updatePrimaryEmaillAddressScript, currentPrimaryAlias, setToPrimaryAlias));
ps.Commands = command;
ps.Runspace = runspace;
ps.Invoke<PSObject>();






Criar um grupo dinâmico de distribuição

Pré-requisitos: http://msedulive.blogspot.com/2011/04/pre-requisitos-powershell.html

Pode haver pedidos do departamento acadêmico ou outro pessoal para criar um novo grupo dinâmico de distribuição. A lista de associação para um grupo dinâmico de distribuição é calculada sempre que uma mensagem é enviada para o grupo com base em filtros e condições definidas quando o grupo é criado.

Abaixo está um exemplo de código para criar um grupo dinâmico de distribuição que inclui todos os destinatários no departamento de ciência da computação na escola.

 

// Script to create a new Dynamic Distribution Group.
string createDdlScript = "New-DynamicDistributionGroup -Name:{0} -RecipientFilter:\"{1}\"";
// Name of the group.
string ddlName = "Computer Science";
// Recipient filter. Filter all users with deaprtment "Computer Science"
string ddlRecipientFilter = "Department –Eq 'Computer Science'";

// Create Dynamic Distribution Group
PowerShell ps = PowerShell.Create();
PSCommand command = newPSCommand();
command.AddScript(string.Format(createDdlScript, ddlName, ddlRecipientFilter));
ps.Commands = command;
ps.Runspace = runspace;
ps.Invoke<PSObject>();



Criar e Importar Sessões remotas Outlook Live

Pré-requisitos: http://msedulive.blogspot.com/2011/04/pre-requisitos-powershell.html

Antes de todas as tarefas administrativas podem ser executadas, uma sessão remota para o Outlook Live tem de ser estabelecida. Discutimos como conseguir isso na seção "powershell" usando o cliente de desktop local do Windows PowerShell. Nesta seção, discutiremos como conseguir isso de um programa c#. Abaixo está o exemplo de código para criar uma sessão.

 

// Abaixo os namespaces devem ser importados para o PowerShell.
// Estes estão disponíveis em System.Management.Automation.dll
// System.Management.Automation.dll é instalado como parte do Windows
// Instalação do Framework de gerenciamento.
using System.Management.Automation;
using System.Management.Automation.Runspaces;
// Criar espaço de execução e sessão remota para Oulook Live, que é importado para
// Este espaço de execução.
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

// Set credenciais para fazer uma conexão remota com o Outlook Live
string userName = "admin@contosouniversity.net";
string password = "password";
PSCredential cred = newPSCredential(userName, password);
// Script para definir uma variável. Esta variável é usado pelo script de nova sessão.
string setVariableScript = "Set-Variable";
PowerShell ps1 = PowerShell.Create();
PSCommand setVariableCommand = newPSCommand();
setVariableCommand.AddScript(setVariableScript);
setVariableCommand.AddParameter("Name", "Cred");
setVariableCommand.AddParameter("Value", cred);
ps1.Commands = setVariableCommand;
ps1.Runspace = runspace;
ps1.Invoke<PSObject>();



Like