/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { SendEmailResponse response = new SendEmailResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("MessageId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.MessageId = unmarshaller.Unmarshall(context); continue; } } return(response); }
public async void EmailRequestHasEmptyToName() { //Arrange var controller = new EmailController(_mockHttpClientFactory, _mockEmailHelperRepository); EmailRequest emailRequest = new EmailRequest(); emailRequest.To = "*****@*****.**"; emailRequest.To_name = ""; var expectedResponse = new SendEmailResponse(false, "Please fix input fields. They are either empty or invalid."); //Act var actualResponse = await controller.SendEmail(emailRequest); //Assert Assert.Equal(expectedResponse.IsEmailSent, actualResponse.IsEmailSent); Assert.Equal(expectedResponse.Message, actualResponse.Message); }
protected override async Task <string> DoSendAsync(string from, string to, string subject, string bodyText, string bodyHtml) { logger.Debug($"DoSendAsync():from={from},to={to},subject={subject}"); Destination destination = new Destination { ToAddresses = (new List <string>() { to }) }; Content subjectContent = new Content(subject); Content bodyContent = new Content(bodyText); Body myBody = new Body(bodyContent); if (!string.IsNullOrEmpty(bodyHtml)) { myBody.Html = new Content(bodyHtml); } Message message = new Message(subjectContent, myBody); SendEmailRequest sendEmailRequest = new SendEmailRequest(from, destination, message); AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(Amazon.RegionEndpoint.USEast1); logger.Debug($"DoSendAsync():client.SendEmailAsync()"); SendEmailResponse sendEmailResponse = await client.SendEmailAsync(sendEmailRequest); logger.Debug($"DoSendAsync():client.SendEmailAsync():sendEmailResponse.MessageId={sendEmailResponse.MessageId}"); return(sendEmailResponse.MessageId); /* * try { * logger.Debug($"DoSendAsync():client.SendEmailAsync()"); * SendEmailResponse sendEmailResponse = await client.SendEmailAsync(sendEmailRequest); * return sendEmailResponse.MessageId; * } * catch (Exception ex) { * Console.WriteLine("The email was not sent."); * Console.WriteLine("Error message: " + ex.Message); * } */ }
public async Task <SendEmailResponse> SendAsync(Message message) { var result = new SendEmailResponse(); string api_key = ApiKey; #region validate api key and message if (api_key == null) { result.ErrorMessage = "The environment variable SENDGRID_API_KEY was not found."; logger.LogWarning(result.ErrorMessage); return(result); } var validator = new MessageValidator(); var messageValidationResult = validator.Validate(message); if (!messageValidationResult.IsValid) { result.ErrorMessage = "Cannot send email. " + string.Join(" ", messageValidationResult.Errors.Select(x => $"Property {x.PropertyName} failed validation with error: {x.ErrorMessage}.")); logger.LogError(result.ErrorMessage); return(result); } #endregion var client = new SendGridClient(api_key); var from = new EmailAddress(message.FromEmail, message.From); var to = new EmailAddress(message.ToEmail, message.To); var msg = MailHelper.CreateSingleEmail(from, to, message.Subject, !message.IsHTML ? message.Content : null, message.IsHTML ? message.Content : null); var response = await client.SendEmailAsync(msg); if (response.StatusCode != HttpStatusCode.Accepted) { var body = response.Body.ReadAsStringAsync(); result.ErrorMessage = $"There were problems with the delivery of the message. Service returned {response.StatusCode} status code. Find more information at https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html. --response body: {body}"; logger.LogError("result.ErrorMessage"); } else { logger.LogInformation($"Successfully delivered email to {message.To} ({message.ToEmail}) from {message.From} ({message.FromEmail})."); } return(result); }
public async Task <SendEmailResponse> SendEmail(EmailRequest emailRequest) { try { if (!emailRequest.isValid()) { return(new SendEmailResponse(false, "Please fix input fields. They are either empty or invalid.")); } var client = _clientFactory.CreateClient(); SendEmailResponse response = new SendEmailResponse(); response = await _emailHelperRepository.SendEmail(client, emailRequest); return(response ?? throw new Exception("Response from Email Provider is Null.")); } catch (Exception ex) { //log exception Console.WriteLine(ex.Message); return(new SendEmailResponse(false, "Oops! Something went wrong, please try again later.")); } }
/// <summary> /// Sends the email. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public async Task <SendEmailResponse> SendEmail(SendEmailRequest request, CancellationToken cancellationToken) { SendEmailResponse response = null; // Translate the request message var apiRequest = new Smtp2GoSendEmailRequest { ApiKey = ConfigurationReader.GetValue("SMTP2GoAPIKey"), HTMLBody = request.IsHtml ? request.Body : String.Empty, TextBody = request.IsHtml ? String.Empty : request.Body, Sender = request.FromAddress, Subject = request.Subject, TestMode = false, To = request.ToAddresses.ToArray() }; String requestSerialised = JsonConvert.SerializeObject(apiRequest); StringContent content = new StringContent(requestSerialised, Encoding.UTF8, "application/json"); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(ConfigurationReader.GetValue("SMTP2GoBaseAddress")); var httpResponse = await client.PostAsync("email/send", content, cancellationToken); var apiResponse = JsonConvert.DeserializeObject <Smtp2GoSendEmailResponse>(await httpResponse.Content.ReadAsStringAsync()); // Translate the Response response = new SendEmailResponse { ApiStatusCode = httpResponse.StatusCode, EmailId = apiResponse.Data.EmailId, Error = apiResponse.Data.Error, ErrorCode = apiResponse.Data.ErrorCode, RequestId = apiResponse.RequestId }; } return(response); }
public async Task <IActionResult> Send(EmailForm model) { var response = new SendEmailResponse(); if (!ModelState.IsValid) { response.Success = false; response.Data = ModelState.Keys .Where(x => ModelState[x].Errors.Count > 0) .Select(x => new { Name = x, Errors = ModelState[x].Errors.Select(y => y.ErrorMessage) }); return(Json(response)); } try { var email = _emailNotificationRequestFactory.CreateEmailBuilder() .WithFrom("*****@*****.**") .WithTo("*****@*****.**") .WithSubject(model.Subject) .WithViewName("Contact") .WithViewModel(model) .Build(); var emailResponse = await _emailNotificationClient.SendAsync(email); response.Success = emailResponse.IsSent; response.Data = model; } catch (Exception exc) { response.Success = false; response.Message = exc.Message; } return(Json(response)); }
private string CreateEmail(List <Entity> usersTo, Guid userFromId, Entity contact) { ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference("systemuser", userFromId) }; List <ActivityParty> toParty = new List <ActivityParty>(); foreach (var user in usersTo) { toParty.Add(new ActivityParty { PartyId = new EntityReference(user.LogicalName, user.Id) }); } Email email = new Email { To = toParty, From = new ActivityParty[] { fromParty }, Description = string.Format("Contact Full Name: {0} \n Contact link: {1}", contact.GetAttributeValue <string>("fullname"), crmUrl + "/main.aspx?etn=contact&pagetype=entityrecord&id=%7B" + contact.Id.ToString().Replace("{", string.Empty).Replace("}", string.Empty) + "%7D"), DirectionCode = true, }; var emailId = _service.Create(email); CoppyContactAttachmentsToEmail(contact.Id, emailId); SendEmailRequest sendEmailreq = new SendEmailRequest { EmailId = emailId, TrackingToken = "", IssueSend = true }; SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq); return(sendEmailresp.Subject); }
public async Task WhenModelStateIsInvalidRedirectsToView() { AssessmentController.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext(), }; var sendEmailResponse = new SendEmailResponse() { IsSuccess = false }; var viewModel = new AssessmentEmailPostRequest() { Email = "*****@*****.**" }; A.CallTo(() => ApiService.SendEmail(A <string> .Ignored, viewModel.Email)).Returns(sendEmailResponse); var actionResponse = await AssessmentController.Email(viewModel).ConfigureAwait(false); Assert.IsType <ViewResult>(actionResponse); }
/// <summary> /// Send an e-mail message. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetSendEmail1> // Use the SendEmail message to send an e-mail message. SendEmailRequest sendEmailreq = new SendEmailRequest { EmailId = _emailId, TrackingToken = "", IssueSend = true }; SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq); Console.WriteLine("Sent the e-mail message."); //</snippetSendEmail1> DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
//Created By : Jerome Anthony Gerero, Created On : 4/29/2016 private void CreateEmail(Entity purchaseOrderEntity, EntityCollection recipients) { //Retrieve System Admininstrator contact EntityCollection sysAdmin = CommonHandler.RetrieveRecordsByOneValue("systemuser", "fullname", "System Administrator", _organizationService, null, OrderType.Ascending, new[] { "internalemailaddress" }); if (sysAdmin != null && sysAdmin.Entities.Count > 0) { Entity systemAdministrator = sysAdmin.Entities[0]; Entity from = new Entity("activityparty"); from["partyid"] = new EntityReference(systemAdministrator.LogicalName, systemAdministrator.Id); EntityCollection recipientsList = new EntityCollection(); recipientsList.EntityName = "activityparty"; foreach (Entity recipientEntity in recipients.Entities) { Entity recipientActivityParty = new Entity("activityparty"); recipientActivityParty["partyid"] = new EntityReference(recipientEntity.LogicalName, recipientEntity.Id); recipientsList.Entities.Add(recipientActivityParty); } Entity to = new Entity("activityparty"); to["partyid"] = recipientsList; Entity email = new Entity("email"); email["from"] = new Entity[] { from }; email["to"] = recipientsList; email["subject"] = "Purchase Order No. " + purchaseOrderEntity["gsc_purchaseorderpn"] + " Order Approved"; email["description"] = "Please be notified that the Purchase Order : " + purchaseOrderEntity["gsc_purchaseorderpn"] + " has been for Approval."; Guid emailId = _organizationService.Create(email); SendEmailRequest req = new SendEmailRequest(); req.EmailId = emailId; req.IssueSend = true; req.TrackingToken = ""; SendEmailResponse res = (SendEmailResponse)_organizationService.Execute(req); } }
private async Task SendEmail(TableRow tableRow) { String fromAddress = SpecflowTableHelper.GetStringRowValue(tableRow, "FromAddress"); String toAddresses = SpecflowTableHelper.GetStringRowValue(tableRow, "ToAddresses"); String subject = SpecflowTableHelper.GetStringRowValue(tableRow, "Subject"); String body = SpecflowTableHelper.GetStringRowValue(tableRow, "Body"); Boolean isHtml = SpecflowTableHelper.GetBooleanValue(tableRow, "IsHtml"); SendEmailRequest request = new SendEmailRequest { Body = body, ConnectionIdentifier = Guid.NewGuid(), FromAddress = fromAddress, IsHtml = isHtml, Subject = subject, ToAddresses = toAddresses.Split(",").ToList() }; SendEmailResponse sendEmailResponse = await this.TestingContext.DockerHelper.MessagingServiceClient.SendEmail(this.TestingContext.AccessToken, request, CancellationToken.None).ConfigureAwait(false); sendEmailResponse.MessageId.ShouldNotBe(Guid.Empty); }
public async Task SimpleEmailServiceProvider_Should_Return_MessageId_If_Response_Is_Accepted() { //Arrange var from = "*****@*****.**"; var to = "*****@*****.**"; var subject = "testing"; var body = "body not found"; var response = new SendEmailResponse { MessageId = "TestId" }; amazonSimpleEmailService.Setup(a => a.SendEmailAsync(It.IsAny <SendEmailRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(response); //Act var result = await simpleEmailServiceProvider.SendAsync(from, to, subject, body); //Assert Assert.IsNotNull(result); Assert.AreEqual(response.MessageId, result); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] [RequestBodyType(typeof(SendEmailToUsersRequest), "Send Email To Users")] SendEmailToUsersRequest req, ILogger log) { try { NewRelic.Api.Agent.NewRelic.SetTransactionName("CommunicationService", "SendEmailToUsers"); log.LogInformation("C# HTTP trigger function processed a request."); SendEmailResponse response = await _mediator.Send(req); return(new OkObjectResult(ResponseWrapper <SendEmailResponse, CommunicationServiceErrorCode> .CreateSuccessfulResponse(response))); } catch (Exception exc) { LogError.Log(log, exc, req); return(new ObjectResult(ResponseWrapper <SendEmailResponse, CommunicationServiceErrorCode> .CreateUnsuccessfulResponse(CommunicationServiceErrorCode.InternalServerError, "Internal Error")) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <SendEmailResponse> SendEmail(SendEmailRequest request) { var response = new SendEmailResponse(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(_url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage resp = await client.PostAsJsonAsync("/api/email", request); if (resp.IsSuccessStatusCode) { response = await resp.Content.ReadAsAsync <SendEmailResponse>(); return(response); } } return(response); }
public void Execute(IServiceProvider serviceprovider) { IPluginExecutionContext Context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext)); //getting the context from input parameters IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory)); //getting service factory IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(Context.UserId); //retrieving the service ITracingService tracingService = (ITracingService)serviceprovider.GetService(typeof(ITracingService)); // getting the tracing service if (Context.InputParameters.Contains("Target") && Context.InputParameters["Target"] is Entity) { Entity lead = (Entity)Context.InputParameters["Target"]; //getting lead entity from inputparameters string EmaildId = lead.GetAttributeValue <string>("emailaddress1"); //retrieving the Email Id from lead entity string Name = lead.GetAttributeValue <string>("lastname"); //retrieving last name of lead // from current user Entity from = new Entity("activityparty"); from["partyid"] = new EntityReference("systemuser", Context.UserId); // to newly created lead user Entity to = new Entity("activityparty"); to["partyid"] = new EntityReference("lead", lead.Id); //created a webresource named as "new_RealMadrid" which stores the image file string webresource = "<html> <img src='~/WebResources/new_RealMadrid' width='205' height='150'></html>"; // Create Email Entity Email = new Entity("email"); Email["from"] = new Entity[] { from }; Email["to"] = new Entity[] { to }; Email["subject"] = "Welcome Mr./ Mrs " + Name; Email["description"] = "<h3> Dear " + Name + "</h3>" + "<br/>" + "Welcome to my blog. Hope it helped you." + "<br/>" + " " + "<br/>" + "visit my blog for any query" + "" + "<br/>" + webresource; // Send email request Guid _emailId = service.Create(Email); SendEmailRequest reqSendEmail = new SendEmailRequest(); reqSendEmail.EmailId = _emailId; reqSendEmail.TrackingToken = ""; reqSendEmail.IssueSend = true; SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail); } }
/// <summary> /// Main entry point for he business logic that the plug-in is to execute. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> protected override void ExecuteCrmPlugin(LocalPluginContext localContext) { IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; Entity preEntity = (Entity)context.PreEntityImages["contactPreImage"]; Contact precontact = preEntity.ToEntity <Contact>(); Entity postEntity = (Entity)context.PostEntityImages["contactPostImage"]; Contact postContact = postEntity.ToEntity <Contact>(); if (precontact.di_IntialInvesmentFinal != postContact.di_IntialInvesmentFinal || precontact.di_interest_rate != postContact.di_interest_rate || precontact.di_InvestmentPeriod != postContact.di_InvestmentPeriod) { Entity entity = GetGlobalTemplate("Changes", service); Email email = new Email(); ActivityParty activityParty = new ActivityParty(); email.LogicalName = "email"; email.Subject = GetDataFromXml("match", entity.Attributes["subject"].ToString()); email.Subject = email.Subject.ToString().Replace("[subject]", "Changes Noticed on your account"); email.Description = GetDataFromXml("match", entity.Attributes["body"].ToString()); string urlToReplace = "<html><body><table border=1>" + "<tr><th>Field</th><th>Before</th><th>After</th>" + "</tr><tr><td>Initial Investment</td><td>" + Math.Round(precontact.di_IntialInvesmentFinal.GetValueOrDefault(0), 2) + "</td><td>" + Math.Round(postContact.di_IntialInvesmentFinal.GetValueOrDefault(0), 2) + "</td></tr><tr><td>Interest Rate</td><td>" + Math.Round(precontact.di_interest_rate.GetValueOrDefault(0), 2) + "</td><td>" + Math.Round(postContact.di_interest_rate.GetValueOrDefault(0), 2) + "</td></tr><tr><td>Investment Period</td><td>" + precontact.di_InvestmentPeriod + "</td><td>" + postContact.di_InvestmentPeriod + "</td></tr>" + "</table></body></html>"; email.Description = email.Description.ToString().Replace("[fullname]", postContact.FullName); email.Description = email.Description.ToString().Replace("[table]", urlToReplace); email.From = CreateActivityPartyList(postContact.OwnerId); email.To = CreateActivityPartyList(new EntityReference(Contact.EntityLogicalName, postContact.ContactId.Value)); email.RegardingObjectId = (new EntityReference(Contact.EntityLogicalName, postContact.ContactId.Value)); Guid emailCreated = service.Create(email); SendEmailRequest req = new SendEmailRequest(); req.EmailId = emailCreated; req.TrackingToken = string.Empty; req.IssueSend = true; SendEmailResponse res = (SendEmailResponse)service.Execute(req); } }
public void CreateAudit(T emailRequest, EmailTemplate emailTemplate, SendEmailResponse response) { var safeRequestSerialized = JsonConvert.SerializeObject(emailRequest); var safeRequest = JsonConvert.DeserializeObject <T>(safeRequestSerialized); try { var emailContent = mergeEmailContentService.MergeTemplateBodyWithContent(safeRequest, emailTemplate?.Body); Add(new Audit { CorrelationId = correlationId, Data = new EmailAuditRecord <T> { Request = safeRequest, EmailContent = emailContent, SendEmailResponse = response, EmailTemplate = emailTemplate }, Timestamp = DateTime.Now }); } catch (Exception exception) { logger.ErrorJustLogIt($"Failed to audit non-citizen email", exception); Add(new Audit { CorrelationId = correlationId, Data = new EmailAuditRecord <T> { Request = safeRequest, Exception = exception, SendEmailResponse = response, EmailTemplate = emailTemplate }, Timestamp = DateTime.Now }); } }
private void InitData() { to = new List <string>() { "*****@*****.**" }; cc = new List <string>() { "*****@*****.**" }; bcc = new List <string>() { "*****@*****.**" }; attahcmentPaths = new List <string>() { $"EmailTemplates\\UserCreated.cshtml", }; attachments = new List <Attachment>() { new Attachment { FileName = "file1", FileStream = new System.IO.MemoryStream() } }; var response = new SendEmailResponse() { HttpStatusCode = HttpStatusCode.OK }; _amazonSimpleEmailServiceMock.Setup(x => x.SendEmailAsync(It.IsAny <SendEmailRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(response); }
private string SendEmailInternal(List <string> toEmailAddresses, string subject, string content) { using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(RegionEndpoint)) { var sendRequest = new SendEmailRequest { Source = FromEmailAddress, Destination = new Destination { ToAddresses = toEmailAddresses }, Message = new Message { Subject = new Content(subject), Body = new Body { Text = new Content { Data = content, Charset = "UTF-8" } } }, ConfigurationSetName = ConfigurationSetName }; try { _logger.LogInformation("Sending email using Amazon SES..."); SendEmailResponse response = client.SendEmailAsync(sendRequest).Result; _logger.LogInformation($"HttpStatusCode = {response.HttpStatusCode}, MessageId = {response.MessageId}, RequestId = {response.ResponseMetadata.RequestId}, Metadata = {string.Join(";", response.ResponseMetadata.Metadata)}"); _logger.LogInformation("The email was sent successfully."); return(response.MessageId); } catch (Exception ex) { _logger.LogError("The email was not sent."); _logger.LogError("Error message: " + ex.Message); throw ex; } } }
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { SendEmailResponse response = new SendEmailResponse(); while (context.Read()) { if (context.IsStartElement) { if (context.TestExpression("SendEmailResult", 2)) { response.SendEmailResult = SendEmailResultUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context); } } } return(response); }
/// <summary> /// Sends the email. /// </summary> /// <param name="accessToken">The access token.</param> /// <param name="sendEmailRequest">The send email request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public async Task <SendEmailResponse> SendEmail(String accessToken, SendEmailRequest sendEmailRequest, CancellationToken cancellationToken) { SendEmailResponse response = null; String requestUri = this.BuildRequestUrl("/api/email/"); try { String requestSerialised = JsonConvert.SerializeObject(sendEmailRequest); StringContent httpContent = new StringContent(requestSerialised, Encoding.UTF8, "application/json"); // Add the access token to the client headers this.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // Make the Http Call here HttpResponseMessage httpResponse = await this.HttpClient.PostAsync(requestUri, httpContent, cancellationToken); // Process the response String content = await this.HandleResponse(httpResponse, cancellationToken); // call was successful so now deserialise the body to the response object response = JsonConvert.DeserializeObject <SendEmailResponse>(content); } catch (Exception ex) { // An exception has occurred, add some additional information to the message Exception exception = new Exception("Error sending email message.", ex); throw exception; } return(response); }
public async Task WhenModelStateIsValidRedirectsToView() { AssessmentController.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext(), }; var sendEmailResponse = new SendEmailResponse() { IsSuccess = true }; var viewModel = new AssessmentEmailPostRequest() { Email = "*****@*****.**" }; A.CallTo(() => ApiService.SendEmail(A <string> .Ignored, viewModel.Email)).Returns(sendEmailResponse); var actionResponse = await AssessmentController.Email(viewModel).ConfigureAwait(false); Assert.IsType <RedirectResult>(actionResponse); var redirectResult = actionResponse as RedirectResult; Assert.Equal($"~/{RouteName.Prefix}/assessment/emailsent", redirectResult.Url); }
// <returns></returns> public static bool sendEmailAttachment(string email, string subject, string body) { var awsConfig = new AmazonSimpleEmailServiceConfig(); awsConfig.RegionEndpoint = Amazon.RegionEndpoint.USWest2; var awsClient = new AmazonSimpleEmailServiceClient("AKIAJENNMZYOVK4V7XJA", "AnNyJMBTBAGvhcUF1N6gVfW1vQtmyC4allr1NVCf", awsConfig); Destination dest = new Destination(); dest.ToAddresses.Add(email); //Attachment att = new Attachment(); // string subject = "Supreme Brands App details"; Body bd = new Body(); bd.Html = new Amazon.SimpleEmail.Model.Content(body); Amazon.SimpleEmail.Model.Content title = new Amazon.SimpleEmail.Model.Content(subject); Message message = new Message(title, bd); try { SendEmailRequest ser = new SendEmailRequest("*****@*****.**", dest, message); SendEmailResponse seResponse = awsClient.SendEmail(ser); return(true); } catch (Exception ex) { return(false); } }
protected override void ExecuteActivity(CodeActivityContext executionContext) { if (this.WorkflowContext.InputParameters == null) { throw new ArgumentNullException("Workflow context doesn't contain any Input Parameter"); } EntityReference emailToBeSent = this.Email.Get <EntityReference>(executionContext); bool issueSend = this.IssueSend.Get <bool>(executionContext); string trackingToken = this.TrackingToken.Get <string>(executionContext); SendEmailRequest sendRequest = new SendEmailRequest() { EmailId = emailToBeSent.Id , IssueSend = issueSend , TrackingToken = trackingToken }; SendEmailResponse sendEmailResponse = this.OrganizationService.Execute(sendRequest) as SendEmailResponse; this.Subject.Set(executionContext, sendEmailResponse.Subject); }
/* * public void QRCode(string entityname, string recordid, string QRInfo, string noteSubject, string noteText, string fileName) * { * tracing.Trace("1"); * QRCodeEncoder encoder = new QRCodeEncoder(); * tracing.Trace("2"); * Bitmap hi = encoder.Encode(QRInfo); * tracing.Trace("3"); * string base64String = String.Empty; * tracing.Trace("4"); * using (MemoryStream ms = new MemoryStream()) * { * tracing.Trace("read stream"); * hi.Save(ms, ImageFormat.Jpeg); * * * byte[] imageBytes = ms.ToArray(); * base64String = Convert.ToBase64String(imageBytes); * } * Entity Annotation = new Entity("annotation"); * Annotation.Attributes["objectid"] = new EntityReference(entityname, new Guid(recordid)); * Annotation.Attributes["objecttypecode"] = entityname; * Annotation.Attributes["subject"] = noteSubject; * Annotation.Attributes["documentbody"] = base64String; * Annotation.Attributes["mimetype"] = @"image/jpeg"; * Annotation.Attributes["notetext"] = noteText; * Annotation.Attributes["filename"] = fileName; * service.Create(Annotation); * /* * * ------------ * * * QRCodeGenerator qrGenerator = new QRCodeGenerator(); * QRCodeData qrCodeData = qrGenerator.CreateQrCode(QRInfo, QRCodeGenerator.ECCLevel.Q); * QRCode qrCode = new QRCode(qrCodeData); * Bitmap qrCodeImage = qrCode.GetGraphic(20); * string base64String = String.Empty; * using (MemoryStream ms = new MemoryStream()) * { * switch (imageFormat) * { * case "jpg": * case "jpeg": * qrCodeImage.Save(ms, ImageFormat.Jpeg); * break; * case "bmp": * qrCodeImage.Save(ms, ImageFormat.Bmp); * break; * case "gif": * qrCodeImage.Save(ms, ImageFormat.Gif); * break; * case "png": * qrCodeImage.Save(ms, ImageFormat.Png); * break; * * } * qrCodeImage.Save(ms, ImageFormat.Jpeg); * byte[] imageBytes = ms.ToArray(); * base64String = Convert.ToBase64String(imageBytes); * } * if (noteSubject == "") * { * noteSubject = "QR"; * } * Entity Annotation = new Entity("annotation"); * Annotation.Attributes["objectid"] = new EntityReference(entityname,new Guid(recordid)); * Annotation.Attributes["objecttypecode"] = entityname; * Annotation.Attributes["subject"] = noteSubject; * Annotation.Attributes["documentbody"] = base64String; * Annotation.Attributes["mimetype"] = @"image/jpeg"; * Annotation.Attributes["notetext"] = noteText; * Annotation.Attributes["filename"] =fileName; * service.Create(Annotation); * * * * }*/ public bool SendEmailToUsersInRole(EntityReference securityRoleLookup, EntityReference email) { var userList = service.RetrieveMultiple(new FetchExpression(BuildFetchXml(securityRoleLookup.Id))); if (tracing != null) { tracing.Trace("Retrieved Data"); } Entity emailEnt = new Entity("email", email.Id); EntityCollection to = new EntityCollection(); foreach (Entity user in userList.Entities) { // Id of the user var userId = user.Id; Entity to1 = new Entity("activityparty"); to1["partyid"] = new EntityReference("systemuser", userId); to.Entities.Add(to1); } emailEnt["to"] = to; service.Update(emailEnt); SendEmailRequest req = new SendEmailRequest(); req.EmailId = email.Id; SendEmailResponse res = (SendEmailResponse)service.Execute(req); return(true); }
public static Boolean SendEmail(String From, String To, String Subject, String Text = null, String HTML = null, String emailReplyTo = null, String returnPath = null) { if (Text != null || HTML != null) { String from = From; List <String> to = To .Replace(", ", ",") .Split(',') .ToList(); Destination destination = new Destination(); destination.WithToAddresses(to); //destination.WithCcAddresses(cc); //destination.WithBccAddresses(bcc); Content subject = new Content(); subject.WithCharset("UTF-8"); subject.WithData(Subject); Body body = new Body(); if (HTML != null) { Content html = new Content(); html.WithCharset("UTF-8"); html.WithData(HTML); body.WithHtml(html); } if (Text != null) { Content text = new Content(); text.WithCharset("UTF-8"); text.WithData(Text); body.WithText(text); } Message message = new Message(); message.WithBody(body); message.WithSubject(subject); string awsAccessKey = AWSAccessKey; string awsSecretKey = AWSSecretKey; //AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]); AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(awsAccessKey, awsSecretKey); SendEmailRequest request = new SendEmailRequest(); request.WithDestination(destination); request.WithMessage(message); request.WithSource(from); if (emailReplyTo != null) { List <String> replyto = emailReplyTo .Replace(", ", ",") .Split(',') .ToList(); request.WithReplyToAddresses(replyto); } if (returnPath != null) { request.WithReturnPath(returnPath); } try { SendEmailResponse response = ses.SendEmail(request); SendEmailResult result = response.SendEmailResult; Console.WriteLine("Email sent."); Console.WriteLine(String.Format("Message ID: {0}", result.MessageId)); return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); throw; return(false); } } Console.WriteLine("Specify Text and/or HTML for the email body!"); return(false); }
protected void btnSend_Click(object sender, EventArgs e) { #region 准备接口数据 string sEmailTemplateID = this.ddlEmailTemplateList.SelectedValue; string sToIDs = this.hdnToIDs.Value; LoginUser CurrentUser = this.CurrUser; string Token = hidToken.Value; Dictionary <string, byte[]> Attachments = new Dictionary <string, byte[]>(); #region Attachments //LPWeb.BLL.Template_Email_Attachments bllTempEmailattach = new Template_Email_Attachments(); //var ds = bllTempEmailattach.GetList(" [Enabled] =1 AND TemplEmailId = " + sEmailTemplateID); LPWeb.BLL.Email_AttachmentsTemp bllEmailAttachTemp = new Email_AttachmentsTemp(); var ds = bllEmailAttachTemp.GetListWithFileImage(Convert.ToInt32(sEmailTemplateID), Token); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { foreach (DataRow item in ds.Tables[0].Rows) { try { Attachments.Add(item["Name"].ToString() + "." + item["FileType"].ToString(), (byte[])item["FileImage"]); } catch { } } } #endregion int[] ToUserIDArray = null; int[] ToContactIDArray = null; string[] ToEmailAddrArray = null; int EmailIndex = 0; int[] CCUserIDArray = null; int[] CCContactIDArray = null; string[] CCEmailAddrArray = null; if (sToIDs == string.Empty) // 如果未添加收件人,则以email template的To和CC为准发邮件 { #region use To and CC of email template #region 获取Email Template的Recipient(s) Template_Email EmailTemplateManager = new Template_Email(); DataTable RecipientList = EmailTemplateManager.GetRecipientList(Convert.ToInt32(sEmailTemplateID)); #endregion #region 获取Loan Team string sSql = "select * from LoanTeam where FileId = " + this.iLoanID; DataTable LoanTeamList = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(sSql); #endregion #region 获取Contacts string sSql2 = "select * from LoanContacts where FileId = " + this.iLoanID; DataTable ContactList = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(sSql2); #endregion Collection <Int32> ToUserIDs = new Collection <int>(); Collection <Int32> ToContactIDs = new Collection <int>(); Collection <String> ToEmailList = new Collection <String>(); Collection <Int32> CCUserIDs = new Collection <int>(); Collection <Int32> CCContactIDs = new Collection <int>(); Collection <String> CCEmailList = new Collection <String>(); #region To DataRow[] ToRecipient = RecipientList.Select("RecipientType='To'"); if (ToRecipient.Length > 0) { string sEmailList_To = ToRecipient[0]["EmailAddr"].ToString(); string sContactList_To = ToRecipient[0]["ContactRoles"].ToString(); string sUserRoleList_To = ToRecipient[0]["UserRoles"].ToString(); #region Emails if (sEmailList_To != string.Empty) { string[] EmailArray_To = sEmailList_To.Split(';'); foreach (string sEmailTo in EmailArray_To) { ToEmailList.Add(sEmailTo); } } #endregion #region User IDs if (sUserRoleList_To != string.Empty) { string[] UserRoleArray_To = sUserRoleList_To.Split(';'); foreach (string sUserRoleIDTo in UserRoleArray_To) { int iUserRoleIDTo = Convert.ToInt32(sUserRoleIDTo); DataRow[] LoanTeamRows = LoanTeamList.Select("RoleId=" + iUserRoleIDTo); foreach (DataRow LoanTeamRow in LoanTeamRows) { int iUserID = Convert.ToInt32(LoanTeamRow["UserId"]); ToUserIDs.Add(iUserID); } } } #endregion #region Contact IDs if (sContactList_To != string.Empty) { string[] ContactArray_To = sContactList_To.Split(';'); foreach (string sContactIDTo in ContactArray_To) { int iContactRoleIDTo = Convert.ToInt32(sContactIDTo); DataRow[] ContactRows = ContactList.Select("ContactRoleId=" + iContactRoleIDTo); foreach (DataRow ContactRow in ContactRows) { int iContactID = Convert.ToInt32(ContactRow["ContactId"]); ToContactIDs.Add(iContactID); } } } #endregion } #endregion #region CC DataRow[] CCRecipient = RecipientList.Select("RecipientType='CC'"); if (CCRecipient.Length > 0) { string sEmailList_CC = CCRecipient[0]["EmailAddr"].ToString(); string sContactList_CC = CCRecipient[0]["ContactRoles"].ToString(); string sUserRoleList_CC = CCRecipient[0]["UserRoles"].ToString(); #region Emails if (sEmailList_CC != string.Empty) { string[] EmailArray_CC = sEmailList_CC.Split(';'); foreach (string sEmailCC in EmailArray_CC) { CCEmailList.Add(sEmailCC); } } #endregion #region User IDs if (sUserRoleList_CC != string.Empty) { string[] UserRoleArray_CC = sUserRoleList_CC.Split(';'); foreach (string sUserRoleIDCC in UserRoleArray_CC) { int iUserRoleIDCC = Convert.ToInt32(sUserRoleIDCC); DataRow[] LoanTeamRows = LoanTeamList.Select("RoleId=" + iUserRoleIDCC); foreach (DataRow LoanTeamRow in LoanTeamRows) { int iUserID = Convert.ToInt32(LoanTeamRow["UserId"]); CCUserIDs.Add(iUserID); } } } #endregion #region Contact IDs if (sContactList_CC != string.Empty) { string[] ContactArray_CC = sContactList_CC.Split(';'); foreach (string sContactIDCC in ContactArray_CC) { int iContactRoleIDCC = Convert.ToInt32(sContactIDCC); DataRow[] ContactRows = ContactList.Select("ContactRoleId=" + iContactRoleIDCC); foreach (DataRow ContactRow in ContactRows) { int iContactID = Convert.ToInt32(ContactRow["ContactId"]); CCContactIDs.Add(iContactID); } } } #endregion } // if check me, add user's email to CC list if (this.chkCCMe.Checked == true && CurrentUser.sEmail != string.Empty) { CCEmailList.Add(CurrentUser.sEmail); } #endregion ToUserIDArray = new int[ToUserIDs.Count]; ToContactIDArray = new int[ToContactIDs.Count]; ToEmailAddrArray = new string[ToEmailList.Count]; CCUserIDArray = new int[CCUserIDs.Count]; CCContactIDArray = new int[CCContactIDs.Count]; CCEmailAddrArray = new string[CCEmailList.Count]; ToUserIDs.CopyTo(ToUserIDArray, 0); ToContactIDs.CopyTo(ToContactIDArray, 0); ToEmailList.CopyTo(ToEmailAddrArray, 0); CCUserIDs.CopyTo(CCUserIDArray, 0); CCContactIDs.CopyTo(CCContactIDArray, 0); CCEmailList.CopyTo(CCEmailAddrArray, 0); #endregion } else // 如果添加收件人,则覆盖email template的To和CC { #region build ToUserIDArray and ToContactIDArray Collection <Int32> ToUserIDs = new Collection <int>(); Collection <Int32> ToContactIDs = new Collection <int>(); string EmailAddress = ""; string UserSql = ""; string ContactSql = ""; DataTable UserTable = null; DataTable ContactTable = null; string[] ToIDArray = sToIDs.Split('$'); ToEmailAddrArray = new string[ToIDArray.Length]; foreach (string ToID in ToIDArray) { if (ToID.Contains("User") == true) { int iToUserID = Convert.ToInt32(ToID.Replace("User", "")); ToUserIDs.Add(iToUserID); UserSql = "select EmailAddress from Users where UserId = " + iToUserID; UserTable = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(UserSql); foreach (DataRow dr in UserTable.Rows) { if (dr["EmailAddress"] == DBNull.Value) { EmailAddress = ""; } else { EmailAddress = dr["EmailAddress"].ToString().Trim(); } } ToEmailAddrArray[EmailIndex] = EmailAddress; EmailIndex = EmailIndex + 1; } else { int iToContactID = Convert.ToInt32(ToID.Replace("Contact", "")); ToContactIDs.Add(iToContactID); ContactSql = "select Email from Contacts where ContactId = " + iToContactID; ContactTable = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(ContactSql); foreach (DataRow dr in ContactTable.Rows) { if (dr["Email"] == DBNull.Value) { EmailAddress = ""; } else { EmailAddress = dr["Email"].ToString().Trim(); } } ToEmailAddrArray[EmailIndex] = EmailAddress; EmailIndex = EmailIndex + 1; } } ToUserIDArray = new int[ToUserIDs.Count]; ToContactIDArray = new int[ToContactIDs.Count]; if (ToUserIDs.Count > 0) { ToUserIDs.CopyTo(ToUserIDArray, 0); } if (ToContactIDs.Count > 0) { ToContactIDs.CopyTo(ToContactIDArray, 0); } #endregion CCUserIDArray = new int[0]; CCContactIDArray = new int[0]; if (this.chkCCMe.Checked == true && CurrentUser.sEmail != string.Empty) { CCEmailAddrArray = new string[1]; CCEmailAddrArray.SetValue(CurrentUser.sEmail, 0); } else { CCEmailAddrArray = new string[0]; } } #endregion #region 调用API string sCloseDialogCodes = this.GetCloseDialogJs(); SendEmailResponse response = null; try { ServiceManager sm = new ServiceManager(); using (LP2ServiceClient service = sm.StartServiceClient()) { #region SendEmailRequest SendEmailRequest req = new SendEmailRequest(); if (this.chkUserEmailTemplate.Checked == true) { req.EmailTemplId = Convert.ToInt32(sEmailTemplateID); req.EmailSubject = string.Empty; req.EmailBody = null; req.AppendPictureSignature = false; } else { req.EmailTemplId = 0; req.EmailSubject = this.txtSubject.Text.Trim(); req.EmailBody = Encoding.UTF8.GetBytes(this.txtBody.Text.Trim()); req.AppendPictureSignature = this.chkAppendMyPic.Checked; } if (this.Request.QueryString["LoanID"] != null) { req.FileId = this.iLoanID; } else if (this.Request.QueryString["ProspectID"] != null) { req.ProspectId = this.iProspectID; } else if (this.Request.QueryString["ProspectAlertID"] != null) { req.PropsectTaskId = this.iProspectAlertID; } if ((this.Request.QueryString["LoanID"] == null) && (this.Request.QueryString["ProspectID"] != null)) { string sSql = "select * from LoanContacts where ContactId=" + req.ProspectId + " and (ContactRoleId=dbo.lpfn_GetBorrowerRoleId() or ContactRoleId=dbo.lpfn_GetCoBorrowerRoleId())"; DataTable LoanList = null; try { LoanList = LPWeb.DAL.DbHelperSQL.ExecuteDataTable(sSql); foreach (DataRow LoanListRow in LoanList.Rows) { req.FileId = (int)LoanListRow["FileId"]; } } catch { } if (LoanList == null || LoanList.Rows.Count == 0) { } } req.UserId = CurrentUser.iUserID; req.ToEmails = ToEmailAddrArray; req.ToUserIds = ToUserIDArray; req.ToContactIds = ToContactIDArray; req.CCEmails = CCEmailAddrArray; req.CCUserIds = CCUserIDArray; req.CCContactIds = CCContactIDArray; req.hdr = new ReqHdr(); #region add Attachments req.Attachments = Attachments; #endregion #endregion response = service.SendEmail(req); } } catch (System.ServiceModel.EndpointNotFoundException) { string sExMsg = string.Format("Failed to send email, reason: Email Manager is not running."); LPLog.LogMessage(LogType.Logerror, sExMsg); PageCommon.WriteJsEnd(this, sExMsg, sCloseDialogCodes); } catch (Exception ex) { string sExMsg = string.Format("Failed to send email, error: {0}", ex.Message); LPLog.LogMessage(LogType.Logerror, sExMsg); PageCommon.WriteJsEnd(this, sExMsg, sCloseDialogCodes); } #endregion // 提示调用结果 if (response.resp.Successful == true) { try { bllEmailAttachTemp.DeleteByToken(Token); } catch { } string RefreshParent = "window.parent.location.href=window.parent.location.href;"; PageCommon.WriteJsEnd(this, "Sent email successfully.", RefreshParent + sCloseDialogCodes); } else { PageCommon.WriteJsEnd(this, "Failed to send email: " + response.resp.StatusInfo.Replace("'", "\'"), sCloseDialogCodes); } }
public async Task <IActionResult> EditUser([Bind("Username", "Name", "PhoneNumber", "EmailAddress", "Role")] UserDataManagementViewModel existingUser) { bool change = false; User identity = await _context.Users.Where(u => u.Username == existingUser.Username).FirstOrDefaultAsync(); if (identity == null) { return(StatusCode(404)); } else if (existingUser.PhoneNumber == null && existingUser.EmailAddress == null) { ViewData["Alert"] = "Danger"; ViewData["Message"] = "You must specify either a Phone Number or Email Address"; existingUser.user = identity; existingUser.allRoles = await _context.Roles.ToListAsync(); return(View(existingUser)); } else { NotificationToken token = new NotificationToken { Type = Models.Type.Verify, Vaild = true, LinkedUser = identity }; if (identity.Existence == Existence.Internal && !existingUser.Username.Equals(identity.Username)) { identity.Username = existingUser.Username; change = true; } if (identity.Existence == Existence.Internal && !existingUser.Name.Equals(identity.Name)) { identity.Name = existingUser.Name; change = true; } if (!existingUser.Role.Equals("User") && identity.Existence == Existence.Internal) { Role role = await _context.Roles.Where(r => r.RoleName == existingUser.Role).FirstOrDefaultAsync(); if (identity.LinkedRole != role) { identity.LinkedRole = role; change = true; } } else if (existingUser.Role.Equals("User") && identity.Existence == Existence.Internal && identity.LinkedRole != null) { identity.LinkedRole = null; change = true; } if (existingUser.PhoneNumber != null && (identity.PhoneNumber == null || !identity.PhoneNumber.Equals(existingUser.PhoneNumber)) && (identity.OverridableField == OverridableField.PhoneNumber || identity.OverridableField == OverridableField.Both)) { identity.PhoneNumber = existingUser.PhoneNumber; identity.VerifiedPhoneNumber = false; token.Token = Areas.Internal.Controllers.AccountController.TokenGenerator(); PublishRequest SNSrequest = new PublishRequest { Message = HttpContext.User.Claims.First(c => c.Type == "name").Value + " has changed the phone number on your account. To confirm this change, please click on this link: " + "https://" + HttpContext.Request.Host + "/Internal/Account/VerifyPhoneNumber?token=" + token.Token, PhoneNumber = "+65" + identity.PhoneNumber }; SNSrequest.MessageAttributes["AWS.SNS.SMS.SenderID"] = new MessageAttributeValue { StringValue = "SmartIS", DataType = "String" }; SNSrequest.MessageAttributes["AWS.SNS.SMS.SMSType"] = new MessageAttributeValue { StringValue = "Transactional", DataType = "String" }; PublishResponse response = await _snsClient.PublishAsync(SNSrequest); if (response.HttpStatusCode != HttpStatusCode.OK) { return(StatusCode(500)); } token.Mode = Mode.SMS; _context.NotificationTokens.Add(token); change = true; } else if (existingUser.PhoneNumber == null && identity.PhoneNumber != null && (identity.OverridableField == OverridableField.PhoneNumber || identity.OverridableField == OverridableField.Both)) { identity.PhoneNumber = null; identity.VerifiedPhoneNumber = false; change = true; } if (existingUser.EmailAddress != null && (identity.EmailAddress == null || !identity.EmailAddress.Equals(existingUser.EmailAddress)) && (identity.OverridableField == OverridableField.EmailAddress || identity.OverridableField == OverridableField.Both)) { identity.EmailAddress = existingUser.EmailAddress; identity.VerifiedEmailAddress = false; token.Token = Areas.Internal.Controllers.AccountController.TokenGenerator(); SendEmailRequest SESrequest = new SendEmailRequest { Source = Environment.GetEnvironmentVariable("SES_EMAIL_FROM-ADDRESS"), Destination = new Destination { ToAddresses = new List <string> { identity.EmailAddress } }, Message = new Message { Subject = new Content("Verify your email address for SmartInsights"), Body = new Body { Text = new Content { Charset = "UTF-8", Data = "Hi " + identity.Name + ",\r\n\n" + HttpContext.User.Claims.First(c => c.Type == "name").Value + " has changed the email address on your account. To confirm this change, please click on this link: " + "https://" + HttpContext.Request.Host + "/Internal/Account/VerifyEmailAddress?token=" + token.Token + "\r\n\n\nThis is a computer-generated email, please do not reply" } } } }; SendEmailResponse response = await _sesClient.SendEmailAsync(SESrequest); if (response.HttpStatusCode != HttpStatusCode.OK) { return(StatusCode(500)); } token.Mode = Mode.EMAIL; _context.NotificationTokens.Add(token); change = true; } else if (existingUser.EmailAddress == null && identity.EmailAddress != null && (identity.OverridableField == OverridableField.EmailAddress || identity.OverridableField == OverridableField.Both)) { identity.EmailAddress = null; identity.VerifiedEmailAddress = false; change = true; } _context.Users.Update(identity); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { ViewData["Alert"] = "Danger"; ViewData["Message"] = "Something went wrong. Maybe try again?"; return(View(existingUser)); } if (change) { TempData["Message"] = "Succesfully edited " + identity.Name + "'s account details"; TempData["Alert"] = "Success"; } else { TempData["Message"] = "No changes made to " + identity.Name + "'s account details"; TempData["Alert"] = "Warning"; } return(RedirectToAction("Manage")); } }
public async Task <IActionResult> CreateUser([Bind("Username", "Name", "PhoneNumber", "EmailAddress", "Role")] UserDataManagementViewModel newUser) { if (newUser.PhoneNumber == null && newUser.EmailAddress == null) { ViewData["Alert"] = "Danger"; ViewData["Message"] = "You must specify either a Phone Number or Email Address"; newUser.allRoles = await _context.Roles.ToListAsync(); return(View(newUser)); } else { User addition = new User { Username = newUser.Username, Name = newUser.Name, Existence = Existence.Internal, Password = Password.GetRandomSalt(), Status = UserStatus.Pending, OverridableField = OverridableField.Both }; if (!newUser.Role.Equals("User")) { Role role = await _context.Roles.Where(r => r.RoleName == newUser.Role).FirstOrDefaultAsync(); addition.LinkedRole = role; } if (newUser.PhoneNumber == null) { addition.EmailAddress = newUser.EmailAddress; } else { addition.PhoneNumber = newUser.PhoneNumber; } _context.Users.Add(addition); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { ViewData["Alert"] = "Danger"; ViewData["Message"] = "Something went wrong. Maybe try again?"; return(View(newUser)); } addition = await _context.Users.Where(u => u.Username == newUser.Username).FirstOrDefaultAsync(); Settings settings = new Settings { LinkedUserID = addition.ID, LinkedUser = addition }; await _context.Settings.AddAsync(settings); NotificationToken token = new NotificationToken { Type = Models.Type.Activate, Vaild = true, LinkedUser = addition }; if (addition.EmailAddress != null) { token.Token = Areas.Internal.Controllers.AccountController.TokenGenerator(); SendEmailRequest SESrequest = new SendEmailRequest { Source = Environment.GetEnvironmentVariable("SES_EMAIL_FROM-ADDRESS"), Destination = new Destination { ToAddresses = new List <string> { addition.EmailAddress } }, Message = new Message { Subject = new Content("Welcome to SmartInsights"), Body = new Body { Text = new Content { Charset = "UTF-8", Data = "Hi " + addition.Name + ",\r\n\n" + HttpContext.User.Claims.First(c => c.Type == "name").Value + " has created an account for you on SmartInsights. Your username to login is:\r\n" + addition.Username + "\r\n\nTo enable your account, you will need to set your password and verify this email address. Please click on this link: " + "https://" + HttpContext.Request.Host + "/Internal/Account/SetPassword?token=" + token.Token + " to do so.\r\n\n\nThis is a computer-generated email, please do not reply" } } } }; SendEmailResponse response = await _sesClient.SendEmailAsync(SESrequest); if (response.HttpStatusCode != HttpStatusCode.OK) { return(StatusCode(500)); } token.Mode = Mode.EMAIL; } else { PublishRequest SNSrequest = new PublishRequest { Message = HttpContext.User.Claims.First(c => c.Type == "name").Value + " has created an account for you on SmartInsights. Your username to login is: " + addition.Username + ". Please click on this link to set your password and verify this phone number: " + "https://" + HttpContext.Request.Host + "/Internal/Account/SetPassword?token=" + token.Token, PhoneNumber = "+65" + addition.PhoneNumber }; SNSrequest.MessageAttributes["AWS.SNS.SMS.SenderID"] = new MessageAttributeValue { StringValue = "SmartIS", DataType = "String" }; SNSrequest.MessageAttributes["AWS.SNS.SMS.SMSType"] = new MessageAttributeValue { StringValue = "Transactional", DataType = "String" }; PublishResponse response = await _snsClient.PublishAsync(SNSrequest); if (response.HttpStatusCode != HttpStatusCode.OK) { return(StatusCode(500)); } token.Mode = Mode.SMS; } await _context.NotificationTokens.AddAsync(token); await _context.SaveChangesAsync(); TempData["Message"] = "Succesfully created " + addition.Name + "'s account. Please ask " + addition.Name + " to look at the email/SMS to activate the account"; TempData["Alert"] = "Success"; return(RedirectToAction("Manage")); } }