public static ExchangeService CreateConnection(string emailAddress) { // Hook up the cert callback to prevent error if Microsoft.NET doesn't trust the server ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; ExchangeService service = null; if (!string.IsNullOrEmpty(Configuration.ExchangeAddress)) { service = new ExchangeService(); service.Url = new Uri(Configuration.ExchangeAddress); } else { if (!string.IsNullOrEmpty(emailAddress)) { service = new ExchangeService(); service.AutodiscoverUrl(emailAddress); } } return service; }
public static ExchangeService GetExchangeService(string emailAddress, string username, string password, ExchangeVersion exchangeVersion, Uri serviceUri) { var service = new ExchangeService(exchangeVersion); service.Credentials = new WebCredentials(username, password); service.EnableScpLookup = false; if (serviceUri == null) { service.AutodiscoverUrl(emailAddress, (url) => { bool result = false; var redirectionUri = new Uri(url); if (redirectionUri.Scheme == "https") { result = true; } return result; }); } else { service.Url = serviceUri; } return service; }
/// <summary> /// Binds to an existing meeting request and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the meeting request.</param> /// <param name="id">The Id of the meeting request to bind to.</param> /// <returns>A MeetingRequest instance representing the meeting request corresponding to the specified Id.</returns> public static new MeetingRequest Bind(ExchangeService service, ItemId id) { return MeetingRequest.Bind( service, id, PropertySet.FirstClassProperties); }
public static void MoveMailToDeletedFolder() { OApplicationSetting applicationSetting = OApplicationSetting.Current; ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // trust any certificate return true; }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential(applicationSetting.EmailUserName, applicationSetting.EmailPassword, applicationSetting.EmailDomain); service.Url = new Uri(applicationSetting.EmailExchangeWebServiceUrl); FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); if (findResults.TotalCount > 0) { service.LoadPropertiesForItems(findResults.Items, PropertySet.FirstClassProperties); foreach (Item item in findResults.Items) { item.Delete(DeleteMode.MoveToDeletedItems); } } }
/// <summary> /// Connects with the Sioux Exchange server to check whether the given username/password are valid /// Sioux credentials. Note: this method may take a second or two. /// </summary> public static bool CheckLogin(string username, string password) { Console.WriteLine("Connecting to exchange server..."); ServicePointManager.ServerCertificateValidationCallback = StolenCode.CertificateValidationCallBack; var service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); service.Credentials = new WebCredentials(username, password, Domain); service.Url = new Uri("https://" + ExchangeServer + "/EWS/Exchange.asmx"); service.UseDefaultCredentials = false; try { // resolve a dummy name to force the client to connect to the server. service.ResolveName("garblwefuhsakldjasl;dk"); return true; } catch (ServiceRequestException e) { // if we get a HTTP Unauthorized message, then we know the u/p was wrong. if (e.Message.Contains("401")) { return false; } throw; } }
/// <summary> /// Binds to an existing task and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the task.</param> /// <param name="id">The Id of the task to bind to.</param> /// <returns>A Task instance representing the task corresponding to the specified Id.</returns> public static new Task Bind(ExchangeService service, ItemId id) { return Task.Bind( service, id, PropertySet.FirstClassProperties); }
public static ExchangeService ConnectToService(IUserData userData, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); if (userData.AutodiscoverUrl == null) { Console.Write(string.Format("Using Autodiscover to find EWS URL for {0}. Please wait... ", userData.EmailAddress)); service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; Console.WriteLine("Autodiscover Complete"); } else { service.Url = userData.AutodiscoverUrl; } return service; }
/// <summary> /// Binds to an existing calendar folder and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the calendar folder.</param> /// <param name="id">The Id of the calendar folder to bind to.</param> /// <returns>A CalendarFolder instance representing the calendar folder corresponding to the specified Id.</returns> public static new CalendarFolder Bind(ExchangeService service, FolderId id) { return CalendarFolder.Bind( service, id, PropertySet.FirstClassProperties); }
/// <summary> /// Binds to an existing task and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the task.</param> /// <param name="id">The Id of the task to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A Task instance representing the task corresponding to the specified Id.</returns> public static new Task Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<Task>(id, propertySet); }
private ExchangeService connectToExchange() { var es = new ExchangeService(ExchangeVersion.Exchange2013) { TraceEnabled = true, TraceFlags = TraceFlags.All }; // ### Option 1 ### //es.UseDefaultCredentials = true; //es.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); // ### Option 2 ### //string username = "******"; //var pwd = "SYMsym1009"; //es.Credentials = new WebCredentials(username, pwd); // ### Option 3 ### Console.Write("Username: "******"Password: "******"https://webmaileu.options-it.com/EWS/Exchange.asmx"); es.Credentials = new WebCredentials(username, Utilities.GetPasswordFromSecurtString(pwd)); return es; }
/// <summary> /// Binds to an existing calendar folder and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the calendar folder.</param> /// <param name="id">The Id of the calendar folder to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A CalendarFolder instance representing the calendar folder corresponding to the specified Id.</returns> public static new CalendarFolder Bind( ExchangeService service, FolderId id, PropertySet propertySet) { return service.BindToFolder<CalendarFolder>(id, propertySet); }
public static ExchangeService ConnectToService( IUserData userData, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); if (userData.AutodiscoverUrl == null) { service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; } else { service.Url = userData.AutodiscoverUrl; } return service; }
public static ExchangeService ConnectToServiceWithImpersonation( IUserData userData, string impersonatedUserSMTPAddress, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); ImpersonatedUserId impersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impersonatedUserSMTPAddress); service.ImpersonatedUserId = impersonatedUserId; if (userData.AutodiscoverUrl == null) { service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; } else { service.Url = userData.AutodiscoverUrl; } return service; }
/// <summary> /// Method is returning Folder object from WellKnownFolderName enum. /// </summary> /// <param name="wellKnownFolderName">WellKnownFolderName for which Folder object needs to be returned.</param> /// <param name="ewsSession">ExchangeService session context.</param> /// <returns></returns> public static Folder GetWellKnownFolder(WellKnownFolderName wellKnownFolderName, ExchangeService ewsSession) { FolderId wellKnownFolderId = new FolderId(wellKnownFolderName); Folder wellKnownFolder = Folder.Bind(ewsSession, wellKnownFolderId); return wellKnownFolder; }
/// <summary> /// Manages the connection for multiple <see cref="StreamingSubscription"/> items. Attention: Use only for subscriptions on the same CAS. /// </summary> /// <param name="exchangeService">The ExchangeService instance this collection uses to connect to the server.</param> public StreamingSubscriptionCollection(ExchangeService exchangeService, Action<SubscriptionNotificationEventCollection> EventProcessor, GroupIdentifier groupIdentifier) { this._exchangeService = exchangeService; this._EventProcessor = EventProcessor; this._groupIdentifier = groupIdentifier; _connection = CreateConnection(); }
/// <summary> /// Binds to an existing meeting cancellation message and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the meeting cancellation message.</param> /// <param name="id">The Id of the meeting cancellation message to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A MeetingCancellation instance representing the meeting cancellation message corresponding to the specified Id.</returns> public static new MeetingCancellation Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<MeetingCancellation>(id, propertySet); }
/// <summary> /// Binds to an existing meeting cancellation message and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the meeting cancellation message.</param> /// <param name="id">The Id of the meeting cancellation message to bind to.</param> /// <returns>A MeetingCancellation instance representing the meeting cancellation message corresponding to the specified Id.</returns> public static new MeetingCancellation Bind(ExchangeService service, ItemId id) { return MeetingCancellation.Bind( service, id, PropertySet.FirstClassProperties); }
public ActionResult SignUp(SignUpView view) { String smtpAddess = "*****@*****.**"; String password = "******"; var exchangeService = new ExchangeService(ExchangeVersion.Exchange2007_SP1); exchangeService.Credentials = new WebCredentials(smtpAddess, password); exchangeService.AutodiscoverUrl(smtpAddess, RedirectionUrlValidationCallback); Contact contact = new Contact(exchangeService); contact.GivenName = view.GivenName; contact.Surname = view.Surname; contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName; contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(view.Email); try { contact.Save(); } catch(Exception e) { ViewBag.Message = e.Message; return View(view); } return View("Thanks"); }
/// <summary> /// Initializes a new instance of the <see cref="SubscriptionBase"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="id">The id.</param> internal SubscriptionBase(ExchangeService service, string id) : this(service) { EwsUtilities.ValidateParam(id, "id"); this.id = id; }
/// <summary> /// Binds to an existing contact and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the contact.</param> /// <param name="id">The Id of the contact to bind to.</param> /// <returns>A Contact instance representing the contact corresponding to the specified Id.</returns> public static new Contact Bind(ExchangeService service, ItemId id) { return Contact.Bind( service, id, PropertySet.FirstClassProperties); }
/// <summary> /// Binds to an existing e-mail message and loads its first class properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the e-mail message.</param> /// <param name="id">The Id of the e-mail message to bind to.</param> /// <returns>An EmailMessage instance representing the e-mail message corresponding to the specified Id.</returns> public static new EmailMessage Bind(ExchangeService service, ItemId id) { return EmailMessage.Bind( service, id, PropertySet.FirstClassProperties); }
public static void CreateAppointment(ExchangeService service, string fechaInicio, string fechaFin, string lugar, string nombre, string dias) { Appointment app = new Appointment(service); app.Subject = nombre; app.Location = lugar; DateTime dateInicio = Convert.ToDateTime(fechaInicio); DateTime dateFin = Convert.ToDateTime(fechaFin); TimeSpan timeSpan = dateFin.Subtract(dateInicio); string timeFor = timeSpan.ToString(@"hh\:mm\:ss"); var time = TimeSpan.Parse(timeFor); app.Start = dateInicio; app.End = dateInicio.Add(time); //----- if (dias != "") { DayOfTheWeek[] days = stringToDays(dias); app.Recurrence = new Recurrence.WeeklyPattern(app.Start.Date, 1, days); app.Recurrence.StartDate = app.Start.Date; app.Recurrence.EndDate = dateFin; } app.IsReminderSet = true; app.ReminderMinutesBeforeStart = 15; app.Save(SendInvitationsMode.SendToAllAndSaveCopy); }
/// <summary> /// Binds to an existing item, whatever its actual type is, and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the item.</param> /// <param name="id">The Id of the item to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>An Item instance representing the item corresponding to the specified Id.</returns> public static Item Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<Item>(id, propertySet); }
public ExchangeWriter() { log.Debug("Creating Exchange writer"); ExchangeConnection con = new ExchangeConnection(); service = con.GetExchangeService(); ResetAppointmentObject(); }
public AppointmentGroup GetNextAppointments() { try { var newAppointments = new AppointmentGroup(); var service = new ExchangeService(); service.UseDefaultCredentials = true; service.AutodiscoverUrl(UserPrincipal.Current.EmailAddress); DateTime from = DateTime.Now.AddMinutes(-5); DateTime to = DateTime.Today.AddDays(1); IEnumerable<Appointment> appointments = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(from, to)) .Select(MakeAppointment); newAppointments.Next = appointments.Where(o => o != null && o.Start >= DateTime.Now) .OrderBy(o => o.Start).ToList(); nextAppointments = newAppointments; return newAppointments; } catch (Exception e) { Trace.WriteLine(e.ToString()); return nextAppointments; } }
/// <summary> /// Initializes an unsaved local instance of <see cref="Persona"/>. To bind to an existing Persona, use Persona.Bind() instead. /// </summary> /// <param name="service">The ExchangeService object to which the Persona will be bound.</param> public Persona(ExchangeService service) : base(service) { this.PersonaType = string.Empty; this.CreationTime = null; this.DisplayNameFirstLastHeader = string.Empty; this.DisplayNameLastFirstHeader = string.Empty; this.DisplayName = string.Empty; this.DisplayNameFirstLast = string.Empty; this.DisplayNameLastFirst = string.Empty; this.FileAs = string.Empty; this.Generation = string.Empty; this.DisplayNamePrefix = string.Empty; this.GivenName = string.Empty; this.Surname = string.Empty; this.Title = string.Empty; this.CompanyName = string.Empty; this.ImAddress = string.Empty; this.HomeCity = string.Empty; this.WorkCity = string.Empty; this.Alias = string.Empty; this.RelevanceScore = 0; // Remaining properties are initialized when the property definition is created in // PersonaSchema.cs. }
/// <summary> /// Binds to an existing Persona and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the Persona.</param> /// <param name="id">The Id of the Persona to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A Persona instance representing the Persona corresponding to the specified Id.</returns> public static new Persona Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<Persona>(id, propertySet); }
/// <summary> /// Binds to an existing e-mail message and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the e-mail message.</param> /// <param name="id">The Id of the e-mail message to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>An EmailMessage instance representing the e-mail message corresponding to the specified Id.</returns> public static new EmailMessage Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<EmailMessage>(id, propertySet); }
/// <summary> /// Binds to an existing appointment and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the appointment.</param> /// <param name="id">The Id of the appointment to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>An Appointment instance representing the appointment corresponding to the specified Id.</returns> public static new Appointment Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<Appointment>(id, propertySet); }
/// <summary> /// Binds to an existing contact and loads the specified set of properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to use to bind to the contact.</param> /// <param name="id">The Id of the contact to bind to.</param> /// <param name="propertySet">The set of properties to load.</param> /// <returns>A Contact instance representing the contact corresponding to the specified Id.</returns> public static new Contact Bind( ExchangeService service, ItemId id, PropertySet propertySet) { return service.BindToItem<Contact>(id, propertySet); }
/// <summary> /// Reads emails from an Exchange server /// </summary> /// <param name="settings">Settings to use</param> /// <param name="options">Options to use</param> /// <returns> /// List of /// { /// string Id. /// string To. /// string Cc. /// string From. /// DateTime Date. /// string Subject. /// string BodyText. /// string BodyHtml. /// List(string) AttachmentSaveDirs /// } /// </returns> public static List <EmailMessageResult> ReadEmailFromExchangeServer([PropertyTab] ExchangeSettings settings, [PropertyTab] ExchangeOptions options) { if (!options.IgnoreAttachments) { // Check that save directory is given if (options.AttachmentSaveDirectory == "") { throw new ArgumentException("No save directory given. ", nameof(options.AttachmentSaveDirectory)); } // Check that save directory exists if (!Directory.Exists(options.AttachmentSaveDirectory)) { throw new ArgumentException("Could not find or access attachment save directory. ", nameof(options.AttachmentSaveDirectory)); } } // Connect, create view and search filter ExchangeService exchangeService = Services.ConnectToExchangeService(settings); ItemView view = new ItemView(options.MaxEmails); var searchFilter = BuildFilterCollection(options); FindItemsResults <Item> exchangeResults; if (!string.IsNullOrEmpty(settings.Mailbox)) { var mb = new Mailbox(settings.Mailbox); var fid = new FolderId(WellKnownFolderName.Inbox, mb); var inbox = Folder.Bind(exchangeService, fid); exchangeResults = searchFilter.Count == 0 ? inbox.FindItems(view) : inbox.FindItems(searchFilter, view); } else { exchangeResults = searchFilter.Count == 0 ? exchangeService.FindItems(WellKnownFolderName.Inbox, view) : exchangeService.FindItems(WellKnownFolderName.Inbox, searchFilter, view); } // Get email items List <EmailMessage> emails = exchangeResults.Where(msg => msg is EmailMessage).Cast <EmailMessage>().ToList(); // Check if list is empty and if an error needs to be thrown. if (emails.Count == 0 && options.ThrowErrorIfNoMessagesFound) { // If not, return a result with a notification of no found messages. throw new ArgumentException("No messages matching the search filter found. ", nameof(options.ThrowErrorIfNoMessagesFound)); } // Load properties for each email and process attachments var result = ReadEmails(emails, exchangeService, options); // should delete mails? if (options.DeleteReadEmails) { emails.ForEach(msg => msg.Delete(DeleteMode.HardDelete)); } // should mark mails as read? if (!options.DeleteReadEmails && options.MarkEmailsAsRead) { foreach (EmailMessage msg in emails) { msg.IsRead = true; msg.Update(ConflictResolutionMode.AutoResolve); } } return(result); }
private static IMessagePostProcessor GetPostProcesor(Config.EmailSettings emailSettings, ExchangeService service) { if (string.IsNullOrEmpty(emailSettings.CompletedFolder) || string.IsNullOrEmpty(emailSettings.ErrorFolder)) { return(new DeleterMessagePostProcessor()); } return(new ArchiverMessagePostProcessor(emailSettings.CompletedFolder, emailSettings.ErrorFolder, service)); }
static void Main(string[] args) { string strsummary = null; string strdescription = null; string strissuetype = null; Item strattachmentloc = null; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential("gades", "suDha@7devi", "camp"); service.AutodiscoverUrl("*****@*****.**", (a) => { return(true); }); FindItemsResults <Item> findResults = service.FindItems( WellKnownFolderName.Inbox, new ItemView(1)); foreach (Item item in findResults.Items) { Console.WriteLine(item.Subject); strsummary = item.Subject; //strdescription = item.Body; strissuetype = "Bug"; strattachmentloc = item; } Jira objJira = new Jira(); objJira.Url = "http://*****:*****@"C:/Users/sarathg/Desktop/sample.txt"); //string[] words = str.Split(','); //foreach (string word in words) //{ // switch (word.Split(':')[0]) // { // case "summary": strsummary = word.Split(':')[1]; // break; // case "description": strdescription = word.Split(':')[1]; // break; // case "IssueType": strissuetype = word.Split(':')[1]; // break; // } //} JiraJson js = new JiraJson { fields = new Fields { summary = strsummary, //description = strdescription, project = new Project { key = "JIR" }, issuetype = new IssueType { name = strissuetype } } }; var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); objJira.JsonString = javaScriptSerializer.Serialize(js); objJira.UserName = ConfigurationManager.AppSettings["JiraUserName"]; objJira.Password = ConfigurationManager.AppSettings["JiraPassword"]; objJira.filePaths = new List <string>() { "" }; objJira.AddJiraIssue(); Console.ReadKey(); }
public Dev2EmailSender(ExchangeService exchangeService, IExchangeEmailSender emailSender) { ExchangeService = exchangeService; EmailSender = emailSender; }
public EMLReturnClass Send(List <EMLMailTarget> targets, string m_MailSubject, string m_MailHtmlBody, string m_MailTextBody, bool substitute) { EMLReturnClass outcome = new EMLReturnClass(); EMLReturnClass outcome2 = new EMLReturnClass(); MailSubject = m_MailSubject; MailHtmlBody = m_MailHtmlBody; MailTextBody = m_MailTextBody; service = new ExchangeService(exVer, TimeZoneInfo.Local); try { ServicePointManager.ServerCertificateValidationCallback = delegate(Object oobj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return(true); }; service.Url = new Uri(MailserverUrl); } catch (Exception ex) { outcome.SetFailureMessage("Problem contacting exchange mail host", ex.ToString()); } if (outcome.Success) { try { if (MailserverDomain.Length > 0) { cred = new WebCredentials(MailserverUsername, MailserverPassword, MailserverDomain); } else { cred = new WebCredentials(MailserverUsername, MailserverPassword); } service.Credentials = cred; } catch (Exception ex) { outcome.SetFailureMessage("Problem contacting exchange mail host", ex.ToString()); } } if (outcome.Success) { foreach (var x in targets) { if (EMLHelpers.IsValidEmail(x.EmailAddress)) { try { if (substitute) { MailHtmlBody = EMLHelpers.SubstituteFields(m_MailHtmlBody, x); //MailTextBody = EMLHelpers.SubstituteFields(m_MailTextBody, x); MailSubject = EMLHelpers.SubstituteFields(m_MailSubject, x); } message = new EmailMessage(service); message.Body = new MessageBody(BodyType.HTML, MailHtmlBody); message.Subject = MailSubject; message.ToRecipients.Add(new EmailAddress(x.Name, x.EmailAddress)); message.From = new EmailAddress(FromEmailName, FromEmailAddress); if (EMLHelpers.IsValidEmail(ReplyToEmailAddress)) { //message.ReplyTo.Add(new MailAddress(ReplyToEmailAddress, ReplytoEmailName)); message.ReplyTo.Add(new EmailAddress(ReplytoEmailName, ReplyToEmailAddress)); } message.SendAndSaveCopy(); } catch (Exception ex) { outcome.Errors.Add("Sending Error with " + x.Name + " " + ex.ToString()); } } else { outcome.Errors.Add("No Email address for " + x.Name); } } } if (outcome.Errors.Count > 0 && outcome.Success) { outcome.Success = false; } return(outcome); }
/// <summary> /// Initializes a new instance of the <see cref="SetTeamMailboxRequest"/> class. /// </summary> /// <param name="service">The service</param> /// <param name="emailAddress">TeamMailbox email address</param> /// <param name="sharePointSiteUrl">SharePoint site URL</param> /// <param name="state">TeamMailbox state</param> SetTeamMailboxRequest(ExchangeService service, EmailAddress emailAddress, Uri sharePointSiteUrl, TeamMailboxLifecycleState state) : super(service)
public TaskManager(string taskCreatorEmailID, string password) { _taskCreatorEmailID = taskCreatorEmailID; _password = password; Service = GetExchangeService(); }
protected ItemObjectModel([NotNull] FolderModel folder, [NotNull] T obj, ICollection <AttachmentModel> attachments, [NotNull] ExchangeService service) : base(obj, service) { this.Folder = folder; this.Attachments = attachments; }
/// <summary> /// Create message in the folder. /// </summary> /// <param name="messageId"></param> /// <param name="mailFolder"></param> /// <param name="exchangeService"></param> internal static async Task CreateMessage(int messageId, MailFolder mailFolder, ExchangeService exchangeService) { Message message = new Message(exchangeService); message.Subject = $"Test msg {messageId}"; message.Body = new ItemBody() { ContentType = BodyType.Html, Content = $"This is test message for sync {messageId}" }; message.ToRecipients = new List<Recipient>() { new Recipient() { EmailAddress = new EmailAddress() { Address = $"abc{messageId}@def.com" } } }; await message.SaveAsync(mailFolder); }
/// <summary> /// Convert Email collection t EMailMessageResults. /// </summary> /// <param name="emails">Emails collection.</param> /// <param name="exchangeService">Exchange services.</param> /// <param name="options">Options.</param> /// <returns>Collection of EmailMessageResult.</returns> private static List <EmailMessageResult> ReadEmails(IEnumerable <EmailMessage> emails, ExchangeService exchangeService, ExchangeOptions options) { List <EmailMessageResult> result = new List <EmailMessageResult>(); foreach (EmailMessage email in emails) { // Define property set var propSet = new PropertySet( BasePropertySet.FirstClassProperties, EmailMessageSchema.Body, EmailMessageSchema.Attachments); // Bind and load email message with desired properties var newEmail = EmailMessage.Bind(exchangeService, email.Id, propSet); var pathList = new List <string>(); if (!options.IgnoreAttachments) { // Save all attachments to given directory pathList = SaveAttachments(newEmail.Attachments, options); } // Build result for email message var emailMessage = new EmailMessageResult { Id = newEmail.Id.UniqueId, Date = newEmail.DateTimeReceived, Subject = newEmail.Subject, BodyText = "", BodyHtml = newEmail.Body.Text, To = string.Join(",", newEmail.ToRecipients.Select(j => j.Address)), From = newEmail.From.Address, Cc = string.Join(",", newEmail.CcRecipients.Select(j => j.Address)), AttachmentSaveDirs = pathList }; // Catch exception in case of server version is earlier than Exchange2013 try { emailMessage.BodyText = newEmail.TextBody.Text; } catch { } result.Add(emailMessage); } return(result); }
public static int Unread() { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } HAP.AD.User u = ((HAP.AD.User)Membership.GetUser()); if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Forms && string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { HttpCookie token = HttpContext.Current.Request.Cookies["token"]; if (token == null) { throw new AccessViolationException("Token Cookie Missing, user not logged in correctly"); } service.Credentials = new NetworkCredential((hapConfig.Current.SMTP.EWSUseEmailoverAN ? u.Email : u.UserName), TokenGenerator.ConvertToPlain(token.Value), HAP.Web.Configuration.hapConfig.Current.AD.UPN); } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.ImpersonateContained(); service.UseDefaultCredentials = true; //service.Credentials = CredentialCache.DefaultNetworkCredentials; } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain)) { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword); } else { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain); } service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, u.Email); } } Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox); SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(10); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Windows || !string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.EndContainedImpersonate(); } return(findResults.TotalCount); }
/// <summary> /// Initializes a new instance of the <see cref="MoveCopyFolderRequest<TResponse>"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="errorHandlingMode"> Indicates how errors should be handled.</param> MoveCopyFolderRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) : super(service, errorHandlingMode)
public FolderMailboxManager(ExchangeService connection, string incomingFolder, IMessagePostProcessor postProcessor) { _service = connection; _mailFolder = incomingFolder; _postProcessor = postProcessor; }
public void TestExchangeService_CTOR_ValidArguments() { Assert.DoesNotThrow(() => { var qs = new ExchangeService(Channel, BaseQueueService); }); }
static void Main(string[] args) { // ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); // service.Credentials = new WebCredentials("*****@*****.**", "password"); // service.Credentials = new WebCredentials("*****@*****.**", "Summer2020"); service.Credentials = new WebCredentials("s.svensson", "Summer2020", "htb"); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; // BypassSSLCert ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; // service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); service.Url = new Uri("https://10.10.10.210/EWS/Exchange.asmx"); EmailMessage email = new EmailMessage(service); // Manually add each email address to recipient // email.ToRecipients.Add("*****@*****.**"); // email.ToRecipients.Add("*****@*****.**"); // Add email address from an array of recipients string[] Recipients = { "Administrator", "alex", "bob", "charles", "david", "davis", "donald", "edward", "frans", "fred", "gregg", "james", "jea_test_account", "jeff", "jenny", "jhon", "jim", "joe", "joseph", "kalle", "kevin", "knut", "lars", "lee", "marshall", "michael", "richard", "robert", "robin", "ronald", "steven", "stig", "sven", "teresa", "thomas", "travis", "william" }; foreach (string rcpt in Recipients) { email.ToRecipients.Add(rcpt + "@htb.local"); } email.Subject = "Hello from sven"; // email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API"); // email.Body = new MessageBody("<html><h1>Download to update</h1><img src=\"file://10.10.14.12/image.jpg\"><p><a href='file://10.10.14.18/download.jpg'>reel2</a></p></html>"); email.Body = new MessageBody("<html><h1>Download to update</h1><p><a href='http://10.10.14.18/download.jpg'>reel2</a></p></html>"); // string html = @"<html> // <head> // </head> // <body> // <a href=""http://10.10.14.18"">click here</a> // </body> // </html>"; // string html = @"cid:message.html"; // email.Body = new MessageBody(BodyType.HTML, html); // string file = @"D:\pictures\Party.jpg"; // string file = @"/mnt/d/pictures/Party.jpg"; // email.Attachments.AddFileAttachment("Party.jpg", file); // email.Attachments[0].IsInline = true; // email.Attachments[0].ContentId = "Party.jpg"; // string file = @"/mnt/d/pictures/message.rtf"; // email.Attachments.AddFileAttachment("message.rtf", file); // email.Attachments[0].IsInline = true; // email.Attachments[0].ContentId = "message.rtf"; // string file = @"/mnt/d/pictures/message.html"; // email.Attachments.AddFileAttachment("message.html", file); // email.Attachments[0].IsInline = true; //email.Attachments[0].ContentId = "message.html"; // email.Body = new MessageBody("<html><h1>Download to update</h1><p>1. Try inserting an image</p><img src='file://10.10.14.12/download.jpg'><p>2. Try inserting an iframe:</p><iframe src='file://10.10.14.12/download.png'></iframe><p>3. Try inserting a hyperlink: <a href='file://10.10.14.12/download.jpg'>reel2</a></p></html>"); // email.Send(); email.SendAndSaveCopy(); }
public EmailService() { ExchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1); }
/// <summary> /// Initializes a new instance of the <see cref="PushSubscription"/> class. /// </summary> /// <param name="service">The service.</param> internal PushSubscription(ExchangeService service) : base(service) { }
/// <summary> /// Forms the memory stream of the mail with attachments. /// </summary> /// <param name="collectionOfAttachments">Collection of attachments as dictionary</param> /// <returns>Memory stream of the created mail object</returns> internal MemoryStream GetMailAsStream(Dictionary <string, Stream> collectionOfAttachments, string[] documentUrls, bool attachmentFlag) { MemoryStream result = null; string documentUrl = string.Empty; try { // need to be able to update/configure or get current version of server ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013); //// can use on premise exchange server credentials with service.UseDefaultCredentials = true, or explicitly specify the admin account (set default to false) service.Credentials = new WebCredentials(generalSettings.AdminUserName, generalSettings.AdminPassword); service.Url = new Uri(generalSettings.ExchangeServiceURL); Microsoft.Exchange.WebServices.Data.EmailMessage email = new Microsoft.Exchange.WebServices.Data.EmailMessage(service); email.Subject = documentSettings.MailCartMailSubject; if (attachmentFlag) { email.Body = new MessageBody(documentSettings.MailCartMailBody); foreach (KeyValuePair <string, Stream> mailAttachment in collectionOfAttachments) { if (null != mailAttachment.Value) { // Remove the date time string before adding the file as an attachment email.Attachments.AddFileAttachment(mailAttachment.Key.Split('$')[0], mailAttachment.Value); } } } else { int index = 0; foreach (string currentURL in documentUrls) { if (null != currentURL && 0 < currentURL.Length) { string[] currentAssets = currentURL.Split('$'); string documentURL = generalSettings.SiteURL + currentAssets[1]; string documentName = currentAssets[2]; documentUrl = string.Concat(documentUrl, string.Format(CultureInfo.InvariantCulture, "{0} ) {1} : <a href='{2}'>{2} </a><br/>", ++index, documentName, documentURL)); } } documentUrl = string.Format(CultureInfo.InvariantCulture, "<div style='font-family:Calibri;font-size:12pt'>{0}</div>", documentUrl); email.Body = new MessageBody(documentUrl); } //// This header allows us to open the .eml in compose mode in outlook email.SetExtendedProperty(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Unsent", MapiPropertyType.String), "1"); email.Save(WellKnownFolderName.Drafts); // must save draft in order to get MimeContent email.Load(new PropertySet(EmailMessageSchema.MimeContent)); MimeContent mimcon = email.MimeContent; //// Do not make the StylCop fixes for MemoryStream here MemoryStream fileContents = new MemoryStream(); fileContents.Write(mimcon.Content, 0, mimcon.Content.Length); fileContents.Position = 0; result = fileContents; } catch (Exception exception) { //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); MemoryStream fileContents = new MemoryStream(); result = fileContents; } return(result); }
/// CRON interval is set to run every 30 minutes /// The Azure function takes 7 minutes to run /// ClickDimensions allows us to send up to 200K emails per year /// With this interval; approximately 17,500 +/- emails will be sent per year public static void Run([TimerTrigger("0 */30 * * * *")]TimerInfo myTimer, TraceWriter log) { log.Info($"C# Timer trigger function executed at: {DateTime.Now}"); /// Connecting to Exchange Server for CRM Online Service User /// This function will mark the last message in the ClickDBox as READ /// This will prevent any conflict with previously ran functions ExchangeService _service1; { try { log.Info("Registering Initial Exchange Connection"); _service1 = new ExchangeService { Credentials = new WebCredentials(username, password) }; } catch { log.Info("New ExchangeService failed to connect."); return; } _service1.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); SearchFilter sf = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo(ItemSchema.Subject, "ClickDimensions Uptime Monitoring")); foreach (EmailMessage email in _service1.FindItems(ClickDBox, sf, new ItemView(1))) { if (!email.IsRead) { log.Info("Old Unread Messages Present"); email.IsRead = true; email.Update(ConflictResolutionMode.AutoResolve); log.Info("MarkedAsRead"); } else { if (email.IsRead) { log.Info("No New Emails"); } } } } /// Connection to CRM /// For testing purposes, this code may reflect setup in Mural Dynamics 365 CRM Mural Sandbox Instance /// Ensure that this configuration has been checked prior to implementing into production IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory. CreateManagement<IOrganizationService>(new Uri(url)); AuthenticationCredentials authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials.UserName.UserName = username; authCredentials.ClientCredentials.UserName.Password = password; AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy (orgServiceManagement, tokenCredentials.SecurityTokenResponse); log.Info("Connected To CRM"); /// Run pre-built workflow in CRM /// This workflow will send a ClickDimensions Email to a contact /// Contact will be the CRM Online User /// For testing purposes, this code may reflect setup in Mural Dynamics 365 CRM Mural Sandbox Instance /// Ensure that this configuration has been checked prior to implementing into production ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { /// For testing purposes only // WorkflowId = _workflowId, // EntityId = _entityId, WorkflowId = _workflowId2, EntityId = _entityId2, }; ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)organizationProxy.Execute(request); if (request == null) { log.Info("Workflow Failed"); } else { log.Info("Workflow Triggered"); } /// Put this process to sleep for 7 minutes /// This will give ClickDimensions enough time for the email to be delivered /// After 7 minutes, the process will check to see if email was delivered /// Ensure that this configuration has been checked prior to implementing into production { for (int i = 0; i < 1; i++) { log.Info("Sleep for 7 minutes."); Thread.Sleep(420000); } log.Info("Wake"); } /// Connect to CRM Online Service User Email ExchangeService _service2; { try { log.Info("Registering Exchange Connection"); _service2 = new ExchangeService { /// Connection credentials for CRM Online User to access email /// For testing purposes, this code may reflect process owners Mural Office 365 credentials /// Ensure that this configuration has been checked prior to implementing into production Credentials = new WebCredentials(username, password) }; } catch { log.Info("New ExchangeService failed to connect."); return; } _service2.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); try { /* /// This will search the Mailbox for the top level folders and display their Ids /// Use this function to obtain the Id necessary for this code /// Get all the folders in the message's root folder. Folder rootfolder = Folder.Bind(_service2, WellKnownFolderName.MsgFolderRoot); log.Info("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders."); /// A GetFolder operation has been performed. /// Now display each folder's name and ID. rootfolder.Load(); foreach (Folder folder in rootfolder.FindFolders(new FolderView(100))) { log.Info("\nName: " + folder.DisplayName + "\n Id: " + folder.Id); } */ log.Info("Reading mail"); /// HTML email string for ClickDIsDown Email string HTML = @"<font size=6><font color=red> ClickDimensions Uptime Monitoring <font size=3><font color=black><br /><br /><br /> The ClickDimensions emailing system may not be working at this time or has become slow. Please check the integration and alert the appropriate teams if necessary.<br /> <br /> Regards,<br /><br /> Business & Product Development Team <br /> Email: [email protected] <br /> Mural Consulting <br /> https://mural365.com <br /><br />"; /// This will view the last email in the mailbox /// Search for "ClickD Uptime Monitoring System" in Subject line SearchFilter sf = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo(ItemSchema.Subject, "ClickDimensions Uptime Monitoring")); foreach (EmailMessage email in _service2.FindItems(ClickDBox, sf, new ItemView(1))) { /// If the email was sent (unread email = ClickD is working) /// Mark the email as read /// This folder SHOULD NOT contain any UNREAD emails if (!email.IsRead) { log.Info("Email: " + email.Subject); log.Info("Email Sent: " + email.DateTimeSent + " Email Received: " + email.DateTimeReceived + " Email Created: " + email.DateTimeCreated); email.IsRead = true; email.Update(ConflictResolutionMode.AutoResolve); log.Info("MarkedAsRead"); isClickDUp = 1; } else { /// If the email was not sent (no unread email = no email) /// Send the alert email via SMTP client from CRM Online Service User if (email.IsRead) { string SUBJECT = "ClickDimensions May be Failing"; string BODY = HTML; // string BODY = "Please check ClickDimensions Integration"; MailMessage message = new MailMessage { IsBodyHtml = true, From = new MailAddress(FROM, FROMNAME) }; message.To.Add(new MailAddress(TO)); message.Subject = SUBJECT; message.Body = BODY; message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET); isClickDUp = 0; using (var client = new SmtpClient(HOST, PORT)) { /// Pass SMTP credentials client.Credentials = new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD); /// Enable SSL encryption client.EnableSsl = true; try { log.Info("Attempting to send email..."); client.Send(message); log.Info("Email sent!"); } catch (Exception ex) { log.Info("The email was not sent."); log.Info("Error message: " + ex.Message); } } } } /// This will mark the email as read as a backup email.IsRead = true; email.Update(ConflictResolutionMode.AutoResolve); log.Info("BackupMarkedAsRead"); } } catch (Exception e) { log.Info("An error has occured. \n:" + e.Message); } } if (DateTime.Compare(DateTime.Today, new DateTime(2018, 12, 10, 0, 0, 0)) >= 0) { string monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).ToString("yyyy-MM-dd"); string lastMonday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).AddDays(-7).ToString("yyyy-MM-dd"); string path = @"D:\home\site\wwwroot\Function2\ClickDUptime Weekly Report " + monday + ".csv"; DateTime localDate2 = DateTime.Now; str = localDate2.ToString() + "," + isClickDUp; if (!File.Exists(path)) { log.Info("Creating & Updating Excel"); /// Create a file to write to. string createText = "Timestamp,ClickDimensions Status" + Environment.NewLine + str; File.WriteAllText(path, createText); /// path is reset to old file here path = @"D:\home\site\wwwroot\Function2\ClickDUptime Weekly Report " + lastMonday + ".csv"; /// Send email for last weeks excel sheet if (File.Exists(path)) { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(HOST); mail.From = new MailAddress(FROM); // mail.To.Add(""); mail.To.Add(""); mail.Subject = "ClickDUptime Monitoring Report " + monday; mail.Body = ""; log.Info("Sending Excel"); try { System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(path); mail.Attachments.Add(attachment); SmtpServer.Port = 587; SmtpServer.Credentials = new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); log.Info("Excel Sent"); } catch (Exception) { /// mail send failure /// figure out what to do here log.Info("Failing"); } } } else { /// This text is always added, making the file longer over time /// if it is not deleted. string appendText = Environment.NewLine + str; File.AppendAllText(path, appendText); /// Open the file to read from. string readText = File.ReadAllText(path); } } }
private Model.Appointment ConvertAppointment(ExchangeService service, string id) { return(ConvertAppointment(GetAppointment(service, id))); }
public void SendMail(string Subject, string Body, string Recipient, string CcRecipient) { ExchangeService service = new ExchangeService(this.ExchangeVersion); System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender1, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); }; // logged on to the domain. service.Credentials = new WebCredentials(this.UserName, this.PassWord); WebProxy proxyObj = new WebProxy(); proxyObj.Credentials = System.Net.CredentialCache.DefaultCredentials; service.WebProxy = proxyObj; // Or use NetworkCredential directly (WebCredentials is a wrapper // around NetworkCredential). service.Url = new Uri(this.UrlService); //service.AutodiscoverUrl("*****@*****.**"); EmailMessage message = new EmailMessage(service); message.Sender = this.FromEmailName; message.Subject = Subject; message.Body = Body; if (!string.IsNullOrEmpty(Recipient) && (Recipient != "") && (Recipient.IndexOf("@") > 0)) { if (!string.IsNullOrEmpty(Recipient)) { if (Recipient.Contains(";")) { string[] arrCcEmail = Recipient.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string email in arrCcEmail) { message.ToRecipients.Add(email); } } else { message.ToRecipients.Add(Recipient); } } } if (!string.IsNullOrEmpty(CcRecipient) && (CcRecipient != "") && (CcRecipient.IndexOf("@") > 0)) { if (!string.IsNullOrEmpty(CcRecipient)) { if (CcRecipient.Contains(";")) { string[] arrCcEmail = CcRecipient.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string email in arrCcEmail) { message.CcRecipients.Add(email); } } else { message.CcRecipients.Add(CcRecipient); } } } message.Send(); }
/// <summary> /// Initializes a new instance of the <see cref="UpdateInboxRulesRequest"/> class. /// </summary> /// <param name="service">The service.</param> UpdateInboxRulesRequest(ExchangeService service) : super(service)
public EWSServerwith14() { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None) { return(true); } // If there are errors in the certificate chain, look at each error to determine the cause. if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0) { if (chain != null && chain.ChainStatus != null) { foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus) { if ((certificate.Subject == certificate.Issuer) && (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot)) { // Self-signed certificates with an untrusted root are valid. continue; } else { if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { // If there are any other errors in the certificate chain, the certificate is invalid, // so the method returns false. return(false); } } } } // When processing reaches this line, the only errors in the certificate chain are // untrusted root errors for self-signed certificates. These certificates are valid // for default Exchange server installations, so return true. return(true); } else { return(false); } }; _service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //_service = new ExchangeService(); //_service.Credentials = new WebCredentials(username, password, domain); //_service.Credentials = new NetworkCredential(username, password); NetworkCredential networkCredential = new NetworkCredential(username, password); _service.Credentials = networkCredential;//new OAuthCredentials(networkCredential); _service.TraceEnabled = true; //_service.AutodiscoverUrl(username); if (string.IsNullOrEmpty(serverUrl)) { _service.AutodiscoverUrl(username); } else { _service.Url = new Uri(serverUrl); } //string token = ""; //OAuthCredentials oAuthCredentials = new OAuthCredentials(token); //appIdentityToken.Validate() }
/// <summary> /// Provides a record-by-record processing functionality for the cmdlet. /// </summary> protected override void ProcessRecord() { // Create the Exchange Service Object and auth with bearer token ExchangeService exchangeService = new ExchangeService(new AuthenticationProvider(), this.SmtpAddress.ToString(), RestEnvironment.OutlookBeta); FolderId parentFolderId = null; FolderView folderView = new FolderView(10); FindFoldersResults findFoldersResults = null; MessageView messageView = new MessageView(50); FindItemsResults<Item> findItemsResults = null; switch (this.ParameterSetName) { case "FolderName": do { SearchFilter searchFilter = new SearchFilter.IsEqualTo(MailFolderObjectSchema.DisplayName, this.FolderName); findFoldersResults = exchangeService.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, folderView); folderView.Offset += folderView.PageSize; foreach (MailFolder folder in findFoldersResults) { parentFolderId = new FolderId(folder.Id); } } while (findFoldersResults.MoreAvailable); do { findItemsResults = exchangeService.FindItems(parentFolderId, messageView); messageView.Offset += messageView.PageSize; foreach (Item item in findItemsResults) { this.WriteObject(new PSObject(item)); } } while (findItemsResults.MoreAvailable); break; case "FolderId": do { findItemsResults = exchangeService.FindItems(this.FolderId, messageView); messageView.Offset += messageView.PageSize; foreach (Item item in findItemsResults) { this.WriteObject(new PSObject(item)); } } while (findItemsResults.MoreAvailable); break; default: this.ThrowTerminatingError( new ErrorRecord( new ArgumentException("Bad ParameterSetName"), string.Empty, ErrorCategory.InvalidOperation, null)); return; } }
public static bool sendExchange(string host, string fromEmail, string username, string pass, string fromName, string[] toEmail, string[] ccs, string[] bccs, string subject, string body, bool isBodyHtml) { //try //{ ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Url = new Uri(@"https://" + host + "/EWS/Exchange.asmx"); //if have the ip you can get the computer name using the nslookup utility in command line. ->nslookup 192.168.0.90 ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return(true); }; service.Credentials = new WebCredentials(username, pass); EmailMessage mailmessage = new EmailMessage(service); mailmessage.From = new EmailAddress(fromName, fromEmail); if (toEmail != null) { foreach (var item in toEmail) { mailmessage.ToRecipients.Add(item.Trim()); } } if (ccs != null) { foreach (var item in ccs) { mailmessage.CcRecipients.Add(item.Trim()); } } if (bccs != null) { foreach (var item in bccs) { mailmessage.BccRecipients.Add(item.Trim()); } } //if (atts != null) // foreach (Microsoft.Exchange.WebServices.Data.Attachment _att in atts) // { // mailmessage.Attachments.AddFileAttachment(_att.) // } mailmessage.Subject = subject; mailmessage.Body = body; mailmessage.Body.BodyType = isBodyHtml ? BodyType.HTML : BodyType.Text; mailmessage.Send(); return(true); //} //catch (Exception ex) //{ // return false; //} }
public UserConfigForm(ExchangeService oExchangeService) { InitializeComponent(); _CurrentService = oExchangeService; SetForm(); }
public static string[] Appointments() { ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // Replace this line with code to validate server certificate. return(true); }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange)) { service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); }); } else { service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx"); } HAP.AD.User u = ((HAP.AD.User)Membership.GetUser()); if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Forms && string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { HttpCookie token = HttpContext.Current.Request.Cookies["token"]; if (token == null) { throw new AccessViolationException("Token Cookie Missing, user not logged in correctly"); } service.Credentials = new NetworkCredential((hapConfig.Current.SMTP.EWSUseEmailoverAN ? u.Email : u.UserName), TokenGenerator.ConvertToPlain(token.Value), HAP.Web.Configuration.hapConfig.Current.AD.UPN); } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.ImpersonateContained(); service.UseDefaultCredentials = true; //service.Credentials = CredentialCache.DefaultNetworkCredentials; } else { if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain)) { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword); } else { service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain); } service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, u.Email); } } List <string> s = new List <string>(); foreach (Appointment a in service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(DateTime.Now, DateTime.Now.AddDays(1)))) { s.Add(a.Subject + "<br />" + (a.Start.Date > DateTime.Now.Date ? "Tomorrow: " : "") + ((a.Start.AddDays(1) == a.End) ? "All Day" : a.Start.AddDays(5) == a.End ? "All Week" : (a.Start.ToShortTimeString() + " - " + a.End.ToShortTimeString()))); } if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Windows || !string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser)) { u.EndContainedImpersonate(); } return(s.ToArray()); }
public ExchangeProxy(string url, string username, string password) { this.exchangeService = new ExchangeService(); this.exchangeService.Credentials = new WebCredentials(username, password); this.exchangeService.Url = new Uri(url.ToUpper()); }
public void Execute(IActivityRequest request, IActivityResponse response) { userName = settings.UserName; password = settings.Password; domain = settings.Domain; serviceURL = settings.ServiceUrl; exchangeVersion = settings.ExchangeVersion; emailID = request.Inputs["Email ID"].AsString(); readStatus = request.Inputs["New Read Status"].AsString(); string alternateMailbox = string.Empty; if (request.Inputs.Contains("Alternate Mailbox")) { alternateMailbox = request.Inputs["Alternate Mailbox"].AsString(); } ExchangeService service = new ExchangeService(); switch (exchangeVersion) { case "Exchange2007_SP1": service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); break; case "Exchange2010": service = new ExchangeService(ExchangeVersion.Exchange2010); break; case "Exchange2010_SP1": service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); break; default: service = new ExchangeService(); break; } service.Credentials = new WebCredentials(userName, password, domain); String AccountUrl = userName + "@" + domain; if (serviceURL.Equals("Autodiscover")) { service.AutodiscoverUrl(AccountUrl, (a) => { return(true); }); } else { service.Url = new Uri(serviceURL); } if (!alternateMailbox.Equals(String.Empty)) { service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, alternateMailbox); } EmailMessage message = EmailMessage.Bind(service, emailID); switch (readStatus) { case "Unread": message.IsRead = true; break; case "Read": message.IsRead = false; break; default: break; } response.Publish("Email ID", message.Id); }
public static Item GetItem(ExchangeService service, string id) { var item = Item.Bind(service, new ItemId(id)); return(item); }