static void Main(string[] args) { var emailService = new AlphaMailEmailService("YOUR-ACCOUNT-API-TOKEN-HERE"); var message = new { Message = "Hello world like a boss!", SomeOtherMessage = "And to the rest of the world! Chíkmàa! مرحبا! नमस्ते! Dumelang!" }; var payload = new EmailMessagePayload() .SetProjectId(12345) // The id of the project your want to send with .SetSender(new EmailContact("Sender Company Name", "*****@*****.**")) .SetReceiver(new EmailContact("Joe E. Receiver", "*****@*****.**")) .SetBodyObject(message); try { var response = emailService.Queue(payload); Console.WriteLine("Mail successfully sent! ID = {0}", response.Result); } catch (AlphaMailServiceException exception) { Console.WriteLine("Error! {0} ({1})", exception.Message, exception.GetErrorCode()); } Console.ReadLine(); }
/// <summary> /// Processes the notification items as individual tasks. /// </summary> /// <param name="applicationName">The application Name.</param> /// <param name="notificationEntities">List of notification entities to process.</param> /// <param name="emailAccountUsed">Email account used to process the notifications.</param> private async Task ProcessEntitiesIndividually(string applicationName, IList <EmailNotificationItemEntity> notificationEntities, Tuple <AuthenticationHeaderValue, AccountCredential> emailAccountUsed) { var traceProps = new Dictionary <string, string>(); traceProps[AIConstants.Application] = applicationName; this.logger.TraceInformation($"Started {nameof(this.ProcessEntitiesIndividually)} method of {nameof(MSGraphNotificationProvider)}.", traceProps); List <Task> emailNotificationSendTasks = new List <Task>(); foreach (var item in notificationEntities) { item.EmailAccountUsed = emailAccountUsed.Item2.AccountName; item.TryCount++; item.ErrorMessage = string.Empty; // Reset the error message on next retry. try { var sendForReal = this.mailSettings.Find(a => a.ApplicationName == applicationName).SendForReal; var toOverride = this.mailSettings.Find(a => a.ApplicationName == applicationName).ToOverride; var saveToSent = this.mailSettings.Find(a => a.ApplicationName == applicationName).SaveToSent; MessageBody body = await this.emailManager.GetNotificationMessageBodyAsync(applicationName, item).ConfigureAwait(false); EmailMessage message = item.ToGraphEmailMessage(body); if (!sendForReal) { this.logger.TraceInformation($"Overriding the ToRecipients in {nameof(this.ProcessEntitiesIndividually)} method of {nameof(EmailManager)}.", traceProps); message.ToRecipients = toOverride.Split(Common.ApplicationConstants.SplitCharacter, System.StringSplitOptions.RemoveEmptyEntries).Select(torecipient => new Recipient { EmailAddress = new EmailAddress { Address = torecipient } }).ToList(); message.CCRecipients = null; message.BCCRecipients = null; message.ReplyToRecipients = null; } EmailMessagePayload payLoad = new EmailMessagePayload(message) { SaveToSentItems = saveToSent }; var isSuccess = await this.msGraphProvider.SendEmailNotification(emailAccountUsed.Item1, payLoad, item.NotificationId).ConfigureAwait(false); item.Status = isSuccess ? NotificationItemStatus.Sent : (item.TryCount <= this.maxTryCount ? NotificationItemStatus.Retrying : NotificationItemStatus.Failed); } catch (AggregateException ex) { item.Status = NotificationItemStatus.Failed; item.ErrorMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } } this.logger.TraceInformation($"Finished {nameof(this.ProcessEntitiesIndividually)} method of {nameof(MSGraphNotificationProvider)}.", traceProps); }
internal static InternalEmailMessagePayload Map(EmailMessagePayload payload) { return new InternalEmailMessagePayload() { project_id = payload.ProjectId, receiver_id = payload.ReceiverId, receiver_email = payload.ReceiverEmail, receiver_name = payload.ReceiverName, sender_email = payload.SenderEmail, sender_name = payload.SenderName, body = payload.Body }; }
internal static InternalEmailMessagePayload Map(EmailMessagePayload payload) { return new InternalEmailMessagePayload() { project_id = payload.ProjectId, sender = new InternalEmailSender() { name = payload.SenderName ?? "", email = payload.SenderEmail ?? "" }, receiver = new InternalEmailReceiver() { id = payload.ReceiverId ?? "", name = payload.ReceiverName ?? "", email = payload.ReceiverEmail ?? "" }, payload = payload.Body ?? new {} }; }
/// <inheritdoc/> public async Task <bool> SendEmailNotification(AuthenticationHeaderValue authenticationHeaderValue, EmailMessagePayload payLoad, string notificationId) { this.logger.TraceInformation($"Started {nameof(this.SendEmailNotification)} method of {nameof(MSGraphProvider)}."); this.httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue; var requestPayLoad = JsonConvert.SerializeObject(payLoad, this.jsonSerializerSettings); HttpResponseMessage response = null; bool isSuccess = false; response = await this.httpClient.PostAsync( $"{this.mSGraphSetting.BaseUrl}/{this.mSGraphSetting.GraphAPIVersion}/{this.mSGraphSetting.SendMailUrl}", new StringContent(requestPayLoad, Encoding.UTF8, ApplicationConstants.JsonMIMEType)).ConfigureAwait(false); this.logger.TraceInformation($"Method {nameof(this.SendEmailNotification)}: Completed Graph Send Email Call."); var responseHeaders = response.Headers.ToString(); if (response.IsSuccessStatusCode) { // Read and deserialize response. var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); isSuccess = true; } else if (response.StatusCode == HttpStatusCode.TooManyRequests || response.StatusCode == HttpStatusCode.RequestTimeout) { isSuccess = false; } else { string content = string.Empty; if (response != null) { content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } throw new System.Exception($"An error occurred while sending notification id: {notificationId}. Details: {content}"); } this.logger.TraceInformation($"Finished {nameof(this.SendEmailNotification)} method of {nameof(MSGraphProvider)}."); return(isSuccess); }
/// <inheritdoc/> public async Task <ResponseData <string> > SendEmailNotification(AuthenticationHeaderValue authenticationHeaderValue, EmailMessagePayload payLoad, string notificationId) { this.logger.TraceInformation($"Started {nameof(this.SendEmailNotification)} method of {nameof(MSGraphProvider)}."); this.httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue; var requestPayLoad = JsonConvert.SerializeObject(payLoad, this.jsonSerializerSettings); HttpResponseMessage response = null; response = await this.httpClient.PostAsync( $"{this.mSGraphSetting.BaseUrl}/{this.mSGraphSetting.GraphAPIVersion}/{this.mSGraphSetting.SendMailUrl}", new StringContent(requestPayLoad, Encoding.UTF8, ApplicationConstants.JsonMIMEType)).ConfigureAwait(false); this.logger.TraceInformation($"Method {nameof(this.SendEmailNotification)}: Completed Graph Send Email Call for notificationId : {notificationId}"); var responseData = await GetResponseData(response).ConfigureAwait(false); if (responseData == null || (!responseData.Status && !(responseData.StatusCode == HttpStatusCode.TooManyRequests || responseData.StatusCode == HttpStatusCode.RequestTimeout))) { throw new System.Exception($"An error occurred while sending notification id: {notificationId}. Details: {responseData?.Result}"); } this.logger.TraceInformation($"Finished {nameof(this.SendEmailNotification)} method of {nameof(MSGraphProvider)}."); return(responseData); }
/// <summary> /// Processes the notification items as individual tasks. /// </summary> /// <param name="applicationName">The application Name.</param> /// <param name="notificationEntities">List of notification entities to process.</param> /// <param name="emailAccountUsed">Email account used to process the notifications.</param> private async Task ProcessEntitiesIndividually(string applicationName, IList <EmailNotificationItemEntity> notificationEntities, Tuple <AuthenticationHeaderValue, AccountCredential> emailAccountUsed) { var traceProps = new Dictionary <string, string>(); traceProps[AIConstants.Application] = applicationName; this.logger.TraceInformation($"Started {nameof(this.ProcessEntitiesIndividually)} method of {nameof(MSGraphNotificationProvider)}.", traceProps); List <Task> emailNotificationSendTasks = new List <Task>(); foreach (var item in notificationEntities) { item.EmailAccountUsed = emailAccountUsed.Item2.AccountName; item.TryCount++; item.ErrorMessage = string.Empty; // Reset the error message on next retry. try { var sendForReal = this.mailSettings.Find(a => a.ApplicationName == applicationName).SendForReal; var toOverride = this.mailSettings.Find(a => a.ApplicationName == applicationName).ToOverride; var saveToSent = this.mailSettings.Find(a => a.ApplicationName == applicationName).SaveToSent; MessageBody body = await this.emailManager.GetNotificationMessageBodyAsync(applicationName, item).ConfigureAwait(false); EmailMessage message = item.ToGraphEmailMessage(body); if (!sendForReal) { this.logger.TraceInformation($"Overriding the ToRecipients in {nameof(this.ProcessEntitiesIndividually)} method of {nameof(EmailManager)}.", traceProps); message.ToRecipients = toOverride.Split(Common.ApplicationConstants.SplitCharacter, System.StringSplitOptions.RemoveEmptyEntries).Select(torecipient => new Recipient { EmailAddress = new EmailAddress { Address = torecipient } }).ToList(); message.CCRecipients = null; message.BCCRecipients = null; message.ReplyToRecipients = null; } EmailMessagePayload payLoad = new EmailMessagePayload(message) { SaveToSentItems = saveToSent }; var response = await this.msGraphProvider.SendEmailNotification(emailAccountUsed.Item1, payLoad, item.NotificationId).ConfigureAwait(false); if (response.Status) { item.Status = NotificationItemStatus.Sent; } else if (item.TryCount <= this.maxTryCount && (response.StatusCode == HttpStatusCode.TooManyRequests || response.StatusCode == HttpStatusCode.RequestTimeout)) { item.Status = NotificationItemStatus.Retrying; item.ErrorMessage = response.Result; _ = this.IsMailboxLimitExchausted(response.Result, item.NotificationId, item.EmailAccountUsed, false, traceProps); } else { this.logger.WriteCustomEvent($"{AIConstants.CustomEventMailSendFailed} for notificationId: {item.NotificationId} "); item.Status = NotificationItemStatus.Failed; item.ErrorMessage = response.Result; } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { this.logger.WriteCustomEvent($"{AIConstants.CustomEventMailSendFailed} for notificationId: {item.NotificationId}"); item.Status = NotificationItemStatus.Failed; item.ErrorMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } } this.logger.TraceInformation($"Finished {nameof(this.ProcessEntitiesIndividually)} method of {nameof(MSGraphNotificationProvider)}.", traceProps); }
static void Main(string[] args) { // Step #1: Let's start by entering the web service URL and the API-token you've been provided // If you haven't gotten your API-token yet. Log into AlphaMail or contact support at '*****@*****.**'. IEmailService emailService = new AlphaMailEmailService() .SetServiceUrl("http://api.amail.io/v2/") .SetApiToken("YOUR-ACCOUNT-API-TOKEN-HERE"); // Step #2: Let's fill in the gaps for the variables (stuff) we've used in our template var message = new HelloWorldMessage() { Message = "Hello world like a boss!", SomeOtherMessage = "And to the rest of the world! Chíkmàa! مرحبا! नमस्ते! Dumelang!" }; // Step #3: Let's set up everything that is specific for delivering this email var payload = new EmailMessagePayload() .SetProjectId(12345) // The id of the project your want to send with .SetSender(new EmailContact("Sender Company Name", "*****@*****.**")) .SetReceiver(new EmailContact("Joe E. Receiver", "*****@*****.**")) .SetBodyObject(message); try { // Step #4: Haven't we waited long enough. Let's send this! var response = emailService.Queue(payload); // Step #5: Pop the champagné! We got here which mean that the request was sent successfully and the email is on it's way! Console.WriteLine("Successfully queued message with id '{0}' (you can use this ID to get more details about the delivery)", response.Result); } // Oh heck. Something went wrong. But don't stop here. // If you haven't solved it yourself. Just contact our brilliant support and they will help you. catch (AlphaMailValidationException exception) { // Example: Handle request specific error code here if (exception.Response.ErrorCode == 3) { // Example: Print a nice message to the user. } else { // Something in the input was wrong. Probably good to double double-check! Console.WriteLine("Validation error: {0} ({1})", exception.Response.Message, exception.Response.ErrorCode); } } catch (AlphaMailAuthorizationException exception) { // Ooops! You've probably just entered the wrong API-token. Console.WriteLine("Authentication error: {0} ({1})", exception.Response.Message, exception.Response.ErrorCode); } catch (AlphaMailInternalException exception) { // Not that it is going to happen.. Right :-) Console.WriteLine("Internal error: {0} ({1})", exception.Response.Message, exception.Response.ErrorCode); } catch (AlphaMailServiceException exception) { // Most likely your internet connection that is down. We are covered for most things except "multi-data-center-angry-server-bashing-monkeys" (remember who coined it) or.. nuclear bombs. // If one blew. Well.. It's just likely that our servers are down. Console.WriteLine("An error (probably related to connection) occurred: {0}", exception); } // Writing to console like a boss Console.WriteLine("\n\tIn doubt or experiencing problems?\n" + "\tPlease email our support at '*****@*****.**'"); // This was exhausting. Let's grab a beer. Console.WriteLine("\nPress any key to terminate.."); Console.ReadLine(); }