Pre-send email analysis: Detecting sensitive data and inappropriate content using Azure AI
Azure Communication Services email enables organizations to send high volume messages to their customers using their applications. This tutorial shows how to leverage Azure AI to ensure that your messages accurately reflect your business’s brand and reputation before sending them. Azure AI offers services to analyze your email content for sensitive data and identify inappropriate content. This tutorial describes how to use Azure AI Text Analytics to check for sensitive data and Azure AI Content Safety to identify inappropriate text content. Use these functions to check your content before sending the email using Azure Communication Services. Prerequisites You need to complete these quickstarts to set up the Azure AI resources: Quickstart: Detect Personally Identifying Information (PII) in text Quickstart: Moderate text and images with content safety in Azure AI Studio Prerequisite check In a terminal or command window, run the dotnet command to check that the .NET client library is installed. reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP" View the subdomains associated with your Email Communication Services resource. Sign in to the Azure portal. Locate your Email Communication Services resource. Open theProvision domains tab from the left navigation pane. Make sure that the email sub-domain you plan to use for sending email is verified in your email communication resource. For more information, seeQuickstart: How to add custom verified email domains. View the domains connected to your Azure Communication Services resource. Sign in to the Azure portal. Locate your Azure Communication Services resource. Open theEmail>Domainstab from the left navigation pane. Verified custom sub-domains must be connected with your Azure Communication Services resource before you use the resource to send emails. For more information, seeQuickstart: How to connect a verified email domain. Create a new C# application This section describes how to create a new C# application, install required packages, and create the Main function. In a console window (such as cmd, PowerShell, or Bash), use thedotnet newcommand to create a new console app with the nameEmailPreCheck. This command creates a simple "Hello World" C# project with a single source file:Program.cs. dotnet new console -o EmailPreCheck Change your directory to the newly createdEmailPreCheckapp folder and use thedotnet buildcommand to compile your application. cd EmailPreCheck dotnet build Install required packages From the application directory, install the Azure Communication Services Email client and Azure AI libraries for .NET packages using thedotnet add packagecommands. dotnet add package Azure.Communication.Email dotnet add package Azure.AI.TextAnalytics dotnet add package Microsoft.Azure.CognitiveServices.ContentModerator Create the Main function OpenProgram.csand replace the existing contents with the following code. Theusingdirectives include theAzure.Communication.EmailandAzure.AI namespaces. The rest of the code outlines theSendMailfunction for your program. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Communication.Email; using Azure.AI.TextAnalytics; using Azure.AI.ContentSafety; namespace SendEmail { internal class Program { static async Task Main(string[] args) { // Authenticate and create the Azure Communication Services email client // Set sample content // Pre-check for sensitive data and inappropriate content // Send Email } } } Add function that checks for sensitive data Create a new function to analyze the email subject and body for sensitive data such as social security numbers and credit card numbers. private static async Task<bool> AnalyzeSensitiveData(List<string> documents) { // Client authentication goes here // Function implementation goes here } Create the Text Analytics client with authentication Create a new function with a Text Analytics client that also retrieves your connection information. Add the following code into theAnalyzeSensitiveDatafunction to retrieve the connection key and endpoint for the resource from environment variables namedLANGUAGE_KEYandLANGUAGE_ENDPOINT. It also creates the newTextAnalyticsClientandAzureKeyCredentialvariables. For more information about managing your Text Analytics connection information, seeQuickstart: Detect Personally Identifiable Information (PII) > Get your key and endpoint. // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT" string languageKey = Environment.GetEnvironmentVariable("LANGUAGE_KEY"); string languageEndpoint = Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT"); var client = new TextAnalyticsClient(new Uri(languageEndpoint), new AzureKeyCredential(languageKey)); Check the content for sensitive data Loop through the content to check for any sensitive data. Start the sensitivity check with a baseline offalse. If sensitive data is found, returntrue. Add the following code into theAnalyzeSensitiveDatafunction following the line that creates theTextAnalyticsClientvariable. bool senstiveDataDetected = false; // we start with a baseline that of no sensitive data var actions = new TextAnalyticsActions { RecognizePiiEntitiesActions = new List<RecognizePiiEntitiesAction> { new RecognizePiiEntitiesAction() } }; var operation = await client.StartAnalyzeActionsAsync(documents, actions); await operation.WaitForCompletionAsync(); await foreach (var documentResults in operation.Value) { foreach (var actionResult in documentResults.RecognizePiiEntitiesResults) { if (actionResult.HasError) { Console.WriteLine($"Error: {actionResult.Error.ErrorCode} - {actionResult.Error.Message}"); } else { foreach (var document in actionResult.DocumentsResults) { foreach (var entity in document.Entities) { if (document.Entities.Count > 0) { senstiveDataDetected = true; // Sensitive data detected } } } } } } return senstiveDataDetected; Add function that checks for inappropriate content Create another new function to analyze the email subject and body for inappropriate content such as hate or violence. static async Task<bool> AnalyzeInappropriateContent(List<string> documents) { // Client authentication goes here // Function implementation goes here } Create the Content Safety client with authentication Create a new function with a Content Safety client that also retrieves your connection information. Add the following code into theAnalyzeInappropriateContentfunction to retrieve the connection key and endpoint for the resource from environment variables namedCONTENT_LANGUAGE_KEYandCONTENT_LANGUAGE_ENDPOINT. It also creates a newContentSafetyClientvariable. If you're using the same Azure AI instance for Text Analytics, these values remain the same. For more information about managing your Content Safety connection information, seeQuickstart: Detect Personally Identifiable Information (PII) > Create environment variables. // This example requires environment variables named "CONTENT_LANGUAGE_KEY" and "CONTENT_LANGUAGE_ENDPOINT" string contentSafetyLanguageKey = Environment.GetEnvironmentVariable("CONTENT_LANGUAGE_KEY"); string contentSafetyEndpoint = Environment.GetEnvironmentVariable("CONTENT_LANGUAGE_ENDPOINT"); var client = new ContentSafetyClient(new Uri(contentSafetyEndpoint), new AzureKeyCredential(contentSafetyLanguageKey)); Check for inappropriate content Loop through the content to check for inappropriate content. Start the inappropriate content detection with a baseline offalse. If inappropriate content is found, returntrue. Add the following code into theAnalyzeInappropriateContentfunction after the line that creates theContentSafetyClientvariable. bool inappropriateTextDetected = false; foreach (var document in documents) { var options = new AnalyzeTextOptions(document); AnalyzeTextResult response = await client.AnalyzeTextAsync(options); // Check the response if (response != null) { // Access the results from the response foreach (var category in response.CategoriesAnalysis) { if (category.Severity > 2) // Severity: 0=safe, 2=low, 4=medium, 6=high { inappropriateTextDetected = true; } } } else { Console.WriteLine("Failed to analyze content."); } } return inappropriateTextDetected; // No inappropriate content detected Update the Main function to run prechecks and send email Now that you added the two functions for checking for sensitive data and inappropriate content, you can call them before sending email from Azure Communication Services. Create and authenticate the email client You have a few options available for authenticating to an email client. This example fetches your connection string from an environment variable. Open Program.cs in an editor. Add the following code to the body of the Main function to initialize an EmailClient with your connection string. This code retrieves the connection string for the resource from an environment variable named COMMUNICATION_SERVICES_CONNECTION_STRING. For more information about managing your resource connection string, seeQuickstart: Create and manage Communication Services resources > Store your connection string. // This code shows how to fetch your connection string from an environment variable. string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING"); EmailClient emailClient = new EmailClient(connectionString); Add sample content Add the sample email content into the Main function, following the lines that create the email client. You need to get the sender email address. For more information about Azure Communication Services email domains, seeQuickstart: How to add Azure Managed Domains to Email Communication Service. Modify the recipient email address variable. Put both the subject and the message body into aList<string>which can be used by the two content checking functions. //Set sample content var sender = "donotreply@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.azurecomm.net"; // get the send email from your email resource in the Azure Portal var recipient = "emailalias@contoso.com"; // modify the recipient var subject = "Precheck Azure Communication Service Email with Azure AI"; var htmlContent = "<html><body><h1>Precheck email test</h1><br/><h4>This email message is sent from Azure Communication Service Email. </h4>"; htmlContent += "<p> My SSN is 123-12-1234. My Credit Card Number is: 1234 4321 5678 8765. My address is 1011 Main St, Redmond, WA, 998052 </p>"; htmlContent += "<p>A 51-year-old man was found dead in his car. There were blood stains on the dashboard and windscreen."; htmlContent += "At autopsy, a deep, oblique, long incised injury was found on the front of the neck. It turns out that he died by suicide.</p>"; htmlContent += "</body></html>"; List<string> documents = new List<string> { subject, htmlContent }; Pre-check content before sending email You need to call the two functions to look for violations and use the results to determine whether or not to send the email. Add the following code to the Main function after the sample content. // Pre-Check content bool containsSensitiveData = await AnalyzeSensitiveData(documents); bool containsInappropriateContent = await AnalyzeInappropriateContent(documents); // Send email only if not sensitive data or inappropriate content is detected if (containsSensitiveData == false && containsInappropriateContent == false) { /// Send the email message with WaitUntil.Started EmailSendOperation emailSendOperation = await emailClient.SendAsync( Azure.WaitUntil.Started, sender, recipient, subject, htmlContent); /// Call UpdateStatus on the email send operation to poll for the status manually try { while (true) { await emailSendOperation.UpdateStatusAsync(); if (emailSendOperation.HasCompleted) { break; } await Task.Delay(100); } if (emailSendOperation.HasValue) { Console.WriteLine($"Email queued for delivery. Status = {emailSendOperation.Value.Status}"); } } catch (RequestFailedException ex) { Console.WriteLine($"Email send failed with Code = {ex.ErrorCode} and Message = {ex.Message}"); } /// Get the OperationId so that it can be used for tracking the message for troubleshooting string operationId = emailSendOperation.Id; Console.WriteLine($"Email operation id = {operationId}"); } else { Console.WriteLine("Sensitive data and/or inappropriate content detected, email not sent\n\n"); } With this step, we have completed the tutorial. Happy coding! You can learn more about Azure Communication Email Service through the following links - Overview of Azure Communication Services email How to create authentication credentials for sending emails using SMTPPart 2 - Multichannel notification system using Azure Communication Services and Azure Functions
In this second part of this tutorial, we complete coding the remaining Azure Functions triggers and then go ahead to deploy the multichannel notification system to Azure Functions, testing the Email, SMS, and WhatsApp triggers with OpenAI GPTs. Let’s get started!Send an email in Python using Azure Communication Services
Here is a step-by-step tutorial on how to send an email using the Azure Communication Services SDK in Python. Pre-requisites 1. Azure Subscription – If you don’t have one, create a free account at Azure. 2. Python – Ensure you have Python 3.6+ installed on your machine. Setting up Azure resources Step 1: Create an Azure Communication Services Resource First, you need to create an Azure Communication Services Resource. Follow the instructions at Create Azure Communication Services resource to get started. Copy the connection string from the Keys blade of your communication resource. You'll need it later. Step 2: Create an Email Service Next, create an Email Service by following the steps at Create and manage Email Communication Service resources using the portal. This is how the create page looks like in the Azure portal. Step 3: Set Up a Free Azure Subdomain Back in the Communication resource, select Try Email. Under Select a domain, choose Set up a free Azure subdomain and select the email service you just created. Use the "Try Email" feature to ensure that your setup is working correctly. Copy and save the Send email from address (it starts with donotreply). You'll need it later. Step 4: Get the connection string and email domain from the Azure portal To send an email, you need to set up an Azure Communication Services resource and fetch the connection string. You can do this through the Azure portal: Navigate to the Azure Portal. Open the Azure Communication Services resource you created in Step 2. Go to Settings > Keys and copy the connection string. Go to Email Service resource > Domains > Copy the sender address. Or you can use the address you copied in Step 2 when setting up the Azure resources. Application code to send an Email Step 1: Install Required Packages First, let's install the required Python packages for Azure Communication Service Email. Open a terminal window on your desktop. Or in VS Code, press Ctrl + ` (press the control key and back quote at the same time) to open a terminal window in the app. In the terminal window, run the following command. pip install azure-communication-email Step 2: Create a new Python file. Open VS Code or any other IDE of your choice. Create a new Python file named send-email.py. Step 3: Write the Python Code to Send an Email 1. Import the Required Libraries import os from azure.communication.email import EmailClient 2. Initialize the Email Client Use the connection string you fetched earlier to initialize the EmailClient in your Python application. connection_string = "your_acs_connection_string" # Replace with your ACS connection string email_client = EmailClient.from_connection_string(connection_string) 3. Prepare the Email Message Next, construct the email message with subject, content, sender, and recipient details. message = { "content": { "subject": "This is the subject", "plainText": "This is the body", "html": "<html><h1>This is the body</h1></html>" }, "recipients": { "to": [ { "address": "customer@domain.com", "displayName": "Customer Name" } ] }, "senderAddress": "sender@contoso.com" } poller = email_client.begin_send(message) result = poller.result() 4. Track the Status of the Email (Optional) You can track the status of the sent email using the message_id returned by the send() method. Here’s how you can query the status of the email: def check_email_status(message_id): try: status_response = email_client.get_send_status(message_id) print(f"Email status: {status_response.status}") except HttpResponseError as ex: print(f"Failed to get email status: {ex}") # Example usage message_id = "your_message_id_here" check_email_status(message_id) Step 5: Run the Application Once you have set everything up, you can run your Python script, and the email should be sent successfully. Run the following command in the terminal. python send-email.py Step 6: Debugging and Error Handling You might encounter errors such as unverified domains, incorrect connection strings, or issues with the Azure Communication Services setup in the terminal. Conclusion You successfully sent an email using Azure Communication Services in Python! This tutorial covered the basic steps, including setting up Azure Communication Services, initializing the EmailClient, and sending an email. Here are some additional learning resources - Overview of Azure Communication Services email Quota increase for Azure Email Communication Service Quickstart - Send email to multiple recipients using Azure Communication Service Quickstart - Send email with attachments using Azure Communication Service Quickstart - Send email with inline attachments using Azure Communication Service Manage domain suppression lists in Azure Communication Services using the management client librariessend from alias enabled for individual users instead of org wide
Hello, There currently exists an org wide setting to enable users to send from their aliases. This allows any user to send from their aliases or .onmicrosoft.com domain. I would like to request a feature to have this ability on the mailbox level instead of org wide. I only want to enable this feature for a small subset of users instead of org wide and currently cannot do this. reference82Views0likes2CommentsMonthly news - November 2024
Microsoft Defender XDRMonthly newsNovember 2024 Edition This is our monthly "What's new" blog post, summarizing product updates and various new assets we released over the past month across our Defender products. In this edition, we are looking at all the goodness from October2024.927Views1like0CommentsMonthly news - August 2024
Microsoft Defender XDRMonthly newsAugust 2024 Edition This is our monthly "What's new" blog post, summarizing product updates and various new assets we released over the past month across our Defender products. In this edition, we are looking at all the goodness from July2024.6.2KViews3likes3CommentsIs this even possible to include a hidden personal email address for F1 users on profile card
Checking in to see if this is possible - Goal: To pull personal email addresses from F1 users that are stored in PeopleSoft and add them into the MS profile card in the email spot, then hide them from public view We want to have the ability to send manually curated news and automatic "news you may have missed" from the newsfeed via our SharePoint intranet to their personal email addresses Current state: Staff's personal email addresses are stored in PeopleSoft, and they have the ability to edit them We have processes that run each week comparing AD Attribute Information against PS Attribute Information and updates accordingly All staff have access to PeopleSoft and use their Microsoft login Staff are authenticated through Azure This group of staff have F1 licenses and tend to be seasonal workers; it's cost-prohibitive to upgrade their licenses Ideal state: The solution uses existing O365 or other corporate software, such as a Microsoft Delve The solution pulls staff's personal email address information from PeopleSoft, where it's currently stored and allows staff to opt in and out from there Alternatively, we use an MS application like Delve for staff to add their email address and opt in or out of corporate communications The solution provides the ability for the staff's personal email addressNOT to be displayedin the MS profile card found when hovering over a staff person's name185Views0likes4Comments