Achraf Ben Alaya
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
SUBSCRIBE
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
No Result
View All Result
Achraf Ben Alaya
No Result
View All Result
ADVERTISEMENT
Home Blog Cloud Azure

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

achraf by achraf
December 8, 2024
in Azure, Blog, Cloud
10 min read
0
Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring
0
SHARES
1.6k
VIEWS
Share on FacebookShare on Twitter

1-General introduction


The recent critical issue my customer experienced was that an application stopped sending emails for more than six months. And what was the reason behind this? It included using a solution that had been marked as deprecated and had been working all along-that is, until it did not work anymore. Of course, as we know, once something is marked as deprecated, it’s only a question of time before it gets retired completely.

The challenge was clear when they called me for help-to fix the problem in one day. Fortunately, my background as a full-stack.NET developer gave me an edge to understand their system in no time. After diving into their codebase, I found they were using some very outdated library for SMTP to handle their email functionality.

With time running out, I needed a modern and reliable solution that could be implemented quickly. Azure Communication Services immediately came to mind: robust, scalable, and fresh from general availability. Its email capability was just what I needed to replace the deprecated SMTP library.

I managed, within the same day, the integration of their application to Azure Communication Services, along with testing, making it live. And then there I went, making them have emails up by the end of that day. This made their team super happy as their updated modern solution was a good solution.

This was an experience, and it reminded me that familiarization with newer tools and technologies is priceless in solving various problems quickly and well, even when the pressure might be really high.

so what is Azure Communication Services ?

Azure Communication Services offers multichannel communication APIs for adding voice, video, chat, text messaging/SMS, email, and more to all your applications.

Azure Communication Services include REST APIs and client library SDKs, so you don’t need to be an expert in the underlying technologies to add communication into your apps. Azure Communication Services is available in multiple Azure geographies and Azure for government.

Azure Communication Services supports various communication formats:

You can connect custom client apps, custom services, and the publicly switched telephone network (PSTN) to your communications experience. You can acquire phone numbers directly through Azure Communication Services REST APIs, SDKs, or the Azure portal and use these numbers for SMS or calling applications.https://learn.microsoft.com/en-us/azure/communication-services/concepts/sdk-options?wt.mc_id=MVP_328341
You can also integrate email capabilities to your applications using production-ready email SDKs. Azure Communication Services direct routing enables you to use SIP and session border controllers to connect your own PSTN carriers and bring your own phone numbers.
In addition to REST APIs, Azure Communication Services client libraries are available for various platforms and languages, including Web browsers (JavaScript), iOS (Swift), Android (Java), Windows (.NET). Take advantage of the UI library to accelerate development for Web, iOS, and Android apps. Azure Communication Services is identity agnostic, and you control how to identify and authenticate your customers

2-Setup Azure Communication Service with a custom domain name to send Email

First of all, you need to have a verified domain. In my use case, I already have a domain name in GoDaddy that I will be using for this demo.

So, let’s get started :

 

First, we need to go to Azure Portal and create the resource by searching for Azure Communication Services. We will then create Azure Communication Services, set up email resources, and configure domain ownership, SPF, and DKIM.
SPF ensures that only authorized mail servers can send mail using your domain, aiding to prevent email spoofing. DKIM adds a verified domain-based digital signature in every email, assuring recipients that messages haven’t been manipulated or tampered with in transitory ways.

For SPF and DKIM configurations, certain TXT records have to be added to the DNS settings of your domain

  • create email resource
 

  • Add custom domain

  • connect domain to send email

3-Test Azure Communication Service from the portal

4- Use Azure Communication Service with C# (including SMTP)

now lets try the code provided from the portal :

using System;
using System.Collections.Generic;
using Azure;
using Azure.Communication.Email;

string connectionString = "endpoint=replace this with your endpoint";
var emailClient = new EmailClient(connectionString);


var emailMessage = new EmailMessage(
    senderAddress: "DoNotReply@yourdomain.com",
    content: new EmailContent("Test Email from communication service")
    {
        PlainText = "Hello world via email from visual studio code.",
        Html = @"
        <html>
            <body>
                <h1>Hello world via email from visual studio code..</h1>
            </body>
        </html>"
    },
    recipients: new EmailRecipients(new List<EmailAddress> { new EmailAddress("youremail@outlook.com") }));
    

EmailSendOperation emailSendOperation = emailClient.Send(
    WaitUntil.Completed,
    emailMessage);

SMTP Sample

 

We will need to implement additional configurations such as custom role to optimize the SMTP sample and ensure seamless functionality.

using System.Net;
using System.Net.Mail;

string smtpAuthUsername = "<Azure Communication Services Resource name>|<Entra Application Id>|<Entra Application Tenant Id>";
string smtpAuthPassword = "Entra Application Client Secret";
string sender = "DoNotReply@yourdomain.com";
string recipient = "testemail@gmail.com";
string subject = "Welcome to Azure Communication Service Email SMTP";
string body = "This email message is sent from Azure Communication Service Email using SMTP.";

string smtpHostUrl = "smtp.azurecomm.net";
var client = new SmtpClient(smtpHostUrl)
{
    Port = 587,
    Credentials = new NetworkCredential(smtpAuthUsername, smtpAuthPassword),
    EnableSsl = true
};

var message = new MailMessage(sender, recipient, subject, body);

try
{
    client.Send(message);
    Console.WriteLine("The email was successfully sent using Smtp.");
}
catch (Exception ex)
{
    Console.WriteLine($"Smtp send failed with the exception: {ex.Message}.");
}

6- Use Azure Communication Service with PowerShell

$Password = ConvertTo-SecureString -AsPlainText -Force -String 'Entra Application Client Secret'
$Cred = New-Object -TypeName PSCredential -ArgumentList '<Azure Communication Services Resource name>|<Entra Application ID>|<Entra Tenant ID>', $Password
Send-MailMessage -From 'DoNotReply@yourdomain.com' -To 'email to test' -Subject 'Test mail' -Body 'test' -SmtpServer 'smtp.azurecomm.net' -Port 587 -Credential $Cred -UseSsl

7- Sample : sending A news Letter to multi Emails with Attachment

Azure Communication Services also support sending emails to multiple recipients and attaching files. For more details, refer to this guide: Send email to multiple recipients


using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mime;
using System.Threading.Tasks;
using Azure;
using Azure.Communication.Email;

namespace SendEmail
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            // This code demonstrates how to fetch your connection string from an environment variable.
            string connectionString = "endpoint=............................................................";
            EmailClient emailClient = new EmailClient(connectionString);

            // Create the email content
            var emailContent = new EmailContent("Newsletter from Achraf Ben Alaya")
            {
                PlainText = "This is the latest news from Achraf Ben Alaya's website.",
                Html = @"
                <html>
                <body>
                    <h1>Latest News from Achraf Ben Alaya</h1>
                    <p>Dear Subscriber,</p>
                    <p>We are excited to share the latest updates from <a href='https://achrafbenalaya.com'>achrafbenalaya.com</a>.</p>
                    <h2>New Features</h2>
                    <ul>
                        <li>Feature 1: Description of feature 1.</li>
                        <li>Feature 2: Description of feature 2.</li>
                        <li>Feature 3: Description of feature 3.</li>
                    </ul>
                    <h2>Upcoming Events</h2>
                    <p>Stay tuned for our upcoming events:</p>
                    <ul>
                        <li>Event 1: Date and details of event 1.</li>
                        <li>Event 2: Date and details of event 2.</li>
                    </ul>
                    <p>Thank you for being a valued subscriber.</p>
                    <p>Best regards,<br/>Achraf Ben Alaya</p>
                </body>
                </html>"
            };

            // Create the To list
            var toRecipients = new List<EmailAddress>
            {
                new EmailAddress("youremail@outlook.com"),
                new EmailAddress("ryle.kutler@finestudio.org"),
            };

            // Create the CC list
            var ccRecipients = new List<EmailAddress>
            {
                new EmailAddress("ripejo9625@bawsny.com"),
            };

            // Create the BCC list
            var bccRecipients = new List<EmailAddress>
            {
                new EmailAddress("wizorvlad@hulas.me"),
            };

            EmailRecipients emailRecipients = new EmailRecipients(toRecipients, ccRecipients, bccRecipients);

            // Create the EmailMessage
            var emailMessage = new EmailMessage(
                senderAddress: "DoNotReply@ihelpyoutodo.com",
                emailRecipients,
                emailContent);

            // Add optional ReplyTo address which is where any replies to the email will go to.
            // emailMessage.ReplyTo.Add(new EmailAddress("<replytoemailalias@emaildomain.com>"));

            // Create the EmailAttachment
            var filePath = @"";
            byte[] bytes = File.ReadAllBytes(filePath);
            var contentBinaryData = new BinaryData(bytes);
            var emailAttachment = new EmailAttachment("micso.png", MediaTypeNames.Application.Pdf, contentBinaryData);

            emailMessage.Attachments.Add(emailAttachment);

            try
            {
                EmailSendOperation emailSendOperation = await emailClient.SendAsync(WaitUntil.Completed, emailMessage);
                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

                // 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}");
            }
            catch (RequestFailedException ex)
            {
                // OperationID is contained in the exception message and can be used for troubleshooting purposes
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }
    }
}

8 – Monitoring

Communications Services provides monitoring and analytics features via Azure Monitor Logs overview and Azure Monitor Metrics. Each Azure resource requires its own diagnostic setting :

Once diagnostic settings are activated, you can monitor email activity directly from the Azure portal. This includes viewing metrics such as the number of emails sent, failed, and the total success rate. Additionally, you can filter the data by sender to gain more detailed insights.

ShareTweet
Previous Post

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

Next Post

Understanding Generative AI and RAG Benefits

Related Posts

AI

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025
110
Azure

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
230
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet
Azure

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025
136
Understanding Generative AI and RAG Benefits
AI

Understanding Generative AI and RAG Benefits

January 12, 2025
96
PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis
Azure

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

November 2, 2024
501
Automated Monitoring of Azure App Registration Secrets with Automation Accounts and Logic Apps
Azure

Automated Monitoring of Azure App Registration Secrets with Automation Accounts and Logic Apps

October 7, 2024
652
Next Post
Understanding Generative AI and RAG Benefits

Understanding Generative AI and RAG Benefits

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Terraform

Certifications

Microsoft certified trainer (MCT)

Recommended

Create a Linux VM with infrastructure in Azure using Terraform

Create a Linux VM with infrastructure in Azure using Terraform

August 30, 2020
2.3k

How To host a Next.js app on Azure

October 5, 2020
1.5k
The Significance of Azure DevSecOps: Best Practices for Securing Your Pipelines

The Significance of Azure DevSecOps: Best Practices for Securing Your Pipelines

August 17, 2023
343
Migrate and modernize your applications on Azure

Migrate and modernize your applications on Azure – Part – 00 (creating .Net 5.0 application )

March 29, 2021
315
Going Dapr

Going Dapr

August 17, 2021
491
Win free certifications at the Microsoft Build Cloud Skills Challenge | May 2022 🎁

Win free certifications at the Microsoft Build Cloud Skills Challenge | May 2022 🎁

May 28, 2022
257
Facebook Twitter LinkedIn Youtube

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025

Categories

  • AI (2)
  • Apps (1)
  • Azure (63)
  • blazor (2)
  • Blog (91)
  • c# (7)
  • Cloud (65)
  • Courses (3)
  • Dapr (4)
  • docker (4)
  • Games (1)
  • General Tips & Fix (1)
  • Home (1)
  • Kubernetes Service (AKS) (1)
  • motivation (2)
  • Motivation (3)
  • News (9)
  • Resume (1)
  • sql (4)
  • Terrafrom (1)
  • Tricks, Tips and Fixes (4)
  • xamarin (5)
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy