public static string Value(this EmailType val) { var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); return(attributes.Length > 0 ? attributes[0].Description : string.Empty); }
public static async Task <HttpResponseMessage> Run(string jsonContent, TraceWriter log) { log.Info("C# NHS111OnlineMailSender trigger function processed a request."); var sendMail = JsonConvert.DeserializeObject <SendMail>(jsonContent); if (!EmailType.IsSupported(sendMail.EmailType)) { log.Info($"Email type {sendMail.EmailType} is not supported!"); return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } if (sendMail.ToEmails == null || sendMail.Body == null || sendMail.Subject == null) { log.Info("Usage: Args[]: str:RecipientEmail, str:Subject, str:Body"); return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } if (IsValidEmails(sendMail.ToEmails) && (sendMail.CcEmails == null || IsValidEmails(sendMail.CcEmails))) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); var emailType = EmailType.GetType(sendMail.EmailType); var keyVaultName = ConfigurationManager.AppSettings["KeyVaultName"]; log.Info($"Using key vault {keyVaultName}"); var mailAccount = await keyVaultClient.GetSecretAsync($"https://{keyVaultName}.vault.azure.net/secrets/{emailType.AccountKey}").ConfigureAwait(false); var mailPassword = await keyVaultClient.GetSecretAsync($"https://{keyVaultName}.vault.azure.net/secrets/{emailType.PasswordKey}").ConfigureAwait(false); log.Info($"Exchange user {mailAccount.Value}"); var service = new ExchangeService(ExchangeVersion.Exchange2013) { Credentials = new WebCredentials(mailAccount.Value, mailPassword.Value), Url = new Uri("https://mail.nhs.net/EWS/Exchange.asmx") }; var message = new EmailMessage(service) { Subject = sendMail.Subject, Body = new MessageBody(BodyType.HTML, $"{sendMail.Body}{(sendMail.EmailType != EmailType.DataExtract.Name ? NoReply : string.Empty)}") }; foreach (var toEmail in sendMail.ToEmails) { message.ToRecipients.Add(toEmail); } if (sendMail.CcEmails != null) { foreach (var ccEmail in sendMail.CcEmails) { message.CcRecipients.Add(ccEmail); } } if (sendMail.Attachments != null) { foreach (var attachment in sendMail.Attachments) { message.Attachments.AddFileAttachment(attachment.Key, Convert.FromBase64String(attachment.Value)); } } try { message.SendAndSaveCopy(); return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (Exception e) { log.Info(e.Message); return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } log.Info("One or more email addresses not valid"); return(new HttpResponseMessage(HttpStatusCode.NoContent)); }