protected override void Execute(CodeActivityContext executionContext) { Boolean Logging = EnableLogging.Get(executionContext); string LogFilePath = LogFile.Get(executionContext); EntityReference Email = EmailId.Get(executionContext); try { if (Logging) Log("Workflow Execution Start", LogFilePath); IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (Logging) Log("Sending Email", LogFilePath); SendEmailRequest sendEmailreq = new SendEmailRequest(); sendEmailreq.EmailId = Email.Id; sendEmailreq.TrackingToken = ""; sendEmailreq.IssueSend = true; SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq); if (Logging) Log("Workflow Executed Successfully", LogFilePath); } catch (Exception ex) { Log(ex.Message, LogFilePath); } }
/// <summary> /// The implementation of the <see cref="Services.EmailService.ServiceContracts.ISendEmailToValidAddressService.SendEmailWithBadAddressCheck"/>. /// It validates the input request and sends an email. /// </summary> /// <param name="request">The <see cref="Services.EmailService.MessageContracts.SendEmailRequest"/> that contains the input request for sending an email to one or more recipients with one or more <see cref="Services.EmailServiceProvider.Interface.FileAttachment"/>.</param> /// <returns>A <see cref="Services.EmailService.MessageContracts.SendEmailResponseWithBadAddressCheck"/> that contains the information if the email was sent successfully along with list of invalid Recipients.</returns> /// <exception cref="System.ServiceModel.FaultException"> /// Throws <see cref="Services.CommonLibraries.Infrastructure.Faults.SystemFault"/> when any unhandled exception occours. /// </exception> /// <exception cref="System.ServiceModel.FaultException"> /// Throws this fault <see cref="Services.EmailService.FaultContracts.EmailServiceFault.ValidationFailed"/> when the <paramref name="request"/> fails validation. /// Following are the possible validation failures. /// <list type="bullet"> /// <item> /// <term><see cref="Services.EmailService.MessageContracts.SendEmailRequest.Subject"/></term> /// <description>When it is <see langword="null"/> or <see cref="System.String.Empty"/></description> /// </item> /// <item> /// <term><see cref="Services.EmailService.MessageContracts.SendEmailRequest.Body"/></term> /// <description>When it is <see langword="null"/> or <see cref="System.String.Empty"/></description> /// </item> /// <item> /// <term><see cref="Services.EmailService.MessageContracts.SendEmailRequest.FromEmailAddress"/></term> /// <description>When it is <see langword="null"/> or <see cref="System.String.Empty"/> or is an invalid email address.</description> /// </item> /// <item> /// <term><see cref="Services.EmailService.MessageContracts.SendEmailRequest.Recipients"/></term> /// <description>When it is <see langword="null"/> or empty or contains one or more invalid email addresses.</description> /// </item> /// <item> /// <term><see cref="Services.EmailService.MessageContracts.SendEmailRequest.CarbonCopyList"/></term> /// <description>When it contains one or more invalid email addresses.</description> /// </item> /// <item> /// <term><see cref="Services.EmailService.MessageContracts.SendEmailRequest.Attachments"/></term> /// <description>When it contains one or more invalid attachments that is not base 64 encoded or missing file name.</description> /// </item> /// </list> /// </exception> /// <exception cref="System.ServiceModel.FaultException"> /// Throws <see cref="Services.CommonLibraries.Infrastructure.Faults.AuthorizationFault"/> when authorization fails. /// </exception> public SendEmailWithBadAddressCheckResponse SendEmailWithBadAddressCheck(SendEmailRequest request) { SendEmailWithBadAddressCheckResponse response = null; bool result = false; try { Logger.Debug("[SendEmailWithBadAddressCheck] Validating the sessionId."); if (string.Compare(request.SessionId, _sessionToken, StringComparison.InvariantCultureIgnoreCase) != 0) { throw new InvalidSessionIdException(); } Logger.Debug("[SendEmailWithBadAddressCheck] Validating input parameters."); if (!ValidateEmailParameters(request)) { Logger.Error("[SendEmailWithBadAddressCheck] Input request is invalid."); throw new FaultException <EmailServiceFault>(EmailServiceFault.ValidationFailed, ValidationMessage); } Logger.Debug("[SendEmailWithBadAddressCheck] Sending the email."); InvalidRecipients InvalidRecipients = ValidateEmailAddress(request); //removal of Recipients from the list who have bad domains in address and mail is getting triggered to recepeints with valid domain address request.Recipients.RemoveAll(x => InvalidRecipients.BadDomains.Contains(x)); if (request.CarbonCopyList != null) { request.CarbonCopyList.RemoveAll(x => InvalidRecipients.BadDomains.Contains(x)); } if (request.Recipients != null && request.Recipients.Any()) { result = _emailServiceProvider.SendEmail(request.Subject, request.Body, request.FromEmailAddress, request.Recipients, request.CarbonCopyList, request.Attachments); } if (result) { Logger.InfoFormat("[SendEmailWithBadAddressCheck] Email was sent successfully. Result :[{0}]", result); } else { Logger.InfoFormat("[SendEmailWithBadAddressCheck] Email could not send .Please check logs for more info Result :[{0}]", result); } //List of bad domain and bad address is added to response with IsSuccess flag response = new SendEmailWithBadAddressCheckResponse { IsSuccess = result, InvalidRecipients = InvalidRecipients }; } catch (Exception ex) { Logger.FatalFormat("[SendEmailWithBadAddressCheck] Unexpected exception. Message:{0}. Stacktrace:{1}", ex, ex.Message, ex.StackTrace); throw GetFaultException(request, ex); } return(response); }
static void Main(string[] args) { if (CheckRequiredFields()) { System.Threading.Thread.Sleep(1000); Console.WriteLine("Welcome to the Console edition of the SES program."); System.Threading.Thread.Sleep(1000); Console.WriteLine("Wait a moment while I prepare things around here."); System.Threading.Thread.Sleep(3000); Console.WriteLine(""); System.Threading.Thread.Sleep(1000); Console.WriteLine("Getting Uplink...(you might want to find a good song right now.)"); System.Threading.Thread.Sleep(5000); Console.WriteLine("Ready to Rock and Roll! Just press any key and watch the magic."); Console.ReadKey(); Console.WriteLine("Emails sent:"); for (int i = 0; i < 50; i++) { Console.Write("\r{0} ", i + 1); var randSubj = new RandomString(15); using (var client = AWSClientFactory.CreateAmazonSimpleEmailServiceClient()) { var sendRequest = new SendEmailRequest { Source = senderAddress, Destination = new Destination { ToAddresses = new List <string> { receiverAddress } }, Message = new Message { Subject = new Content("Message:" + randSubj.getRandSubj()), Body = new Body { Text = new Content("Brian Murtagh sent this email..\n\n-Napster") } } }; try { var response = client.SendEmail(sendRequest); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("The email was not sent."); Console.WriteLine("Error message: " + ex.Message); break; } } } } Console.WriteLine(""); Console.Write("Press any key to exit..."); Console.ReadKey(); }
private static void BuildAndSendEmailRequest(SendEmailRequest emailRequest, string toEmail, string emailSubject, string emailBody) { emailRequest.ToEmails = toEmail; emailRequest.EmailSubject = emailSubject; emailRequest.EmailBody = emailBody; EmailComponent objemail = new EmailComponent(); objemail.SendEmail(emailRequest); }
private async Task SendAsync(SendEmailRequest request, bool retry) { if (retry) { // wait and try again await Task.Delay(2000); } await _client.SendEmailAsync(request); }
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); }
protected override void Execute(CodeActivityContext executionContext) { ITracingService tracer = executionContext.GetExtension <ITracingService>(); IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { EntityReference emailToSend = EmailToSend.Get(executionContext); EntityReference recipientTeam = RecipientTeam.Get(executionContext); bool sendEmail = SendEmail.Get(executionContext); List <Entity> ccList = new List <Entity>(); Entity email = RetrieveEmail(service, emailToSend.Id); if (email == null) { UsersAdded.Set(executionContext, 0); return; } //Add any pre-defined recipients specified to the array foreach (Entity activityParty in email.GetAttributeValue <EntityCollection>("cc").Entities) { ccList.Add(activityParty); } EntityCollection teamMembers = GetTeamMembers(service, recipientTeam.Id); ccList = ProcessUsers(service, teamMembers, ccList); //Update the email email["cc"] = ccList.ToArray(); service.Update(email); //Send if (sendEmail) { SendEmailRequest request = new SendEmailRequest { EmailId = emailToSend.Id, TrackingToken = string.Empty, IssueSend = true }; service.Execute(request); } UsersAdded.Set(executionContext, ccList.Count); } catch (Exception ex) { tracer.Trace("Exception: {0}", ex.ToString()); } }
private bool SendAmazonEmail(EMAIL_Messages entity, out string error) { error = string.Empty; try { var TO = entity.ToEmail; var SUBJECT = entity.Subject; var BODY = entity.MessageBoby; // Construct an object to contain the recipient address. var destination = new Destination { ToAddresses = new List <string> { TO } }; // Create the subject and body of the message. var subject = new Content(SUBJECT); var body = new Body { Html = new Content(BODY) }; // Create a message with the specified subject and body. var message = new Message { Subject = subject , Body = body }; // Assemble the email. var request = new SendEmailRequest { Source = FROM , Destination = destination , Message = message }; Logger.Debug("send email to " + entity.ToEmail); _setSecurityProtocol(); // Send the email. var response = _s3MailClinet.SendEmail(request); Logger.Debug($"email to {entity.ToEmail} has been sent"); return(response.HttpStatusCode == HttpStatusCode.OK); } catch (Exception ex) { error = Utils.FormatError(ex); Logger.Error("send email", entity.EmailId, ex, CommonEnums.LoggerObjectTypes.Email); return(false); } }
public static void sendSignUpAlert(string newUser) { using (var client = new AmazonSimpleEmailServiceClient(RegionEndpoint.USEast1)) { var resetHTMLBody = @"<html> <head></head> <body> <h1>New Sign Up</h1> <p>This user signed up:</p> <p><b>" + newUser + @"</b></p> </body> </html>"; var sendRequest = new SendEmailRequest { Source = "*****@*****.**", Destination = new Destination { ToAddresses = new List <string> { "*****@*****.**" } }, Message = new Message { Subject = new Content(resetSubject), Body = new Body { Html = new Content { Charset = "UTF-8", Data = resetHTMLBody }, Text = new Content { Charset = "UTF-8", Data = textBody } } }, // If you are not using a configuration set, comment // or remove the following line //ConfigurationSetName = configSet }; try { var response = client.SendEmailAsync(sendRequest); } catch (Exception ex) { var response = ex.Message; } } }
public async Task <EmailResult> SendEmailWithoutAttachment(EmailOptions options) { // Replace USWest2 with the AWS Region you're using for Amazon SES. // Acceptable values are EUWest1, USEast1, and USWest2. using (var client = new AmazonSimpleEmailServiceClient(Settings.Default.AccessKey.FromBase64(), Settings.Default.SecretKey.FromBase64(), RegionEndpoint.USEast1)) { var sendRequest = new SendEmailRequest { Source = options.From.ToString(), Destination = new Destination { ToAddresses = options.To.Select(a => a.ToString()).ToList() }, Message = new Message { Subject = new Content(options.Subject), Body = new Body { Html = options.BodyHtml ? new Content { Charset = "UTF-8", Data = options.Body } : null, Text = !options.BodyHtml ? new Content { Charset = "UTF-8", Data = options.Body } : null }, }, // If you are not using a configuration set, comment // or remove the following line //ConfigurationSetName = configSet }; try { Console.WriteLine("Sending email using Amazon SES..."); var response = await client.SendEmailAsync(sendRequest); return(new EmailResult() { EmailId = response.MessageId, StatusCode = response.HttpStatusCode.ToString() }); } catch (Exception ex) { Console.WriteLine("The email was not sent. " + ex.ToString()); return(new EmailResult() { Error = ex.ToString(), StatusCode = "500" }); } } }
public async Task <IActionResult> SendEmail([FromForm] SendEmailRequest sendEmailRequest) { var correlationId = Guid.NewGuid(); try { var sessionId = await TryGetSessionId(Request); if (string.IsNullOrEmpty(sessionId)) { return(Redirect("/")); } var model = new SaveProgressViewModel { BackLink = "/save-my-progress" }; if (!sendEmailRequest.ValidEmail) { if (string.IsNullOrWhiteSpace(sendEmailRequest.Email)) { return(Redirect("/save-my-progress/email?e=1")); } return(Redirect("/save-my-progress/email?e=2")); } NotifyResponse notifyResponse = null; try { notifyResponse = await _apiServices.SendEmail($"https://{Request.Host.Value}", sendEmailRequest.Email?.ToLower(), _appSettings.NotifyEmailTemplateId, sessionId, correlationId); if (!notifyResponse.IsSuccess) { throw new Exception(notifyResponse?.Message); } model.SentTo = sendEmailRequest.Email?.ToLower(); AppendCookie(sessionId); TempData["SentEmail"] = model.SentTo; return(RedirectToAction("EmailSent")); } catch (Exception ex) { _log.LogError(ex, $"Correlation Id: {correlationId} - Sending email in action {nameof(SendEmail)}"); return(Redirect("/save-my-progress/email?e=3")); } } catch (Exception ex) { _log.LogError(ex, $"Correlation Id: {correlationId} - An error occurred rendering action {nameof(SendEmail)}"); return(RedirectToAction("Error500", "Error")); } }
public Task Execute(string email, string subject, string message) { _logger.LogDebug("Send email execute"); Task response = null; using (var client = new AmazonSimpleEmailServiceClient(Options.AWSAccessKeyId, Options.AWSSecretAccessKey, RegionEndpoint.USEast1)) { var replyToAddresses = new List <string>(); replyToAddresses.Add(Options.EmailReplyto); var destinationAddresses = new List <string>(); destinationAddresses.Add(email); SendEmailRequest sendRequest = new SendEmailRequest { Source = Options.EmailFrom, ReplyToAddresses = replyToAddresses, Destination = new Destination { ToAddresses = destinationAddresses }, Message = new Message { Subject = new Content(subject), Body = new Body { Html = new Content { Charset = "UTF-8", Data = message }, Text = new Content { Charset = "UTF-8", Data = message } } } }; try { _logger.LogInformation("Sending email using Amazon SES..."); response = client.SendEmailAsync(sendRequest); _logger.LogInformation("The email was sent successfully."); } catch (Exception ex) { _logger.LogWarning("The email was not sent."); _logger.LogError("Error message: " + ex.Message); } } return(response); }
public static void SendMailToResourceImpoter(DataTable dt_unprocessed, string totalCount, decimal TL, decimal Dolar, decimal Euro, IOrganizationService service) { try { string errorHtml = string.Empty; StringBuilder sb = new StringBuilder(); if (dt_unprocessed.Rows.Count != 0) { errorHtml = ConvertDtToHtmlTable(dt_unprocessed); } sb.AppendLine("Toplam " + totalCount + " Adet Satış " + String.Format("{0:0,0.00}", TL) + " TL ve " + String.Format("{0:0,0.00}", Dolar) + " $ ve " + String.Format("{0:0,0.00}", Euro) + " € 'dur"); sb.AppendLine(errorHtml); #region Create Email Entity fromParty = new Entity("activityparty"); fromParty["partyid"] = new EntityReference("systemuser", Globals.AdministratorId); Entity toParty = new Entity("activityparty"); toParty["addressused"] = "*****@*****.**"; //Entity toParty = new Entity("activityparty"); //toParty["addressused"] = "*****@*****.**"; Entity email = new Entity("email"); email["to"] = new Entity[] { toParty }; email["from"] = new Entity[] { fromParty }; email["subject"] = DateTime.Now.AddDays(-1).Date.ToString("dd/MM/yyyy") + " Tarihli Satışlar"; email["description"] = sb.ToString(); email["directioncode"] = true; Guid id = service.Create(email); #endregion #region Send Email var req = new SendEmailRequest { EmailId = id, TrackingToken = string.Empty, IssueSend = true }; try { var res = (SendEmailResponse)service.Execute(req); } catch (Exception ex) { } #endregion } catch (Exception ex) { } }
public void Execute(IServiceProvider serviceProvider) { // Context data var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext; var factory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory; var trace = serviceProvider.GetService(typeof(ITracingService)) as ITracingService; var quote = context.InputParameters.ContainsKey("Target") ? context.InputParameters["Target"] as Entity : null; var service = factory.CreateOrganizationService(context.InitiatingUserId); // Gate checks if (context.Depth > 1 || !context.PrimaryEntityName.Equals("xms_gift") || quote == null) { trace.Trace("Error in Gate Checks"); return; } // Gift references var goodKid = quote.GetAttributeValue <EntityReference>("xms_kid"); var product = quote.GetAttributeValue <EntityReference>("xms_product"); var userName = service.Retrieve(goodKid.LogicalName, goodKid.Id, new ColumnSet("governmentid")).GetAttributeValue <string>("governmentid"); var productEntity = service.Retrieve(product.LogicalName, product.Id, new ColumnSet("productnumber", "name")); var productCode = productEntity.GetAttributeValue <string>("productnumber"); var productName = productEntity.GetAttributeValue <string>("name"); // Email subjects var fromParty = new Entity("activityparty"); fromParty["partyid"] = new EntityReference("systemuser", context.InitiatingUserId); var toPartyContacts = new Entity("activityparty"); toPartyContacts["partyid"] = goodKid; try { // Feedback email entity var email = new Entity("email"); email["from"] = new Entity[] { fromParty }; email["to"] = new Entity[] { toPartyContacts }; email["subject"] = $"Feedback requested for gift: {productName} / "; email["description"] = $"Please provide your feedback <a href='https://xmasdevfeedback.azurewebsites.net/Home/Index/{userName}/{productCode}'>here</a>"; var emailId = service.Create(email); // Email send var request = new SendEmailRequest { EmailId = emailId, IssueSend = true }; var response = service.Execute(request) as SendEmailResponse; } catch (Exception ex) { trace.Trace(ex.Message); } }
public async Task <IActionResult> NotifyAccountStatusChanged(string id, bool isBanned) { var ret = false; if (id == null) { return(Json(ret)); } var user = _userService.GetUserProfile(id); if (user == null) { return(Json(ret)); } var isAccountLocked = _userService.IsAccountLocked(user); ret = true; try { var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new EmailManager.EmailManagerClient(channel); var request = new SendEmailRequest { Email = user.Email, }; if (isBanned && isAccountLocked) { request.Subject = "Account lock"; request.Message = "Your account has been locked due to not completing your tasks in time."; } else if (!isBanned && !isAccountLocked) { request.Subject = "Account unlock"; request.Message = "Your account has been unlocked!"; } else { return(Json(ret)); } var response = await client.SendEmailAsync(request); ret = response.Status == EmailService.Status.Ok; } catch (Exception) { ret = false; } return(Json(ret)); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } Guid primaryEntityId = localContext.WorkflowExecutionContext.PrimaryEntityId; EntityReference emailToSend = EmailToSend.Get(context); EntityReference connectionRole = ConnectionRole.Get(context); bool includeOpposite = IncludeOppositeConnection.Get(context); bool sendEmail = SendEmail.Get(context); List <Entity> toList = new List <Entity>(); Entity email = RetrieveEmail(localContext.OrganizationService, emailToSend.Id); if (email == null) { UsersAdded.Set(context, 0); return; } //Add any pre-defined recipients specified to the array foreach (Entity activityParty in email.GetAttributeValue <EntityCollection>("to").Entities) { toList.Add(activityParty); } EntityCollection records = GetConnectedRecords(localContext.OrganizationService, primaryEntityId, connectionRole.Id, includeOpposite); toList = ProcessRecords(localContext.OrganizationService, records, toList, primaryEntityId); //Update the email email["to"] = toList.ToArray(); localContext.OrganizationService.Update(email); //Send if (sendEmail) { SendEmailRequest request = new SendEmailRequest { EmailId = emailToSend.Id, TrackingToken = string.Empty, IssueSend = true }; localContext.OrganizationService.Execute(request); } UsersAdded.Set(context, toList.Count); }
public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { try { context.Logger.LogLine($"Event ID: {record.EventID}"); context.Logger.LogLine($"Event Name: {record.EventName}"); var oldVersion = ConvertToTODOList(record.Dynamodb.OldImage); var newVersion = ConvertToTODOList(record.Dynamodb.NewImage); var emailsToTasks = CompareVersions(oldVersion, newVersion); foreach (var kvp in emailsToTasks) { var emailBody = CreateEmailBody(kvp.Value); var request = new SendEmailRequest { Source = fromEmail, Destination = new Destination { ToAddresses = new List <string> { kvp.Key } }, Message = new Message { Subject = new Content { Data = "New tasks have been assigned to you." }, Body = new Body { Text = new Content { Data = emailBody } } } }; await this.SESClient.SendEmailAsync(request); context.Logger.LogLine($"Sent email to {request.Destination.ToAddresses[0]} from {request.Source}"); context.Logger.LogLine(emailBody); } } catch (Exception e) { context.Logger.LogLine($"Error processing record: {e.Message}"); context.Logger.LogLine(e.StackTrace); } } context.Logger.LogLine("Stream processing complete."); }
public async Task <NotifierResponse> Notify(SendEmailSNSRequest request) { var lambdaresponse = new NotifierResponse { ResponseData = "Failed" }; var configSet = Configuration["configSet"]; using (var client = new AmazonSimpleEmailServiceClient()) { var sendRequest = new SendEmailRequest { Source = request.From, Destination = new Destination { ToAddresses = request.To.ToList() }, Message = new Message { Subject = new Content(request.Subject), Body = new Body { Html = new Content { Charset = "UTF-8", Data = request.HtmlBody }, Text = new Content { Charset = "UTF-8", Data = request.Body } } }, // If you are not using a configuration set, comment // or remove the following line ConfigurationSetName = configSet }; try { Console.WriteLine("Sending email using Amazon SES..."); var response = await client.SendEmailAsync(sendRequest).ConfigureAwait(false); Console.WriteLine("The email was sent successfully."); lambdaresponse.ResponseData = "Success"; } catch (Exception ex) { Console.WriteLine("The email was not sent."); Console.WriteLine("Error message: " + ex.Message); } return(lambdaresponse); } }
public SendEmailResponse SendEmail(SendEmailRequest request) { var response = _emailSender.SendEmailAsync(request, 0, null).Result.LinkTo(request); response.Message = response.Result.Type.Equals(ProcessResultType.Ok) ? request.MessageSuccessfulSending : request.MessageFailedSending; return(response); }
public void SendMessage(IMessageInfo message) { AmazonSimpleEmailServiceClient client = InitializeClient(); using (client) { SendEmailRequest request = CreateSendRequest(message); client.SendEmail(request); } }
private static void BuildAndSendEmailRequest(SendEmailRequest emailRequest, string toEmail, string emailSubject, string emailBody) { Log.Error("call BookOrChangeAppointment BC"); emailRequest.ToEmails = toEmail; emailRequest.EmailSubject = emailSubject; emailRequest.EmailBody = emailBody; EmailComponent objemail = new EmailComponent(); objemail.SendEmail(emailRequest); }
public async Task SendEmail(SendEmailRequest request) { var result = validator.Validate(request); if (!result) { throw new ArgumentException(nameof(request)); } await notificationServiceV3.SendEmail(request); }
public async Task SendEmail(SendEmailRequest request) { var result = validator.Validate(request); if (!result) { throw new ArgumentException(nameof(request)); } await emailService.Send(request.FromEmail, request.ToEmail); }
/// <inheritdoc /> protected override void Execute(Context context) { var emailRef = Email.Get(context); var request = new SendEmailRequest { EmailId = emailRef.Id, TrackingToken = "", IssueSend = true }; var service = ExecureAsSystem.Get(context) ? context.SystemService : context.Service; service.Execute(request); }
public async Task <IActionResult> PostEmail([FromBody] SendEmailRequest request, CancellationToken cancellationToken) { Logger.LogInformation(JsonConvert.SerializeObject(request)); SendEmailCommand command = SendEmailCommand.Create(request); await this.CommandRouter.Route(command, cancellationToken); return(this.Ok(command.Response)); }
/// <summary> /// Sending Email /// </summary> /// <param name="request"></param> /// <returns></returns> public SendEmailResponse SendEmail(SendEmailRequest request) { Logger.Current.Informational("In Send Email method"); SendEmailResponse response = new SendEmailResponse(); response.Success = false; string toEmail = string.Empty; string emailBody = string.Empty; string subject = "Coupon Report - Response - GrabOn Team"; bool success = false; IDictionary <int, bool> emailStatus = new Dictionary <int, bool>(); string[] formSubmissionIds = request.FormSubmissionIds.ToArray(); IList <InvalidCouponEnagedFrom> invalidCouponEngatedcontacts = new List <InvalidCouponEnagedFrom>(); IEnumerable <Person> contacts = contactRepository.GetEmailById(request.Contacts); foreach (var contact in contacts) { toEmail = contact.Email; emailBody = string.Format("Hi {0} {1}, <br> {2}", contact.FirstName, contact.LastName, request.EmailBody); success = EmailSend(subject, emailBody, toEmail, request.AccountId, request.RequestedBy.Value); if (!emailStatus.ContainsKey(contact.Id)) { emailStatus.Add(contact.Id, success); } } if (emailStatus != null) { var sucessContacts = emailStatus.Where(k => k.Value).Select(k => k.Key); if (sucessContacts.IsAny()) { contactRepository.UpdateContactLastTouchedThrough(sucessContacts, request.AccountId); foreach (int conId in sucessContacts) { int index = Array.IndexOf(request.Contacts.ToArray(), conId); string formSubmissionId = formSubmissionIds[index]; int[] submisionIds = formSubmissionId.Split(',').Select(x => int.Parse(x)).ToArray(); foreach (int fmId in submisionIds) { InvalidCouponEnagedFrom invalidCouponEngatedData = new InvalidCouponEnagedFrom(); invalidCouponEngatedData.ContactId = conId; invalidCouponEngatedData.FormSubmissionId = fmId; invalidCouponEngatedcontacts.Add(invalidCouponEngatedData); } } enterpriseServiceRepository.BulkInvalidCouponEngagedContacts(invalidCouponEngatedcontacts); } } response.Success = emailStatus.Where(k => !k.Value).Any() ? false : true; response.Message = response.Success ? "Email sent to all selected contacts" : "Email sent to partial list of selected contacts"; return(response); }
/// <summary> /// Sends an email (specified per Email class properties) using AWS Simple Email Service /// </summary> /// <returns> email send success (boolean) </returns> public async Task <bool> Send() { bool status = false; { using (var client = new AmazonSimpleEmailServiceClient(RegionEndpoint.USWest2)) { var sendRequest = new SendEmailRequest { Source = Sender, Destination = new Destination { ToAddresses = new List <string> { Recipient } }, Message = new Message { Subject = new Content(Subject), Body = new Body { Html = new Content { Charset = "UTF-8", Data = BodyHtml }, Text = new Content { Charset = "UTF-8", Data = BodyText } } }, // If you are not using a configuration set, comment // or remove the following line // ConfigurationSetName = ConfigSet }; try { Console.WriteLine("Sending email using Amazon SES..."); var response = await client.SendEmailAsync(sendRequest); status = true; Console.WriteLine("The email was sent successfully."); } catch (Exception ex) { Console.WriteLine("The email was not sent."); Console.WriteLine("Error message: " + ex.Message); } } return(status); } }
public async Task <GeneralResponse> SendEmail(User user) { var roles = await _userManager.GetRolesAsync(user); var role = roles.Contains(RoleConstants.APPLICANT) ? "Applicant" : "Client"; var totalUsersInRole = await _userManager.GetUsersInRoleAsync(role); using (var client = new AmazonSimpleEmailServiceClient(new EnvironmentVariablesAWSCredentials(), RegionEndpoint.USWest2)) { var sendRequest = new SendEmailRequest { Source = ConstantStrings.EMAIL_SENDER, Destination = new Destination { ToAddresses = new List <string> { ConstantStrings.EMAIL_RECIEVER } }, Message = new Message { Subject = new Content("New user registration"), Body = new Body { Html = new Content { Charset = "UTF-8", Data = await _emailTemplate.NewUserTemplate(user) }, Text = new Content { Charset = "UTF-8", Data = $"New {role} has just registered!" + $"Dear Admin," + $"This email was sent to you to notify when a user is registered on your website." + $"The new {role} with email {user.Email} became the {totalUsersInRole.Count + " "}{role} on your application!" } } }, }; var emailResponse = new SendEmailResponse(); var generalResponse = new GeneralResponse(); try { emailResponse = await client.SendEmailAsync(sendRequest); generalResponse.Succeeded = true; return(generalResponse); } catch (Exception e) { return(generalResponse.ErrorHandling <EmailSenderManager>(emailResponse.MessageId, objects: (sendRequest, e))); } } }
private string SendEmail(int ContactID, int UserID, byte[] EmailBody) { string ReturnMessage = string.Empty; ServiceManager sm = new ServiceManager(); LPWeb.BLL.Loans _bLoan = new LPWeb.BLL.Loans(); using (LP2ServiceClient service = sm.StartServiceClient()) { SendEmailRequest req = new SendEmailRequest(); req.hdr = new ReqHdr(); req.hdr.SecurityToken = "SecurityToken"; //todo:check dummy data req.hdr.UserId = this.CurrUser.iUserID; req.EmailBody = EmailBody; req.EmailSubject = string.Format("Loan Status Report for {0}'s loan", _bLoan.GetLoanBorrowerName(iLoanID)); req.UserId = this.CurrUser.iUserID; if (ContactID > 0) { req.ToContactIds = new int[1] { ContactID }; } if (UserID > 0) { req.ToUserIds = new int[1] { UserID }; } SendEmailResponse respone = null; try { respone = service.SendEmail(req); if (respone.resp.Successful) { ReturnMessage = string.Empty; } else { ReturnMessage = respone.resp.StatusInfo; } } catch (System.ServiceModel.EndpointNotFoundException) { string sExMsg = string.Format("Failed to send email, reason: Email Manager is not running."); LPLog.LogMessage(LogType.Logerror, sExMsg); } catch (Exception ex) { string sExMsg = string.Format("Failed to send email, error: {0}", ex.Message); LPLog.LogMessage(LogType.Logerror, sExMsg); } return(ReturnMessage); } }
void SendEmail(Guid? emailId) { if (emailId == null) throw new ArgumentNullException("no email created"); SendEmailRequest request = new SendEmailRequest { EmailId = emailId.Value, TrackingToken = string.Empty, IssueSend = true }; _service.Execute(request); }
/// <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) { return(new SendEmailResponse { RequestId = "requestid", EmailId = "emailid", ApiStatusCode = HttpStatusCode.OK, Error = String.Empty, ErrorCode = String.Empty }); }
public void SendEmail(IOrganizationService service, Entity entity) { var sendEmailRequest = new SendEmailRequest { EmailId = entity.Id, TrackingToken = String.Empty, IssueSend = true }; service.Execute(sendEmailRequest); }
/// <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; } }
/// <summary> /// Checks if the "Est. Close Date" is greater than 10 days. If it is, /// send an email to the administrator so that s/he can verify close date /// with the owner of the opportunity. /// </summary> protected override void Execute(CodeActivityContext executionContext) { IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // Get opportunity entity Entity opportunity = service.Retrieve("opportunity", this.inputOpportunity.Get(executionContext).Id, new ColumnSet("estimatedclosedate")); // Calulate 10 days from today DateTime todayPlusTen = DateTime.UtcNow.AddDays(10.0); // Check "Est. Close Date" if (opportunity.Contains("estimatedclosedate")) { DateTime estCloseDate = (DateTime)opportunity["estimatedclosedate"]; if (DateTime.Compare(estCloseDate, todayPlusTen) > 0) { // Need system user id for activity party WhoAmIRequest systemUserRequest = new WhoAmIRequest(); WhoAmIResponse systemUser = (WhoAmIResponse)service.Execute(systemUserRequest); // Create an activity party for the email Entity[] activityParty = new Entity[1]; activityParty[0] = new Entity("activityparty"); activityParty[0]["partyid"] = new EntityReference("systemuser", systemUser.UserId); // Create an email message Entity email = new Entity("email"); email.LogicalName = "email"; email["subject"] = "Warning: Close date has been extended more than 10 days."; email["description"] = "Verify close date is correct."; email["to"] = activityParty; email["from"] = activityParty; email["regardingobjectid"] = opportunity.ToEntityReference(); Guid emailId = service.Create(email); // Send email SendEmailRequest sendEmailRequest = new SendEmailRequest(); sendEmailRequest.EmailId = emailId; sendEmailRequest.IssueSend = true; sendEmailRequest.TrackingToken = ""; SendEmailResponse sendEmailResponse = (SendEmailResponse)service.Execute(sendEmailRequest); } } }
private void SendEmail(List<ProxyToSendEmailExtended> listSales, IOrganizationService service, byte whatDay) { var Agreements = getAgreements(); foreach (var item in Agreements) { Email mail = new Email(); mail.Subject = "Просьба согласовать Договор либо внести комментарии"; string link = string.Empty; var current = from p in listSales where Equals(p.agreementLaw, item) || Equals(p.agreementLog, item) || Equals(p.agreementFin, item) || Equals(p.agreementAc, item) || Equals(p.agreementSd, item) select p; if (current.Count() == 0) continue; foreach (var colection in current) { link += string.Format("<p class='MsoNormal'><i><u><span lang='RU' style='color:rgb(0,112,192)'>" + /*"<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etc=SalesOrder&extraqs=%3f_gridType%3d4212%26etc%3d4212%26id%3d%257b{0}" + "%257d%26preloadcache%3d1406639059288%26rskey%3d307497509&histKey=417657088&newWindow=true&pagetype=entityrecord>{1}</a></span></u></i></p>",*/ "<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etn=SalesOrder&pagetype=entityrecord&id=%7b{0}%7d>{1}</a></span></u></i></p>", colection.recordId.ToString(), colection.Name.ToString()); } switch (whatDay) { case 0: mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'> <p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования договора(ов) истекает завтра. Просьба согласовать Договор либо внести комментарии.</span><o:p></o:p></p> <p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p> <br></div>", link.ToString()); break; case 1: mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'> <p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования договора(ов) истекает сегодня. Просьба согласовать Договор либо внести комментарии.</span><o:p></o:p></p> <p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p> <br></div>", link.ToString()); break; } mail.DirectionCode = true; SystemUser user = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, item.Id, new ColumnSet("fullname", "internalemailaddress")); if (user.InternalEMailAddress == null) continue; var activityParty1 = new ActivityParty { AddressUsed = user.InternalEMailAddress }; var activityParty2 = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, new Guid("C49FE2C3-FB35-E511-80D7-005056820ECA")), }; mail.From = new[] { activityParty2 }; mail.To = new[] { activityParty1 }; Guid createdEmailId = service.Create(mail); var sendEmailreq = new SendEmailRequest { EmailId = createdEmailId, TrackingToken = "", IssueSend = true }; try { service.Execute(sendEmailreq); } catch (Exception) { } } }
public void SendEmail(Guid emailId) { var request = new SendEmailRequest() { EmailId = emailId, TrackingToken = "", IssueSend = true }; Execute(request); }
private void SendEmail(List<EmailProxy> listData) { using (var orgContext = new OrganizationServiceContext(service)) { try { foreach (var item in listData) { Email unloadEmail = new Email(); var client = (Invoice)service.Retrieve(Invoice.EntityLogicalName, item.InvoiceId, new ColumnSet("customerid")); //Тема письма: «Уведомление о неотгруженном в срок заказе. //Сущность - invoice поле new_invoice_number, Сущность - invoice поле - customerid unloadEmail.Subject = string.Format("Уведомление о неотгруженном в срок заказе. {0} , {1}", item.NumberInvoice, client.CustomerId == null ? "" : client.CustomerId.Name); //Заказы по нижеуказанным данным не поступили в ожидаемый срок. //Сущность invoicedetail, Сущность invoicedetail поле new_sopplierid, Сущность invoicedetail поле new_sopplierid_invoice_supplier //Требуемые действия Логиста: //1) связаться с поставщиком для решения вопроса с поставкой //2) предоставить ответственному менеджеру информацию о причинах задержки и обновленной дате отгрузки заказа //Требуемые действия ответственного менеджера: //1) связаться с заказчиком, извиниться и сообщить о задержке заказа предоставив информацию о новых датах отгрузки //link ----<http://crm2011:5555/SoftlineInternationalLtd/userdefined/edit.aspx?etc=1091&id=%7b{0}%7d> string link = string.Format(/*@"<p class='MsoNormal'><i><u><span lang='RU' style='color:rgb(0,112,192)'>" +*/ @"<a href=http://crm2011:5555/SoftlineInternationalLtd/userdefined/edit.aspx?etc=1091&id=%7b{0}%7d>{1}</a></span></u></i></p>", item.InvoiceDetail.Id.ToString(), item.Product); unloadEmail.Description = string.Format(@"<div id=':1df' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст повідомлення' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 240px;'><p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><b><i><span style='color: black;'>Заказы по нижеуказанным данным не поступили в ожидаемый срок.</span></i></b></p> <p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><span lang='EN-US' style='color: black;'>{0}, {1}</span><span lang='EN-US' style='color: black;'>, {2}</span></p> <p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><b><i><span style='color: black;'>Требуемые действия Логиста: </span></i></b></p> <p style='background-image: initial; background-repeat: initial;'><span style='color: black;'>1)</span><span style='color: rgb(40, 40, 40);'> </span><span style='color: black;'>связаться с поставщиком для решения вопроса с поставкой</span><span style='color: rgb(40, 40, 40);'></span></p> <p style='background-image: initial; background-repeat: initial;'><span style='color: black;'>2)</span><span style='color: rgb(40, 40, 40);'> </span><span style='color: black;'>предоставить ответственному менеджеру информацию о причинах задержки и обновленной дате отгрузки заказа</span></p> <p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><b><i><span style='color: black;'>Требуемые действия ответственного менеджера: </span></i></b><span style='color: rgb(40, 40, 40);'></span></p> <p style='background-image: initial; background-repeat: initial;'><span style='color: black;'>1)</span><span style='color: rgb(40, 40, 40);'> </span><span style='color: black;'>связаться с заказчиком, извиниться и сообщить о задержке заказа предоставив информацию о новых датах отгрузки</span><span style='color: rgb(40, 40, 40);'></span></p><p style='background-image: initial; background-repeat: initial;'><span style='color: rgb(40, 40, 40);'>Ссылка для перехода - {3}</span><span style='color: black;'><br></span></p></div>" , item.Product, item.InvoiceAccount == null ? "" : item.InvoiceAccount.Name, item.Number, link); unloadEmail.DirectionCode = true; SystemUser user = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, item.EntityOwner.Id, new ColumnSet("internalemailaddress")); if (user.InternalEMailAddress == null) { Log.AddLog(string.Format("Адрес Електроной почты отсутствует... ({0})", item.EntityOwner.Name)); continue; } var activity1 = new ActivityParty { AddressUsed = user.InternalEMailAddress }; var activity2 = new ActivityParty { AddressUsed = @"*****@*****.**" }; unloadEmail.To = new[] { activity1 }; unloadEmail.Cc = new[] { activity2 }; Guid createdEmailId = service.Create(unloadEmail); service.Update(new InvoiceDetail { Id = item.InvoiceDetail.Id, new_shipping = true }); var sendEmailreq = new SendEmailRequest { EmailId = createdEmailId, TrackingToken = "", IssueSend = true }; try { service.Execute(sendEmailreq); } catch (Exception ex) { Log.AddLog(ex.Message); } } } catch (Exception ex) { Log.AddLog(ex.Message); } } }