Azure Communication Service · AzureContainerApps · Infrastructure As Code · Java · Spring boot · terraform

Email and SMS with Azure Communication Service: Step-by-Step

Introduction

Azure Communication Service is a powerful cloud-based platform offered by Microsoft that enables developers to integrate real-time communication features like SMS, voice, and email into their applications. With Azure Communication Service, developers can easily send emails and SMS to end users in a unified and seamless way, reducing the complexity of managing multiple communication channels. In this tutorial, we will explore how to use Azure Communication Service to send emails and one-way SMS messages through code snippets and examples.

Infrastructure

To get started, let’s provision Azure Communication Service using Terraform. Terraform is an infrastructure-as-code tool that allows us to define and manage our Azure resources effortlessly. Below are the Terraform snippets to provision Azure Communication Service. ACS offers two flavors for the email domain: Azure Managed Domain and Custom Domain.

  1. Install the Azure provider plugin in your Terraform configuration:
terraform {
  required_version = ">=0.12"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>2.0"
    }
    azapi = {
      source  = "azure/azapi"
      version = "~>1.7.0"
    }    
  }
}

provider "azurerm" {  
  features {}
}

provider "azapi" {
}

2. Provision Azure Communication Service with the Azure-managed domain:

resource "azurerm_resource_group" "communication_rg" {
  name     = "communication-resource-group"
  location = "West Europe"
}

resource "azurerm_communication_service" "communication_service" {
  name                = "my-communication-service"
  resource_group_name = azurerm_resource_group.communication_rg.name
  location            = azurerm_resource_group.communication_rg.location
  sku                 = "S0" # Choose the appropriate SKU based on your requirements
}

2. Provision Azure Communication Service with a custom domain:

resource "azurerm_communication_service" "communication_service_custom" {
  name                = "my-communication-service-custom"
  resource_group_name = azurerm_resource_group.communication_rg.name
  location            = azurerm_resource_group.communication_rg.location
  sku                 = "S1" # Choose the appropriate SKU based on your requirements
  custom_domains = [
    {
      "name"       = "yourcustomdomain.com"
      "use_subdomain" = false
    }
  ]
}

When provisioning with Custom Domain you need to manually verify the domain from Azure Portal. Essentially, you need to add some TXT record to your DNS to proof the ownership of the domain. Besides domain ownership, you also need to add the SPF and DKIM records to prevent spoofing and forging sender address.

Sending Email:

Now, let’s look at an example of how to build a REST API using Java Spring boot to send emails using Azure Communication Service. We will assume you have set up a Java Spring boot project and have integrated Azure SDK.

  1. Add the Azure SDK dependency in your Maven pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.acsdemo</groupId>
	<artifactId>acs</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>acs</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.azure</groupId>
			<artifactId>azure-communication-email</artifactId>
			<version>1.0.0</version>
		</dependency>
		<dependency>
			<groupId>com.azure</groupId>
			<artifactId>azure-communication-common</artifactId>
			<version>1.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.azure</groupId>
			<artifactId>azure-communication-sms</artifactId>
			<version>1.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2. Create a Java class to send emails using Azure Communication Service:

import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.communication.sms.*;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.http.rest.Response;

public class EmailSender {
    public static void sendEmail() {
            var senderAddress = environment.getProperty("ACS_SENDER_EMAIL");
            var acsEndpoint = environment.getProperty("ACS_ENDPOINT");
            var azureCredentailHelper = new AzureCredentailHelper(environment);
            var credential = azureCredentailHelper.getCredential();

            var client = new EmailClientBuilder()
                .endpoint(acsEndpoint)
                .credential(credential)
                .buildClient();
            EmailMessage emailMessage = new EmailMessage()
                .setSenderAddress(senderAddress)
                .setToRecipients(email.to())
                .setSubject(email.subject())
                .setBodyPlainText(email.content());
            SyncPoller<EmailSendResult, EmailSendResult> poller = client.beginSend(emailMessage);           

            PollResponse<EmailSendResult> pollResponse = null;
            Duration timeElapsed = Duration.ofSeconds(0);

             while (pollResponse == null
                     || pollResponse.getStatus() == LongRunningOperationStatus.NOT_STARTED
                     || pollResponse.getStatus() == LongRunningOperationStatus.IN_PROGRESS)
             {
                 pollResponse = poller.poll();
                 System.out.println("Email send poller status: " + pollResponse.getStatus());

                 Thread.sleep(POLLER_WAIT_TIME.toMillis());
                 timeElapsed = timeElapsed.plus(POLLER_WAIT_TIME);

                 if (timeElapsed.compareTo(POLLER_WAIT_TIME.multipliedBy(18)) >= 0)
                 {
                     throw new RuntimeException("Polling timed out.");
                 }
             }

             if (poller.getFinalResult().getStatus() == EmailSendStatus.SUCCEEDED)
             {
                 // String.format("Successfully sent the email (operation id: %s)", poller.getFinalResult().getId());                
             }
    }
}

Sending SMS

In Azure Communication Service, one-way SMS messages can be sent with an alphanumeric sender ID, which is a custom sender name that appears as the sender instead of a phone number.

  1. Create a Java class to send SMS using Azure Communication Service:
import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.communication.sms.*;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.http.rest.Response;

public class SmsSender {
    private static final String CONNECTION_STRING = "your_connection_string";
    private static final String SENDER_NAME = "YourSenderID";

    public static void sendSms(String recipient, String message) {
        SmsClientBuilder smsClientBuilder = new SmsClientBuilder();
        SmsClient smsClient = smsClientBuilder.connectionString(CONNECTION_STRING).buildClient();

        SendSmsOptions options = new SendSmsOptions();
        options.setFrom(new PhoneNumber(SENDER_NAME));
        options.setTo(new PhoneNumber(recipient));
        options.setMessage(message);

        smsClient.send(options);
    }
}

Conclusion

In this tutorial, we’ve explored how to use Azure Communication Service to send emails and one-way SMS messages in a unified way. We demonstrated how to provision Azure Communication Service using Terraform, including the variations comes with the ‘AzureManagedDomain’ or ‘CustomDomain’, and provided code snippets for sending emails and SMS messages using Java Spring Boot.

To access the full code samples, you can find them on GitHub: https://github.com/MoimHossain/azure-communication-servicve-demo.

Now, you can integrate Azure Communication Service into your applications to effortlessly engage with your end users through emails and SMS messages!

4 thoughts on “Email and SMS with Azure Communication Service: Step-by-Step

  1. Is all of this needed for emails? or is this just for sms?
    More steps as to what your doing would be really heplful.

    Like

Leave a comment