static void Main(string[] args) { //gather settings from the host process config file string tenantName = ConfigurationManager.AppSettings["TenantName"]; string tenantUpnDomain = ConfigurationManager.AppSettings["TenantUpnDomain"]; Uri tenantAdminUri = new Uri(string.Format("https://{0}-admin.sharepoint.com", tenantName)); //get the ream and app-only access token string adminRealm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var adminToken = TokenHelper.GetAppOnlyAccessToken (TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, adminRealm).AccessToken; //we use the app-only access token to authenticate without the interaction of the user using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), adminToken)) { //load the tenant object var tenant = new Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //call the extension method to get all site collections IList <SiteEntity> siteCollections = tenant.GetSiteCollections(); //at this stage you could build aby report, like an Excel file with OpenXML //in this demo we generate a simple email EmailProperties emailProperties = GenerateEmailReport(siteCollections); //use the OffideDev PnP utilities to send out the email Utility.SendEmail(clientContext, emailProperties); clientContext.ExecuteQuery(); } }
static void Main(string[] args) { ClientContext clientContext = new ClientContext(ConfigurationManager.AppSettings["siteUrl"].ToString()); clientContext.AuthenticationMode = ClientAuthenticationMode.Default; string password = ConfigurationManager.AppSettings["userPassword"].ToString(); System.Security.SecureString passwordChar = new System.Security.SecureString(); foreach (char ch in password) { passwordChar.AppendChar(ch); } clientContext.Credentials = new SharePointOnlineCredentials(ConfigurationManager.AppSettings["userEmail"].ToString(), passwordChar); var emailp = new EmailProperties(); emailp.To = new List <string> { "*****@*****.**" }; emailp.Body = "Yunus Emre Araç test email"; emailp.Subject = "Yunus Emre Araç sitesi için deneme mail gönderimidir."; Utility.SendEmail(clientContext, emailp); clientContext.ExecuteQuery(); }
public void Send(EmailProperties email) { var from = string.IsNullOrWhiteSpace(email.From) ? _configuration.GetSection("MailService:EmailFrom").Value : email.From; var fromDisplayName = string.IsNullOrWhiteSpace(email.FromDisplayName) ? _configuration.GetSection("MailService:EmailFromDisplayName").Value : email.FromDisplayName; var password = string.IsNullOrWhiteSpace(email.Password) ? _configuration.GetSection("MailService:EmailPassword").Value : email.Password; MailMessage mailMsg = new MailMessage { From = new MailAddress(from, fromDisplayName), IsBodyHtml = true, Subject = email.Subject, Body = email.Body, }; // Init SmtpClient and send var smtpClient = new SmtpClient { Host = _configuration.GetSection("MailService:EmailHost").Value, Port = int.Parse(_configuration.GetSection("MailService:EmailPort").Value), UseDefaultCredentials = false, Credentials = new NetworkCredential(_configuration.GetSection("MailService:EmailFrom").Value, password), EnableSsl = true, }; foreach (var address in email.To.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { mailMsg.To.Clear(); mailMsg.To.Add(new MailAddress(address)); smtpClient.Send(mailMsg); } }
private void EnforceTwoAdministratorsTimerJob_TimerJobRun(object sender, TimerJobRunEventArgs e) { Console.WriteLine("Starting job"); var web = e.SiteClientContext.Web; var siteUsers = e.SiteClientContext.LoadQuery(web.SiteUsers.Include(u => u.Email).Where(u => u.IsSiteAdmin)); e.SiteClientContext.ExecuteQueryRetry(); if (siteUsers.Count() < 2) { Console.WriteLine("Site found"); if (!web.IsPropertyAvailable("Url")) { e.SiteClientContext.Load(web, w => w.Url); e.SiteClientContext.ExecuteQueryRetry(); } var adminUser = siteUsers.FirstOrDefault(); EmailProperties mailProps = new EmailProperties(); mailProps.Subject = "Action required: assign an additional site administrator to your site"; StringBuilder bodyBuilder = new StringBuilder(); bodyBuilder.Append("<html><body style=\"font-family:sans-serif\">"); bodyBuilder.AppendFormat("<p>Your site with address <a href=\"{0}\">{0}</a> has only one site administrator defined: you. Please assign an additional site administrator.</p>", e.SiteClientContext.Web.Url); bodyBuilder.AppendFormat("<p>Click here to <a href=\"{0}/_layouts/mngsiteadmin.aspx\">assign an additional site collection adminstrator.</a></p>", e.SiteClientContext.Web.Url); bodyBuilder.Append("</body></html>"); mailProps.Body = bodyBuilder.ToString(); mailProps.To = new[] { adminUser.Email }; Utility.SendEmail(e.SiteClientContext, mailProps); e.SiteClientContext.ExecuteQueryRetry(); } Console.WriteLine("Ending job"); }
public async Task SendEmail(EmailProperties pemailProperties) { try { //Propiedades del mensaje var message = new EmailMessage { Subject = pemailProperties.subject, Body = pemailProperties.body, To = pemailProperties.to, }; var fn = pemailProperties.attachment; var file = Path.Combine(FileSystem.CacheDirectory, fn); message.Attachments.Add(new EmailAttachment(file)); //API que se encarga de abrir el cliente como el Gmail, Outlook u otros para realizar el envío del mensaje await Email.ComposeAsync(message); } catch (FeatureNotSupportedException fnsEx) { // Email is not supported on this device await DisplayAlert("Error", fnsEx.ToString(), "OK"); } catch (Exception ex) { // Some other exception occurred await DisplayAlert("Error", ex.ToString(), "OK"); } }
/// <summary> /// This method builds an email with a table of all site collection data /// You can replace it with anything that suits your needs /// </summary> /// <param name="siteCollections">A list of site collections to report on</param> /// <returns>An email properties object</returns> static private EmailProperties GenerateEmailReport(IList<SiteEntity> siteCollections) { //configure the email properties EmailProperties emailProperties = new EmailProperties(); emailProperties.To = new List<string> { ConfigurationManager.AppSettings["TargetEmail"] }; emailProperties.Subject = "Periodic Site Usage Report " + DateTime.Now.ToShortDateString(); //build the body StringBuilder mailBody = new StringBuilder(); mailBody.Append("<html><body>"); mailBody.AppendLine("<p>Site collections:</p>"); mailBody.AppendLine("<table style='border:1px solid black'>"); mailBody.AppendLine("<tr><th>Site Collection Url</th><th>Storage Quota</th><th>Storage Used</th><th>Last Content Modification Date</th><th>Web Count</th></tr>"); //gather data for each site collection foreach (SiteEntity item in siteCollections) { mailBody.AppendLine( string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", new object[] { item.Url, item.StorageMaximumLevel, item.StorageUsage, item.LastContentModifiedDate, item.WebsCount })); } mailBody.AppendLine("</table>"); mailBody.AppendLine("</body></html>"); emailProperties.Body = mailBody.ToString(); return emailProperties; }
public async Task SendEmailAsync(string idEvent, string html) { ReadEmailTemplate(html); using (ClientContext clientContext = _sharepointContextProvider.GetSharepointContextFromUrl(APIResource.SHAREPOINT_CONTEXT + "/sites/FOS/")) { await GetDataByEventIdAsync(clientContext, idEvent); var emailp = new EmailProperties(); string hostname = WebConfigurationManager.AppSettings[OAuth.HOME_URI]; foreach (var user in emailTemplate.UsersEmail) { emailp.To = new List <string>() { user.mail }; emailp.From = emailTemplate.HostUserEmail.mail; emailp.BCC = new List <string> { emailTemplate.HostUserEmail.mail }; emailp.Body = String.Format(emailTemplate.Html.ToString(), emailTemplate.EventTitle.ToString(), emailTemplate.EventRestaurant.ToString(), user.mail.ToString(), hostname + "make-order/1"); emailp.Subject = emailTemplate.Subject; Utility.SendEmail(clientContext, emailp); clientContext.ExecuteQuery(); } } }
private void EnforceTwoAdministratorsTimerJob_TimerJobRun(object sender, TimerJobRunEventArgs e) { Console.WriteLine("Starting job"); var web = e.SiteClientContext.Web; var siteUsers = e.SiteClientContext.LoadQuery(web.SiteUsers.Include(u => u.Email).Where(u => u.IsSiteAdmin)); e.SiteClientContext.ExecuteQueryRetry(); if (siteUsers.Count() < 2) { Console.WriteLine("Site found"); if (!web.IsPropertyAvailable("Url")) { e.SiteClientContext.Load(web, w => w.Url); e.SiteClientContext.ExecuteQueryRetry(); } var adminUser = siteUsers.FirstOrDefault(); EmailProperties mailProps = new EmailProperties(); mailProps.Subject = "Action required: assign an additional site administrator to your site"; StringBuilder bodyBuilder = new StringBuilder(); bodyBuilder.Append("<html><body style=\"font-family:sans-serif\">"); bodyBuilder.AppendFormat("<p>Your site with address <a href=\"{0}\">{0}</a> has only one site administrator defined: you. Please assign an additional site administrator.</p>", e.SiteClientContext.Web.Url); bodyBuilder.AppendFormat("<p>Click here to <a href=\"{0}/_layouts/mngsiteadmin.aspx\">assign an additional site collection adminstrator.</a></p>", e.SiteClientContext.Web.Url); bodyBuilder.Append("</body></html>"); mailProps.Body = bodyBuilder.ToString(); mailProps.To = new[] { adminUser.Email }; Utility.SendEmail(e.SiteClientContext, mailProps); e.SiteClientContext.ExecuteQueryRetry(); } Console.WriteLine("Ending job"); }
public static void SendMail(string email, string name, string site, string username, SecureString password) { string emailMessage; var siteDomain = ConfigurationManager.AppSettings["siteDomain"]; string targetSite = siteDomain + site; emailMessage = "<table border='0' cellspacing='0' cellpadding='0'><tbody>" + "<tr><td style= 'padding:12px 0 14px 0;font-family:Segoe UI,Arial,sans-serif;font-size:16px;color:#3D3D3D' ><span style='font-size:16px;'>Dear " + name + ",</td></tr>" + "<tr><td style= 'padding:12px 0 18px 0;font-family:Segoe UI,Arial,sans-serif;font-size:16px;color:#3D3D3D'><span style='font-size:16px;' > Welcome to the Sharepoint site, your access has now been granted.</span></td></tr>" + "<tr><td style = 'padding:6px 0 48px 0;font-family:Segoe UI,Arial,sans-serif';color:'#3D3D3D'><span style='font-size:32px;'>Go To <a href = \"" + targetSite + "\" target =\"_blank\"><span style='color:darkorange;text-decoration-color:darkorange;text-decoration:underline; '> SharePoint Site </span></a></span></td></tr>" + "</tbody></table>"; var emailp = new EmailProperties(); emailp.To = new List <string> { email }; emailp.CC = new List <string> { "*****@*****.**" }; emailp.From = "*****@*****.**"; emailp.Body = emailMessage; emailp.Subject = "Access Granted"; using (var ctx = new ClientContext(siteDomain + site)) { ctx.Credentials = new SharePointOnlineCredentials(username, password); var web = ctx.Web; Utility.SendEmail(ctx, emailp); ctx.ExecuteQuery(); } }
public static void SendEmail(string webUrl, FieldUserValue[] users, string Subject, int index, FieldUserValue[] userReceived, ListItem item) { using (ClientContext ctx = SPConnection.GetSPOLContext(webUrl)) { foreach (FieldUserValue user in users) { bool notcontain = true; if (userReceived != null) { foreach (FieldUserValue recuser in userReceived) { if (user.Email == recuser.Email) { notcontain = false; } } } if (notcontain) { List <string> usersEmail = new List <string> { }; usersEmail.Add(user.Email.ToString()); string body = ""; if (index == 4) { body = EmailBody(index, item, user.Email.ToString(), users); } else { body = EmailBody(index, item, user.Email.ToString()); } try { ///jke risk of dispose // using (ctx) { var emailProperties = new EmailProperties(); //Email of authenticated external user emailProperties.To = usersEmail; emailProperties.From = "*****@*****.**"; emailProperties.Body = body; emailProperties.Subject = Subject; //emailProperties.CC = cc; Utility.SendEmail(ctx, emailProperties); ctx.ExecuteQuery(); } } catch (Exception ex) { } } } } }
public async Task <bool> SendEmailAsync(EmailProperties emailProperties) { //const string configset = "ConfigSet"; var status = false; const string awsAccessKey = "AKIAJ4IK5ITYGVQ6NICA"; const string awsAccessSecretKey = "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"; using (var awsClient = new AmazonSimpleEmailServiceClient(awsAccessKey, awsAccessSecretKey, RegionEndpoint.USEast1)) { var request = new SendEmailRequest { Source = _emailSettings.SmtpEmail, Destination = new Destination() { ToAddresses = emailProperties.ReceipentsEmail }, Message = new Message() { Subject = new Content(emailProperties.Subject), Body = new Body() { Html = new Content { Charset = "UTF-8", Data = "This message body contains HTML formatting. It can, for example, contain links like this one: <a href ='http://docs.aws.amazon.com/ses/latest/DeveloperGuide\' target = '\'_blank\"> Amazon SES Developer Guide </a>." }, Text = new Content() { Charset = "UTF-8", Data = emailProperties.Body } } } }; var templatedEmailRequest = new SendTemplatedEmailRequest { Source = _emailSettings.SmtpEmail, Destination = new Destination() { ToAddresses = emailProperties.ReceipentsEmail }, Template = "withButtonTemplate", TemplateData = "{\"subject\":\"" + emailProperties.Subject + "\"}" }; var response = await awsClient.SendEmailAsync(request); if (response.HttpStatusCode == HttpStatusCode.OK) { status = true; } } return(status); }
public void Execute() { EmailProperties properties = new EmailProperties(); properties.To = new string[] { EmailTo }; properties.Body = Text; Utility.SendEmail(context, properties); context.ExecuteQuery(); }
/// <summary> /// Handles events that occur before an action occurs, such as when a user adds or deletes a list item. /// </summary> /// <param name="properties">Holds information about the remote event.</param> /// <returns>Holds information returned from the remote event.</returns> public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); ClientContext clientContext = null; try { clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties); } catch (Exception ex) { // TODO : Log } if (clientContext == null) { string siteUrl = properties.ItemEventProperties.WebUrl; string acsAppId = ConfigurationManager.AppSettings["ClientId"]; string acsSupport = ConfigurationManager.AppSettings["ClientSecret"]; AuthenticationManager authManager = new AuthenticationManager(); clientContext = authManager.GetAppOnlyAuthenticatedContext(siteUrl, acsAppId, acsSupport); } if (clientContext == null) { result.Status = SPRemoteEventServiceStatus.CancelNoError; return(result); } using (clientContext) { clientContext.Load(clientContext.Web); var currentUser = clientContext.Web.CurrentUser; clientContext.Load(currentUser); clientContext.ExecuteQuery(); string title = properties.ItemEventProperties.AfterProperties["Title"].ToString(); var emailp = new EmailProperties(); emailp.To = new List <string> { currentUser.Email, "*****@*****.**" }; emailp.From = "*****@*****.**"; emailp.Body = "<b>html here...</b>"; emailp.Subject = "subject: " + title; //Utility.SendEmail(clientContext, emailp); //clientContext.ExecuteQuery(); } return(result); }
private async Task <string> GetEmailBody(string content, EmailProperties emailProperties) { // Deserialize the content into an EmailPage object EmailPage emailPage = JsonSerializer.Deserialize <EmailPage>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); // Create the body string body = await emailPage.CreateBody(context); return(emailProperties.Set(body)); }
/// <summary> /// Sends an email using the SharePoint SendEmail method /// </summary> /// <param name="context">Context for SharePoint objects and operations</param> /// <param name="to">List of TO addresses.</param> /// <param name="cc">List of CC addresses.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">HTML body of the mail.</param> public static void SendEmail(ClientContext context, IEnumerable <String> to, IEnumerable <String> cc, string subject, string body) { EmailProperties properties = new EmailProperties(); properties.To = to; if (cc != null) { properties.CC = cc; } properties.Subject = subject; properties.Body = body; Microsoft.SharePoint.Client.Utilities.Utility.SendEmail(context, properties); context.ExecuteQueryRetry(); }
public async Task <IActionResult> AddNewJob([FromBody] SaveJobResource jobResource) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!_emailServiceClient.IsValidEmail(jobResource.GeneralContractorEmail) || !_emailServiceClient.IsValidEmail(jobResource.HomeOwnerEmail)) { return(BadRequest("Invalid Email")); } var prop = new EmailProperties { Subject = "Add New Job", Body = "We are testing sending email from AWS", EmailHeading = "This will be heading", HasButton = false, ReceipentsEmail = new List <string>() { jobResource.GeneralContractorEmail, jobResource.HomeOwnerEmail } }; var jobs = _mapper.Map <SaveJobResource, Jobs>(jobResource); jobs.UserId = await GetUserId(); _jobRepository.SaveJob(jobs); await _unitOfWork.CompleteAsync(); return(Ok(_mapper.Map <Jobs, JobResource>(jobs))); } catch (Exception ex) { return(BadRequest(ex.ToString())); } }
public void Send(EmailProperties email) { var mail = new MailMessage { Subject = email.Subject, Body = email.Body, IsBodyHtml = true, BodyEncoding = Encoding.UTF8, From = new MailAddress(email.From, email.DisplayName) }; foreach (var to in email.To.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { mail.To.Add(to); } foreach (var bcc in email.Bcc) { mail.Bcc.Add(bcc); } foreach (var attachment in email.Attachments) { mail.Attachments.Add(new Attachment(new MemoryStream(attachment.Item2), attachment.Item1)); } var smtpClient = new SmtpClient { Host = email.Host, Port = email.Port, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(email.From, email.Password), EnableSsl = true }; Task.Run(() => smtpClient.Send(mail)); }
/// <summary> /// This method builds an email with a table of all site collection data /// You can replace it with anything that suits your needs /// </summary> /// <param name="siteCollections">A list of site collections to report on</param> /// <returns>An email properties object</returns> static private EmailProperties GenerateEmailReport(IList <SiteEntity> siteCollections) { //configure the email properties EmailProperties emailProperties = new EmailProperties(); emailProperties.To = new List <string> { ConfigurationManager.AppSettings["TargetEmail"] }; emailProperties.Subject = "Periodic Site Usage Report " + DateTime.Now.ToShortDateString(); //build the body StringBuilder mailBody = new StringBuilder(); mailBody.Append("<html><body>"); mailBody.AppendLine("<p>Site collections:</p>"); mailBody.AppendLine("<table style='border:1px solid black'>"); mailBody.AppendLine("<tr><th>Site Collection Url</th><th>Storage Quota</th><th>Storage Used</th><th>Last Content Modification Date</th><th>Web Count</th></tr>"); //gather data for each site collection foreach (SiteEntity item in siteCollections) { mailBody.AppendLine( string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", new object[] { item.Url, item.StorageMaximumLevel, item.StorageUsage, item.LastContentModifiedDate, item.WebsCount })); } mailBody.AppendLine("</table>"); mailBody.AppendLine("</body></html>"); emailProperties.Body = mailBody.ToString(); return(emailProperties); }
public static void DocownerRejected( [ActivityTrigger] ApprovalStartInfo approvalStartInfo, TraceWriter log, ExecutionContext context ) { using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"])) { var emailp = new EmailProperties(); emailp.BCC = new List <string> { approvalStartInfo.startedByEmail }; emailp.To = new List <string> { approvalStartInfo.startedByEmail }; emailp.From = "*****@*****.**"; emailp.Body = "<b>rejected</b>"; emailp.Subject = "rejected"; Utility.SendEmail(cc, emailp); cc.ExecuteQuery(); }; }
static public void SendEmail(String path, String test, String result) { string ServiceSiteUrl = ConfigurationManager.AppSettings["sharepointOnline"]; string ServiceUserName = ConfigurationManager.AppSettings["SPOUsername"]; //decrypt password string base64Encoded = ConfigurationManager.AppSettings["SPOPassword"]; string ServicePassword; byte[] data = System.Convert.FromBase64String(base64Encoded); ServicePassword = System.Text.ASCIIEncoding.ASCII.GetString(data); var securePassword = new SecureString(); foreach (char c in ServicePassword) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(ServiceUserName, securePassword); var context = new ClientContext(ServiceSiteUrl); context.Credentials = onlineCredentials; context.ExecuteQuery(); List <string> mailRecipients = ConfigurationManager.AppSettings["mailRecipients"].Split(';').ToList(); var emailp = new EmailProperties(); emailp.To = mailRecipients; emailp.From = ConfigurationManager.AppSettings["SPOUsername"]; emailp.Body = "Something went wrong with Cookie Checker Results in test " + test + ". Click <a href=\"" + path + "\">here</a> to check. Problem: " + result; emailp.Subject = "Cookie Checker Results problem!"; Utility.SendEmail(context, emailp); context.ExecuteQuery(); }
private void ValidateExternalUsersTimerJob_TimerJobRun(object sender, TimerJobRunEventArgs e) { Console.WriteLine("Starting job"); var web = e.SiteClientContext.Web; Tenant tenant = new Tenant(e.TenantClientContext); var siteAdmins = e.SiteClientContext.LoadQuery(web.SiteUsers.Include(u => u.Email).Where(u => u.IsSiteAdmin)); e.SiteClientContext.ExecuteQueryRetry(); List <string> adminEmails = new List <string>(); foreach (var siteAdmin in siteAdmins) { adminEmails.Add(siteAdmin.Email); } SiteProperties p = tenant.GetSitePropertiesByUrl(e.SiteClientContext.Url, true); var sharingCapability = p.EnsureProperty(s => s.SharingCapability); if (sharingCapability != Microsoft.Online.SharePoint.TenantManagement.SharingCapabilities.Disabled) { DateTime checkDate = DateTime.Now; var lastCheckDate = e.WebClientContext.Web.GetPropertyBagValueString(PNPCHECKDATEPROPERTYBAGKEY, string.Empty); if (lastCheckDate == string.Empty) { // new site. Temporary set the check date to less than one Month checkDate = checkDate.AddMonths(-2); } else { if (!DateTime.TryParse(lastCheckDate, out checkDate)) { // Something went wrong with trying to parse the date in the propertybag. Do the check anyway. checkDate = checkDate.AddMonths(-2); } } if (checkDate.AddMonths(1) < DateTime.Now) { e.SiteClientContext.Web.EnsureProperty(w => w.Url); e.WebClientContext.Web.EnsureProperty(w => w.Url); EmailProperties mailProps = new EmailProperties(); mailProps.Subject = "Review required: external users with access to your site"; StringBuilder bodyBuilder = new StringBuilder(); bodyBuilder.AppendFormat("<html><head>{0}</head><body style=\"font-family:sans-serif\">", CSSSTYLE); bodyBuilder.AppendFormat("<p>Your site with address {0} has one or more external users registered. Please review the following list and take appropriate action if such access is not wanted anymore for a user.</p>", e.SiteClientContext.Web.Url); bodyBuilder.Append("<table class=\"tg\"><tr><th>Name</th><th>Invited by</th><th>Created</th><th>Invited As</th><th>Accepted As</th></tr>"); var externalusers = e.TenantClientContext.Web.GetExternalUsersForSiteTenant(new Uri(e.WebClientContext.Web.Url)); if (externalusers.Any()) { foreach (var externalUser in externalusers) { bodyBuilder.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", externalUser.DisplayName, externalUser.InvitedBy, externalUser.WhenCreated, externalUser.InvitedAs, externalUser.AcceptedAs); } bodyBuilder.Append("</table></body></html>"); mailProps.Body = bodyBuilder.ToString(); mailProps.To = adminEmails.ToArray(); Utility.SendEmail(e.SiteClientContext, mailProps); e.SiteClientContext.ExecuteQueryRetry(); } e.WebClientContext.Web.SetPropertyBagValue(PNPCHECKDATEPROPERTYBAGKEY, DateTime.Now.ToString()); } } Console.WriteLine("Ending job"); }
public static void Run() { // ExStart:1 EmailApi emailApi = new EmailApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH); StorageApi storageApi = new StorageApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH); String name = "email_test"; String fileName = name + ".eml"; String storage = ""; String folder = ""; EmailDocument body = new EmailDocument(); EmailProperties emailProperties = new EmailProperties(); System.Collections.Generic.List <Link> links = new System.Collections.Generic.List <Link> { }; System.Collections.Generic.List <EmailProperty> empProps = new System.Collections.Generic.List <EmailProperty> { }; Link link = new Link(); link.Href = "http://api.aspose.com/v1.1/pdf/"; link.Rel = "self"; link.Title = "NewField"; link.Type = "link"; links.Add(link); EmailProperty emailBody = new EmailProperty(); EmailProperty emailTo = new EmailProperty(); EmailProperty emailFrom = new EmailProperty(); emailBody.Name = "Body"; emailBody.Value = "This is the Body"; emailBody.Link = link; empProps.Add(emailBody); emailTo.Name = "To"; emailTo.Value = "*****@*****.**"; emailTo.Link = link; empProps.Add(emailTo); emailFrom.Name = "From"; emailFrom.Value = "*****@*****.**"; emailFrom.Link = link; empProps.Add(emailFrom); emailProperties.List = empProps; emailProperties.Link = link; body.DocumentProperties = emailProperties; body.Links = links; try { // Invoke Aspose.Email Cloud SDK API to add new email EmailDocumentResponse apiResponse = emailApi.PutCreateNewEmail(fileName, storage, folder, body); if (apiResponse != null) { Com.Aspose.Storage.Model.ResponseMessage storageRes = storageApi.GetDownload(fileName, null, null); System.IO.File.WriteAllBytes(Common.GetDataDir() + fileName, storageRes.ResponseStream); Console.WriteLine("Add New Email, Done!"); Console.ReadKey(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("error:" + ex.Message + "\n" + ex.StackTrace); } // ExEnd:1 }
/// <summary> /// When the context menu property is clicked this is fired. /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">What parameter was sent</param> private void OnShowProperty(object sender, System.EventArgs e) { if ( m_listView.Selected != null ) { Cursor c = this.Cursor; this.Cursor = Cursors.WaitCursor; LdapSearchResult entry = m_listView.Selected.Tag as LdapSearchResult; bool isInvalid = (entry.DomainAccount == "[No Domain Account]" ); EmailProperties frm = new EmailProperties(entry); if ( frm.ShowDialog(this) == DialogResult.OK ) { if ( entry.DomainAccount.Length > 0 ) { if (entry.DomainAccount != "[No Domain Account]" && isInvalid ) { m_listView.Selected.IconNumber = 2; m_numberInvalid--; ShowInvalid(); } } } this.Cursor = c; } }
static void Main(string[] args) { //get governance variables such as warning duration and cutoff duration int warningDuration = Convert.ToInt32(ConfigurationManager.AppSettings["WarningDuration"]); int cutoffDuration = Convert.ToInt32(ConfigurationManager.AppSettings["CutoffDuration"]); string tenantName = ConfigurationManager.AppSettings["TenantName"]; string tenantUpnDomain = ConfigurationManager.AppSettings["TenantUpnDomain"]; Uri tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantName)); string webUrl = ""; #if DEBUG webUrl = "http://localhost:25440/"; #else webUrl = "https://sposharing.azurewebsites.net/"; #endif foreach (var siteUrl in sites) { //initialize a process date for this site and clean up to match SQL percision DateTime processDate = DateTime.Now; string stringTicks = processDate.Ticks.ToString(); int adjustmentTicks = Convert.ToInt32(stringTicks.Substring(stringTicks.Length - 5)); processDate = processDate.Subtract(TimeSpan.FromTicks(adjustmentTicks)); //use O365 Tenant Administration to get all the external sharing details for this site List <ExternalShareDetails> shares = new List <ExternalShareDetails>(); string adminRealm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var adminToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, adminRealm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), adminToken)) { //load the tenant var tenant = new Office365Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //initalize varables to going through the paged results int position = 0; bool hasMore = true; while (hasMore) { //get external users 50 at a time (this is the limit and why we are paging) var externalUsers = tenant.GetExternalUsersForSite(siteUrl, position, 50, String.Empty, SortOrder.Descending); clientContext.Load(externalUsers, i => i.TotalUserCount); clientContext.Load(externalUsers, i => i.ExternalUserCollection); clientContext.ExecuteQuery(); //convert each external user to our own entity foreach (var extUser in externalUsers.ExternalUserCollection) { position++; shares.Add(new ExternalShareDetails() { AcceptedAs = extUser.AcceptedAs.ToLower(), DisplayName = extUser.DisplayName, InvitedAs = extUser.InvitedAs.ToLower(), InvitedBy = (String.IsNullOrEmpty(extUser.InvitedBy)) ? null : extUser.InvitedBy.ToLower(), UserId = extUser.UserId, WhenCreated = extUser.WhenCreated }); } //determine if we have more pages to process hasMore = (externalUsers.TotalUserCount > position); } } //get an AppOnly accessToken and clientContext for the site collection Uri siteUri = new Uri(siteUrl); string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken)) { //first we need to load the site to determine if external sharing is enabled (Site.ShareByEmailEnabled) var site = clientContext.Site; var siteOwner = clientContext.Site.Owner; clientContext.Load(site); clientContext.Load(siteOwner); //include the site owner in case the share "InvitedBy" is null...we will send them email instead clientContext.ExecuteQuery(); //validate that the site has sharing turned on if (site.ShareByEmailEnabled) { //process all of the shares foreach (var externalShare in shares) { //look for an existing record in the database using (ExternalSharingDataEntities entities = new ExternalSharingDataEntities()) { var shareRecord = entities.ExternalShares.FirstOrDefault(i => i.LoginName.Equals(externalShare.AcceptedAs)); if (shareRecord != null) { //Update LastProcessedDate column of the record with the processDate shareRecord.LastProcessedDate = processDate; entities.SaveChanges(); } else { //get the original share date var details = getREST(accessToken, String.Format("{0}/_api/Web/SiteUserInfoList/Items({1})/FieldValuesAsText", siteUrl, externalShare.UserId)); externalShare.WhenCreated = Convert.ToDateTime(details.Descendants(ns + "Created").FirstOrDefault().Value); shareRecord = new ExternalShare() { UniqueIdentifier = Guid.NewGuid(), SiteCollectionUrl = siteUrl.ToLower(), LoginName = externalShare.AcceptedAs, UserId = externalShare.UserId, InvitedBy = (String.IsNullOrEmpty(externalShare.InvitedBy)) ? siteOwner.Email : externalShare.InvitedBy, OriginalSharedDate = externalShare.WhenCreated, LastProcessedDate = processDate }; entities.ExternalShares.Add(shareRecord); entities.SaveChanges(); } //check if the record falls inside the warnings double daysActive = processDate.Subtract(shareRecord.OriginalSharedDate).TotalDays; if (shareRecord.RefreshSharedDate != null) { daysActive = processDate.Subtract((DateTime)shareRecord.RefreshSharedDate).TotalDays; } //check for cutoff if (daysActive > cutoffDuration) { //remove the SPUser from the site clientContext.Web.SiteUsers.RemoveById(externalShare.UserId); clientContext.ExecuteQuery(); //delete the record entities.ExternalShares.Remove(shareRecord); entities.SaveChanges(); } else if (daysActive > warningDuration) { int expiresIn = Convert.ToInt32(cutoffDuration - daysActive); //send email to InvitedBy (which will be site collection owner when null) EmailProperties email = new EmailProperties(); email.To = new List <String>() { shareRecord.InvitedBy }; email.Subject = String.Format("Action Required: External sharing with {0} about to expire", externalShare.AcceptedAs); email.Body = String.Format("<html><body><p>You are receiving this message because you are the site administrator of <a href='{0}'>{0}</a> OR you shared it with {1}. The external access for this user is set to expire in {2} days. Use the link below to view additional details and perform actions to revoke OR extend access for another {3} days. If you do not act on this notice, the external access for this user to terminate in {2} days.</p><ul><li><a href='{4}Details/{5}'>View Details</a></li><li><a href='{4}Extend/{5}'>Extend {3} Days</a></li><li><a href='{4}Revoke/{5}'>Revoke Access</a></li></ul></body></html>", siteUrl, externalShare.AcceptedAs, expiresIn.ToString(), cutoffDuration.ToString(), webUrl, shareRecord.UniqueIdentifier); Utility.SendEmail(clientContext, email); clientContext.ExecuteQuery(); } } } } } //delete all database records for this site that have an older processDate...these should represent external users deleted by manually using (ExternalSharingDataEntities entities = new ExternalSharingDataEntities()) { var cleanUpRecords = entities.ExternalShares.Where(i => i.SiteCollectionUrl.Equals(siteUrl.ToLower()) && i.LastProcessedDate < processDate); foreach (var record in cleanUpRecords) { entities.ExternalShares.Remove(record); entities.SaveChanges(); } } } }
private void ValidateExternalUsersTimerJob_TimerJobRun(object sender, TimerJobRunEventArgs e) { Console.WriteLine("Starting job"); var web = e.SiteClientContext.Web; Tenant tenant = new Tenant(e.TenantClientContext); var siteAdmins = e.SiteClientContext.LoadQuery(web.SiteUsers.Include(u => u.Email).Where(u => u.IsSiteAdmin)); e.SiteClientContext.ExecuteQueryRetry(); List<string> adminEmails = new List<string>(); foreach (var siteAdmin in siteAdmins) { adminEmails.Add(siteAdmin.Email); } SiteProperties p = tenant.GetSitePropertiesByUrl(e.SiteClientContext.Url, true); var sharingCapability = p.EnsureProperty(s => s.SharingCapability); if (sharingCapability != Microsoft.Online.SharePoint.TenantManagement.SharingCapabilities.Disabled) { DateTime checkDate = DateTime.Now; var lastCheckDate = e.WebClientContext.Web.GetPropertyBagValueString(PNPCHECKDATEPROPERTYBAGKEY, string.Empty); if (lastCheckDate == string.Empty) { // new site. Temporary set the check date to less than one Month checkDate = checkDate.AddMonths(-2); } else { if (!DateTime.TryParse(lastCheckDate, out checkDate)) { // Something went wrong with trying to parse the date in the propertybag. Do the check anyway. checkDate = checkDate.AddMonths(-2); } } if (checkDate.AddMonths(1) < DateTime.Now) { e.SiteClientContext.Web.EnsureProperty(w => w.Url); e.WebClientContext.Web.EnsureProperty(w => w.Url); EmailProperties mailProps = new EmailProperties(); mailProps.Subject = "Review required: external users with access to your site"; StringBuilder bodyBuilder = new StringBuilder(); bodyBuilder.AppendFormat("<html><head>{0}</head><body style=\"font-family:sans-serif\">", CSSSTYLE); bodyBuilder.AppendFormat("<p>Your site with address {0} has one or more external users registered. Please review the following list and take appropriate action if such access is not wanted anymore for a user.</p>", e.SiteClientContext.Web.Url); bodyBuilder.Append("<table class=\"tg\"><tr><th>Name</th><th>Invited by</th><th>Created</th><th>Invited As</th><th>Accepted As</th></tr>"); var externalusers = e.TenantClientContext.Web.GetExternalUsersForSiteTenant(new Uri(e.WebClientContext.Web.Url)); if (externalusers.Any()) { foreach (var externalUser in externalusers) { bodyBuilder.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", externalUser.DisplayName, externalUser.InvitedBy, externalUser.WhenCreated, externalUser.InvitedAs, externalUser.AcceptedAs); } bodyBuilder.Append("</table></body></html>"); mailProps.Body = bodyBuilder.ToString(); mailProps.To = adminEmails.ToArray(); Utility.SendEmail(e.SiteClientContext, mailProps); e.SiteClientContext.ExecuteQueryRetry(); } e.WebClientContext.Web.SetPropertyBagValue(PNPCHECKDATEPROPERTYBAGKEY, DateTime.Now.ToString()); } } Console.WriteLine("Ending job"); }
static void Main(string[] args) { //get governance variables such as warning duration and cutoff duration int warningDuration = Convert.ToInt32(ConfigurationManager.AppSettings["WarningDuration"]); int cutoffDuration = Convert.ToInt32(ConfigurationManager.AppSettings["CutoffDuration"]); string tenantName = ConfigurationManager.AppSettings["TenantName"]; string tenantUpnDomain = ConfigurationManager.AppSettings["TenantUpnDomain"]; Uri tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantName)); string webUrl = ""; #if DEBUG webUrl = "http://localhost:25440/"; #else webUrl = "https://sposharing.azurewebsites.net/"; #endif foreach (var siteUrl in sites) { //initialize a process date for this site and clean up to match SQL percision DateTime processDate = DateTime.Now; string stringTicks = processDate.Ticks.ToString(); int adjustmentTicks = Convert.ToInt32(stringTicks.Substring(stringTicks.Length - 5)); processDate = processDate.Subtract(TimeSpan.FromTicks(adjustmentTicks)); //use O365 Tenant Administration to get all the external sharing details for this site List<ExternalShareDetails> shares = new List<ExternalShareDetails>(); string adminRealm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri); var adminToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, adminRealm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), adminToken)) { //load the tenant var tenant = new Office365Tenant(clientContext); clientContext.Load(tenant); clientContext.ExecuteQuery(); //initalize varables to going through the paged results int position = 0; bool hasMore = true; while (hasMore) { //get external users 50 at a time (this is the limit and why we are paging) var externalUsers = tenant.GetExternalUsersForSite(siteUrl, position, 50, String.Empty, SortOrder.Descending); clientContext.Load(externalUsers, i => i.TotalUserCount); clientContext.Load(externalUsers, i => i.ExternalUserCollection); clientContext.ExecuteQuery(); //convert each external user to our own entity foreach (var extUser in externalUsers.ExternalUserCollection) { position++; shares.Add(new ExternalShareDetails() { AcceptedAs = extUser.AcceptedAs.ToLower(), DisplayName = extUser.DisplayName, InvitedAs = extUser.InvitedAs.ToLower(), InvitedBy = (String.IsNullOrEmpty(extUser.InvitedBy)) ? null : extUser.InvitedBy.ToLower(), UserId = extUser.UserId, WhenCreated = extUser.WhenCreated }); } //determine if we have more pages to process hasMore = (externalUsers.TotalUserCount > position); } } //get an AppOnly accessToken and clientContext for the site collection Uri siteUri = new Uri(siteUrl); string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken)) { //first we need to load the site to determine if external sharing is enabled (Site.ShareByEmailEnabled) var site = clientContext.Site; var siteOwner = clientContext.Site.Owner; clientContext.Load(site); clientContext.Load(siteOwner); //include the site owner in case the share "InvitedBy" is null...we will send them email instead clientContext.ExecuteQuery(); //validate that the site has sharing turned on if (site.ShareByEmailEnabled) { //process all of the shares foreach (var externalShare in shares) { //look for an existing record in the database using (ExternalSharingDataEntities entities = new ExternalSharingDataEntities()) { var shareRecord = entities.ExternalShares.FirstOrDefault(i => i.LoginName.Equals(externalShare.AcceptedAs)); if (shareRecord != null) { //Update LastProcessedDate column of the record with the processDate shareRecord.LastProcessedDate = processDate; entities.SaveChanges(); } else { //get the original share date var details = getREST(accessToken, String.Format("{0}/_api/Web/SiteUserInfoList/Items({1})/FieldValuesAsText", siteUrl, externalShare.UserId)); externalShare.WhenCreated = Convert.ToDateTime(details.Descendants(ns + "Created").FirstOrDefault().Value); shareRecord = new ExternalShare() { UniqueIdentifier = Guid.NewGuid(), SiteCollectionUrl = siteUrl.ToLower(), LoginName = externalShare.AcceptedAs, UserId = externalShare.UserId, InvitedBy = (String.IsNullOrEmpty(externalShare.InvitedBy)) ? siteOwner.Email : externalShare.InvitedBy, OriginalSharedDate = externalShare.WhenCreated, LastProcessedDate = processDate }; entities.ExternalShares.Add(shareRecord); entities.SaveChanges(); } //check if the record falls inside the warnings double daysActive = processDate.Subtract(shareRecord.OriginalSharedDate).TotalDays; if (shareRecord.RefreshSharedDate != null) daysActive = processDate.Subtract((DateTime)shareRecord.RefreshSharedDate).TotalDays; //check for cutoff if (daysActive > cutoffDuration) { //remove the SPUser from the site clientContext.Web.SiteUsers.RemoveById(externalShare.UserId); clientContext.ExecuteQuery(); //delete the record entities.ExternalShares.Remove(shareRecord); entities.SaveChanges(); } else if (daysActive > warningDuration) { int expiresIn = Convert.ToInt32(cutoffDuration - daysActive); //send email to InvitedBy (which will be site collection owner when null) EmailProperties email = new EmailProperties(); email.To = new List<String>() { shareRecord.InvitedBy }; email.Subject = String.Format("Action Required: External sharing with {0} about to expire", externalShare.AcceptedAs); email.Body = String.Format("<html><body><p>You are receiving this message because you are the site administrator of <a href='{0}'>{0}</a> OR you shared it with {1}. The external access for this user is set to expire in {2} days. Use the link below to view additional details and perform actions to revoke OR extend access for another {3} days. If you do not act on this notice, the external access for this user to terminate in {2} days.</p><ul><li><a href='{4}Details/{5}'>View Details</a></li><li><a href='{4}Extend/{5}'>Extend {3} Days</a></li><li><a href='{4}Revoke/{5}'>Revoke Access</a></li></ul></body></html>", siteUrl, externalShare.AcceptedAs, expiresIn.ToString(), cutoffDuration.ToString(), webUrl, shareRecord.UniqueIdentifier); Utility.SendEmail(clientContext, email); clientContext.ExecuteQuery(); } } } } } //delete all database records for this site that have an older processDate...these should represent external users deleted by manually using (ExternalSharingDataEntities entities = new ExternalSharingDataEntities()) { var cleanUpRecords = entities.ExternalShares.Where(i => i.SiteCollectionUrl.Equals(siteUrl.ToLower()) && i.LastProcessedDate < processDate); foreach (var record in cleanUpRecords) { entities.ExternalShares.Remove(record); entities.SaveChanges(); } } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); var paramlistname = List.Title; var paramviewname = View.Title; this.ColumnMappings = new List <FieldMappings>(); try { var viewlist = ClientContext.Web.GetListByTitle(paramlistname); ClientContext.Load(viewlist, rcll => rcll.Fields, rcll => rcll.ItemCount, rcll => rcll.ContentTypes, rcll => rcll.BaseType); ClientContext.Load(viewlist.Views, wv => wv.Include(wvi => wvi.Title, wvi => wvi.Id, wvi => wvi.ListViewXml, wvi => wvi.ViewFields)); ClientContext.ExecuteQueryRetry(); var viewFieldHeaderHtml = string.Empty; var view = viewlist.Views.FirstOrDefault(w => w.Title.Trim().Equals(paramviewname, StringComparison.CurrentCultureIgnoreCase)); if (view != null) { var doc = XDocument.Parse(view.ListViewXml); var queryXml = doc.Root.Element(XName.Get("Query")); var camlFieldXml = doc.Root.Element(XName.Get("ViewFields")); var queryWhereXml = queryXml.Element(XName.Get("Where")); var queryGroupByXml = queryXml.Element(XName.Get("GroupBy")); var queryOrderXml = queryXml.Element(XName.Get("OrderBy")); var queryViewCaml = ((camlFieldXml != null) ? camlFieldXml.ToString() : string.Empty); var queryWhereCaml = ((queryWhereXml != null) ? queryWhereXml.ToString() : string.Empty); var queryOrderCaml = ((queryOrderXml != null) ? queryOrderXml.ToString() : string.Empty); var viewFields = new List <string>() { "ContentTypeId", "FileRef", "FileDirRef", "FileLeafRef" }; if (viewlist.BaseType == BaseType.GenericList) { viewFields.AddRange(new string[] { ConstantsListFields.Field_LinkTitle, ConstantsListFields.Field_LinkTitleNoMenu }); } if (viewlist.BaseType == BaseType.DocumentLibrary) { viewFields.AddRange(new string[] { ConstantsLibraryFields.Field_LinkFilename, ConstantsLibraryFields.Field_LinkFilenameNoMenu }); } foreach (var xnode in camlFieldXml.Descendants()) { var attributeValue = xnode.Attribute(XName.Get("Name")); var fe = attributeValue.Value; if (fe == "ContentType") { fe = "ContentTypeId"; } if (!viewFields.Any(vf => vf == fe)) { viewFields.Add(fe); } } // lets override the view field XML with some additional columns queryViewCaml = CAML.ViewFields(viewFields.Select(s => CAML.FieldRef(s)).ToArray()); var viewFieldsHeader = "<tr>"; var viewFieldsHeaderIdx = 0; view.ViewFields.ToList().ForEach(fe => { var fieldDisplayName = viewlist.Fields.FirstOrDefault(fod => fod.InternalName == fe); ColumnMappings.Add(new FieldMappings() { ColumnInternalName = fieldDisplayName.InternalName, ColumnMandatory = fieldDisplayName.Required, ColumnType = fieldDisplayName.FieldTypeKind }); viewFieldsHeader += string.Format("<th>{0}</th>", (fieldDisplayName == null ? fe : fieldDisplayName.Title)); viewFieldsHeaderIdx++; }); viewFieldsHeader += "</tr>"; var innerGroupName = string.Empty; var hasGroupStrategy = false; if (queryGroupByXml != null && queryGroupByXml.HasElements) { queryWhereCaml = queryGroupByXml.ToString() + queryWhereCaml; hasGroupStrategy = true; var innerGroupBy = queryGroupByXml.Elements(); var innerGroupField = innerGroupBy.FirstOrDefault(); innerGroupName = innerGroupField.Attribute(XName.Get("Name")).Value; } var camlQueryXml = CAML.ViewQuery(ViewScope.RecursiveAll, queryWhereCaml, queryOrderCaml, queryViewCaml, 500); ListItemCollectionPosition camlListItemCollectionPosition = null; var camlQuery = new CamlQuery(); camlQuery.ViewXml = camlQueryXml; var previousgroupname = "zzzzzzzzzheader"; var htmltoemail = new StringBuilder(); htmltoemail.Append("<table>"); if (!hasGroupStrategy) { htmltoemail.Append(viewFieldsHeader); } while (true) { camlQuery.ListItemCollectionPosition = camlListItemCollectionPosition; var spListItems = viewlist.GetItems(camlQuery); this.ClientContext.Load(spListItems, lti => lti.ListItemCollectionPosition); this.ClientContext.ExecuteQueryRetry(); camlListItemCollectionPosition = spListItems.ListItemCollectionPosition; foreach (var ittpItem in spListItems) { LogVerbose("Item {0}", ittpItem.Id); if (hasGroupStrategy) { var currentgroupname = ittpItem.RetrieveListItemValue(innerGroupName).Trim(); if (previousgroupname != currentgroupname) { htmltoemail.AppendFormat("<tr><th colspan='{0}' style='text-align:center;background-color:blue;color:white'>{1}</th></tr>", viewFieldsHeaderIdx, currentgroupname); htmltoemail.Append(viewFieldsHeader); previousgroupname = currentgroupname; } } var htmlrow = "<tr>"; view.ViewFields.ToList().ForEach(fe => { if (fe == "ContentType") { fe = "ContentTypeId"; } var htmlrowvalue = string.Empty; try { var c = ColumnMappings.FirstOrDefault(f => f.ColumnInternalName == fe); if (c != null && c.ColumnType == FieldType.Lookup) { var res = ittpItem.RetrieveListItemValueAsLookup(fe); htmlrowvalue = res.ToLookupValue(); } else if (c != null && c.ColumnType == FieldType.User) { var res = ittpItem.RetrieveListItemUserValue(fe); htmlrowvalue = res.ToUserValue(); } else { htmlrowvalue = ittpItem.RetrieveListItemValue(fe); } } catch (Exception fex) { LogWarning("Failed to retreive {0} msg => {1}", fe, fex.Message); } finally { } htmlrow += string.Format("<td>{0}</td>", htmlrowvalue); }); htmlrow += "</tr>"; htmltoemail.Append(htmlrow); } if (camlListItemCollectionPosition == null) { break; } } htmltoemail.Append("</table>"); var properties = new EmailProperties { To = SendTo, Subject = $"HTML from Email List ${List.Title}", Body = string.Format("<div>{0}</div>", htmltoemail.ToString()) }; Microsoft.SharePoint.Client.Utilities.Utility.SendEmail(this.ClientContext, properties); this.ClientContext.ExecuteQueryRetry(); } } catch (Exception fex) { LogError(fex, "Failed to parse view and produce HTML report"); } }
/// <summary> /// Sends an email using the SharePoint SendEmail method /// </summary> /// <param name="context">Context for SharePoint objects and operations</param> /// <param name="to">List of TO addresses.</param> /// <param name="cc">List of CC addresses.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">HTML body of the mail.</param> public static void SendEmail(ClientContext context, IEnumerable<String> to, IEnumerable<String> cc, string subject, string body) { EmailProperties properties = new EmailProperties(); properties.To = to; if (cc != null) { properties.CC = cc; } properties.Subject = subject; properties.Body = body; Microsoft.SharePoint.Client.Utilities.Utility.SendEmail(context, properties); context.ExecuteQueryRetry(); }
public void SendEmail(EmailProperties properties) { Utility.SendEmail(context, properties); context.ExecuteQuery(); }
// .........................................................................Add To Queue..................................................................... public void AddToQueue(EmailType emailType, string subject, Recipient recipient, EmailProperties emailProperties) { List <Recipient> recipients = new List <Recipient>(); recipients.Add(recipient); AddToQueue(emailType, subject, recipients, emailProperties); }
public void AddToQueue(EmailType emailType, string subject, IEnumerable <Recipient> recipients, EmailProperties emailProperties) { foreach (Recipient recipient in recipients) { emailProperties.Recipient = new Recipient { FirstName = recipient.FirstName, LastName = recipient.LastName, Email = recipient.Email }; emails.Add(new EmailMessage { EmailType = emailType, EmailAddress = recipient.Email, Subject = subject, EmailProperties = emailProperties }); } }
public static bool SendEmail(EmailProperties emailProperties, ref string outputMessage) { bool mailStatus = true; try { if (string.IsNullOrEmpty(emailProperties.SmtpServer)) { outputMessage += "Email Module : Empty/Null SmtpServer specified." + Environment.NewLine; mailStatus = false; } if (string.IsNullOrEmpty(emailProperties.To)) { outputMessage = "Email Module : Empty/Null ToAddress specified." + Environment.NewLine; mailStatus = false; } emailProperties.From = string.IsNullOrEmpty(emailProperties.From) ? "*****@*****.**" : emailProperties.From; emailProperties.Subject = string.IsNullOrEmpty(emailProperties.Subject) ? "Email subject is not specified." : emailProperties.Subject; emailProperties.Body = string.IsNullOrEmpty(emailProperties.Body) ? "Email body is not specified. " : emailProperties.Body; // Process email only if there are no email property issues if (mailStatus) { SmtpClient objSMTPClient = new SmtpClient(); objSMTPClient.Host = emailProperties.SmtpServer; objSMTPClient.EnableSsl = emailProperties.EnableSSL; if (!string.IsNullOrEmpty(emailProperties.UserName) && !string.IsNullOrEmpty(emailProperties.Password)) { objSMTPClient.Credentials = new NetworkCredential(emailProperties.UserName, emailProperties.Password); objSMTPClient.UseDefaultCredentials = true; } else { objSMTPClient.UseDefaultCredentials = true; } // Prepare MailMessage since we need to setup CC MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress(emailProperties.From); mailMessage.Subject = emailProperties.Subject; mailMessage.Body = emailProperties.Body; if (emailProperties.To?.Length > 0) { foreach (var toAddress in emailProperties.To.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries)) { mailMessage.To.Add(toAddress); } } if (emailProperties.CC?.Length > 0) { foreach (var ccAddress in emailProperties.CC.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries)) { mailMessage.CC.Add(ccAddress); } } if (emailProperties.Attachments?.Count > 0) { foreach (string attachmentFileName in emailProperties.Attachments) { if (System.IO.File.Exists(attachmentFileName)) { // Create the file attachment for this e-mail message. Attachment data = new Attachment(attachmentFileName, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(attachmentFileName); disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachmentFileName); disposition.ReadDate = System.IO.File.GetLastAccessTime(attachmentFileName); // Add the file attachment to this e-mail message. mailMessage.Attachments.Add(data); } } } //mailMessage.IsBodyHtml = true; // Finally send the message objSMTPClient.Send(mailMessage); } return(mailStatus); } catch (Exception ex) { outputMessage = "Email Module : EXCEPTION " + ex.Message + Environment.NewLine; return(false); } }
public void TestPutCreateNewEmail() { EmailApi target = new EmailApi(APIKEY, APPSID, BASEPATH); StorageApi storageApi = new StorageApi(APIKEY, APPSID, BASEPATH); string name = "email_test.eml"; string storage = null; string folder = null; EmailDocument body = new EmailDocument(); EmailProperties emailProperties = new EmailProperties(); System.Collections.Generic.List <Link> links = new System.Collections.Generic.List <Link> { }; System.Collections.Generic.List <EmailProperty> empProps = new System.Collections.Generic.List <EmailProperty> { }; Link link = new Link(); link.Href = "http://api.aspose.com/v1.1/pdf/"; link.Rel = "self"; link.Title = "NewField"; link.Type = "link"; links.Add(link); EmailProperty emailBody = new EmailProperty(); EmailProperty emailTo = new EmailProperty(); EmailProperty emailFrom = new EmailProperty(); emailBody.Name = "Body"; emailBody.Value = "This is the Body"; emailBody.Link = link; empProps.Add(emailBody); emailTo.Name = "To"; emailTo.Value = "*****@*****.**"; emailTo.Link = link; empProps.Add(emailTo); emailFrom.Name = "From"; emailFrom.Value = "*****@*****.**"; emailFrom.Link = link; empProps.Add(emailFrom); emailProperties.List = empProps; emailProperties.Link = link; body.DocumentProperties = emailProperties; body.Links = links; storageApi.PutCreate(name, null, null, System.IO.File.ReadAllBytes("\\temp\\email\\resources\\" + name)); EmailDocumentResponse actual; actual = target.PutCreateNewEmail(name, storage, folder, body); Assert.AreEqual("200", actual.Code); Assert.IsInstanceOfType(new EmailDocumentResponse(), actual.GetType()); }
static void Main(string[] args) { // DateTime d1 = DateTime.Parse(DateTime.Now.ToShortDateString()); // DateTime t = utility.NthOf(0, d1.DayOfWeek); //// d1 = DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(7); // t = utility.NthOf(1, d1.DayOfWeek); // t = utility.NthOf(2, d1.DayOfWeek); // t = utility.NthOf(3, d1.DayOfWeek); // t = utility.NthOf(4, d1.DayOfWeek); // d1 = DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(14); // t = utility.NthOf(1, d1.DayOfWeek); string logFilePath = ConfigurationManager.AppSettings["logFilePath"]; string logFileName = "GCC-NthDay-log -" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + ".log"; using (StreamWriter writer = new StreamWriter(logFilePath + "/" + logFileName, true)) { writer.WriteLine("Data Time:" + DateTime.Now); writer.Close(); } DateTime dateValue = DateTime.Now; ClientContext ctx = spAuthentication(ConfigurationManager.AppSettings["url"]); Web web = ctx.Web; List sourcelist = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["Library"]); string we = dateValue.DayOfWeek.ToString(); string caml = @"<View><Query><Where><Eq><FieldRef Name='WeekDay' /><Value Type='Choice'>" + we + "</Value></Eq></Where></Query></View>"; CamlQuery query = new CamlQuery(); query.ViewXml = caml; ListItemCollection listItems = sourcelist.GetItems(query); ctx.Load(listItems); ctx.ExecuteQuery(); // Console.WriteLine("Total No of Items is:" + listItems.Count); try { foreach (var listItem in listItems) { string rec = listItem["Recurrence"].ToString(); string wd = listItem["WeekDay"].ToString(); string title = listItem["Title"].ToString(); double reportTime = Convert.ToDouble(listItem["ReportTime"]); string assignedTo = listItem["AssignedTo"].ToString(); string criticality = listItem["Criticality"].ToString(); string program = listItem["Program"].ToString(); string subProgram = listItem["SubProgram"].ToString(); string status = Convert.ToString(listItem["Status"]); string reportCategory = Convert.ToString(listItem["ReportCategory"]); string distro = Convert.ToString(listItem["Distro"]); if (rec != "Last") { int c = int.Parse(rec); DayOfWeek dd = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), wd); bool dt = utility.NthDayOfMonth(dateValue, dd, c); // Console.WriteLine(dt); if (dt) { List targetlist = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["DestinationList"]); CamlQuery qry = new CamlQuery(); qry.ViewXml = @"<Query><OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy></Query>"; ListItemCollection listItemss = targetlist.GetItems(qry); ctx.Load(listItemss); ctx.ExecuteQuery(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = targetlist.AddItem(itemCreateInfo); oListItem["Title"] = title; oListItem["ReportDate"] = DateTime.Now; oListItem["Program"] = program; var dateTimeOnly = DateTime.Now.Date.AddHours(reportTime); oListItem["ReportTime"] = dateTimeOnly; oListItem["AssignedTo"] = assignedTo; oListItem["Status"] = status; oListItem["Criticality"] = criticality; oListItem["SubProgram"] = subProgram; oListItem["TypeofReport1"] = reportCategory; oListItem.Update(); ctx.ExecuteQuery(); // Console.Write(oListItem.Id); using (var EmailclientContext = ctx) { var emailprpoperties = new EmailProperties(); List <string> assignees = assignedTo.Split(';').ToList(); emailprpoperties.To = assignees; emailprpoperties.From = "*****@*****.**"; emailprpoperties.Body = "<b>Good Day!!</b><br/>" + "Please note – the above said task has been assigned to you and is due by " + dateTimeOnly.ToString("MM/dd/yyyy HH:mm") + " hrs, upon completion respond on the same task mail.<br/>In event of delay click <a href=https://247incc.sharepoint.com/sites/GCC/Lists/GCCTransaction/EditForm.aspx?ID=" + oListItem.Id + "> here</a> to update status/ reason" + "<br/>" + "Refer doc #" + distro + "for email distro"; emailprpoperties.Subject = title + " ## " + oListItem.Id; Utility.SendEmail(EmailclientContext, emailprpoperties); EmailclientContext.ExecuteQuery(); } } } else { DayOfWeek ddl = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), wd); DateTime de1 = utility.GetLastWeekdayOfTheMonth(DateTime.Now, ddl); // bool dtd = utility.LastDayOfMonth(DateTime.Now); if (de1.Date.ToShortDateString() == dateValue.Date.ToShortDateString()) { List targetlist1 = ctx.Web.Lists.GetByTitle("GCCTransaction"); CamlQuery qry1 = new CamlQuery(); qry1.ViewXml = @"<Query><OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy></Query>"; ListItemCollection listItemss1 = targetlist1.GetItems(qry1); ctx.Load(listItemss1); ctx.ExecuteQuery(); ListItemCreationInformation itemCreateInfo1 = new ListItemCreationInformation(); ListItem oListItem1 = targetlist1.AddItem(itemCreateInfo1); oListItem1["Title"] = title; oListItem1["ReportDate"] = DateTime.Now; oListItem1["Program"] = program; var dateTimeOnly1 = DateTime.Now.Date.AddHours(reportTime); oListItem1["ReportTime"] = dateTimeOnly1; oListItem1["AssignedTo"] = assignedTo; oListItem1["Status"] = status; oListItem1["Criticality"] = criticality; oListItem1["SubProgram"] = subProgram; oListItem1["TypeofReport1"] = reportCategory; oListItem1.Update(); ctx.ExecuteQuery(); // Console.WriteLine(oListItem1.Id); using (var EmailclientContext1 = ctx) { var emailprpoperties1 = new EmailProperties(); List <string> assignees1 = assignedTo.Split(';').ToList(); emailprpoperties1.To = assignees1; emailprpoperties1.From = "*****@*****.**"; emailprpoperties1.Body = "<b>Good Day!!</b><br/>" + "Please note – the above said task has been assigned to you and is due by " + dateTimeOnly1.ToString("MM/dd/yyyy HH:mm") + " hrs, upon completion respond on the same task mail.<br/>In event of delay click <a href=https://247incc.sharepoint.com/sites/GCC/Lists/GCCTransaction/EditForm.aspx?ID=" + oListItem1.Id + "> here</a> to update status/ reason" + "<br/>" + "Refer doc #" + distro + " for email distro"; emailprpoperties1.Subject = title + " ## " + oListItem1.Id; Utility.SendEmail(EmailclientContext1, emailprpoperties1); EmailclientContext1.ExecuteQuery(); } } } } using (StreamWriter writer = new StreamWriter(logFilePath + "/" + logFileName, true)) { writer.WriteLine("Data Time:" + DateTime.Now); writer.Close(); } } catch (Exception ex) { using (var EmailclientContext = ctx) { var emailprpoperties = new EmailProperties(); emailprpoperties.To = new List <string> { "*****@*****.**", "*****@*****.**" }; emailprpoperties.From = "*****@*****.**"; emailprpoperties.Body = "<b>Nth Day data creation failed</b>" + ex; emailprpoperties.Subject = "Nth Day data creation failed"; Utility.SendEmail(EmailclientContext, emailprpoperties); EmailclientContext.ExecuteQuery(); } using (StreamWriter writer = new StreamWriter(logFilePath + "/" + logFileName, true)) { writer.WriteLine("Exception Msg : " + ex.Message); writer.WriteLine("Exception Msg : " + ex.StackTrace); writer.Close(); } } }