The Most Advanced Guide on Azure Email Sending.

The Most Advanced Guide on Azure Email Sending.

Consider the scenario where you've chosen Microsoft Azure as your environment's cloud computing platform. It can be necessary for hosting your app or anything else. You will eventually need to implement email sending, which could be challenging. No Azure service allows you to send emails directly. Why? The solution and information on how to send emails using Azure are provided below.

Azure's SMTP limitations.

The prohibition covers SMTP port 25 direct DNS MX lookups for unauthenticated email delivery (without SPF, DKIM, and DMARC entries). The purpose is to safeguard Azure data center IP addresses against the exploitation of their good name. For 30 days, a free account offers $200 in credits. You can utilize those to test out any Azure platform service. In light of this, people utilize this offer to host and test their servers or apps. Not for that, is a trial subscription intended? These servers and apps send emails without the required sender authentication data. The public IP addresses of Azure data centers suffer as a result, and they are banned.

Users in the enterprise are unaffected by the Azure SMTP restriction. Subscribers who pay as you go can remove the restriction. They must submit the appropriate support request, which Microsoft must then authorize.

Hold off on switching to AWS or any Azure substitute if you are a trial subscriber. Azure allows you to send emails, but only through an SMTP relay provider.

To send emails from Azure, what do I need?

Use an authenticated SMTP relay service, also known as a Smart Host, with TLS capability to deliver emails from Azure VMs or Apps.

For users of Azure, Microsoft formally recommends this. Between the mail servers of the sender and receiver, SMTP relay services offer an additional SMTP server as a middleman. Secure ports 587 or 443 are used to establish the TCP connection. Other SMTP ports, however, might also be supported.

The most popular SMTP relay service that Microsoft Azure integrates with is MailSlurp. Emails can be sent via the MailSlurp SMTP API, which should not be confused with the Web or HTTP API. This blog article features this SMTP relay service as a key actor. We'll also look at services like Office 365 and MailSlurp.

You are, however, free to select any market-available authenticated smart host, such as Elastic Email, SocketLabs, and others. Regardless of your Azure membership, you are free to use any of these services.

Use MailSlurp to send emails.

The recommended mechanism for sending emails from any app, web job, or Azure function is MailSlurp. MailSlurp provides free emails each month along with a variety of APIs such as SMTP, Web, Event, and others. You must register for an account and obtain your MailSlurp SMTP credentials before you can begin using the SMTP relay. You'll need to perform a few additional operations with SMTP API. So let's get started with the fundamentals.

Integration of MailSlurp into your Azure environment

Click Create a resource after logging into Azure Portal.

Select MailSlurp after finding it in the search field. Click Create after that.

You'll require:

  • Name, Password, and Confirm Password fields must be filled out. A new MailSlurp account will be made using these parameters.
  • choosing a subscription
  • use an existing Resource group or build a new one
  • and choose a price tier.
  • include a telephone number
  • and concur with the terms of use.

Once you're prepared, click Create

Deployment Succeeded pop-up will appear at the conclusion, and MailSlurp Accounts will list your account.

Enter account information

Enter your new account information, then select Manage. To start the email verification procedure, this is necessary. Your email address will receive a confirmation email from MailSlurp.

You must create an API Key if you choose to use the MailSlurp SMTP API. Select Manage, then Settings, then API Keys.

After clicking Create API Key, give the key a name and choose permission. When ready, click Create & View.

Copy and save your API Key when you see it. Remember that you won't be able to see it once more.

Using .NET's Built-in SMTP Library

Here is the code sample for building a MIME email and sending it through MailSlurp:

Using MailSlurp to send emails from Azure

Now that the SMTP relay service is operational, you can send emails from Azure. There are various methods for doing this.

SMTP PowerShell usage

To send emails using PowerShell, enter your MailSlurp SMTP server credentials. The following is a sample text email script:

$From = "<user@sender.com>"

$To = "<user@recipient.com>"

$SMTPServer = "smtp.MailSlurp.net"

$SMTPPort = "587"

$Username = "<your-MailSlurp-username>"

$Password = "<your-MailSlurp-password>"

$subject = "Test Email"

$body = "Test email using MailSlurp Email Delivery"

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer,
$SMTPPort)

$smtp.EnableSSL = $true

$smtp.Credentials = New-Object
System.Net.NetworkCredential($Username, $Password)

$smtp.Send($From, $To, $subject, $body)

Using the SMTP Library included into.NET

The code sample for creating a MIME email and sending it via MailSlurp is provided below:

using System;

using System.Collections.Generic;

using System. Text;

using System.Net.Mail;

using System.Net.Mime;

namespace SmtpMail

{

class Program

{

static void Main()

{

try

{

MailMessage mailMsg = new MailMessage();

mailMsg.To.Add(new MailAddress("user@recipient.com", "The
Recipient"));

mailMsg.From = new MailAddress("user@sender.com", "The Sender");

mailMsg.Subject = "Test Email";

string text = "Test Email with MailSlurp using .NET's Built-in SMTP
Library";

string html = @"<strong>HTML text for the Test Email</strong>";

mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text,
null, MediaTypeNames.Text.Plain));

mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html,
null, MediaTypeNames.Text.Html));

SmtpClient smtpClient = new SmtpClient("smtp.MailSlurp.net",
Convert.ToInt32(587));

System.Net.NetworkCredential credentials = new
System.Net.NetworkCredential("<MailSlurp-username>",
"<MailSlurp-password>");

smtpClient.Credentials = credentials;

smtpClient.Send(mailMsg);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

}

}

Using the SMTP API to access the MailSlurp C# Library

In your application, install the MailSlurp NuGet package. It is a client library for C# that enables sending emails over MailSlurp APIs. Through Tools => NuGet Package Manager => Manage NuGet Packages for Solution in Visual Studio, you may immediately install it. Identify MailSlurp and download the most recent stable version.

Check out the code example below to send a straightforward email:

using MailSlurp;

using MailSlurp.Helpers.Mail;

using System;

using System.Threading.Tasks;

namespace Example

{

internal class Example

{

private static void Main()

{

Execute().Wait();

}

static async Task Execute()

{

var apiKey = Environment.GetEnvironmentVariable("");
//insert your MailSlurp API Key

var client = new MailSlurpClient(apiKey);

var from = new EmailAddress("user@sender.com", "The Sender");

var subject = "Test Email with MailSlurp";

var to = new EmailAddress("user@recipient.com", "The Recipient");

var plainTextContent = "Test Email with MailSlurp C# Library";

var htmlContent = "<strong>HTML text for the Test
Email</strong>";

var msg = MailHelper.CreateSingleEmail(from, to, subject,
plainTextContent, htmlContent);

var response = await client.SendEmailAsync(msg);

}

}

}

Using the ASP.NET Core API's MailHelper class

From ASP.NET Core, emails can also be sent. Utilize MailSlurp's MailHelper class. Namespace Helpers. Mail The appsettings.json file is where the API key must be kept (you can tweak it from the Azure Portal as well). Here's how it ought to appear:

{

"Logging": {

"IncludeScopes": false,

"LogLevel": {

"Default": "Debug",

"System": "Information",

"Microsoft": "Information"

}

},

"MailSlurp_API_KEY": ""

}

Make the Startup.cs file to retrieve the API Key from the appsettings.json file. After include it in the ConfigureServicesmethod below, inject the IConfiguration interface at the controller's

function Object() { [native code] }:

And this is a sample controller program's code:

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddSingleton<IConfiguration>(Configuration);

}

And here is the sample code for the controller:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using MailSlurp;

using MailSlurp.Helpers.Mail;

using Microsoft.Extensions.Configuration;

namespace MailSlurpMailApp.Controllers

{

[Route("api/[controller]")]

public class NotificationController : Controller

{

private readonly IConfiguration _configuration;

public NotificationController(IConfiguration configuration)

{

_configuration = configuration;

}

[Route("SendNotification")]

public async Task PostMessage()

{

var apiKey = _configuration.GetSection("MailSlurp_API_KEY").Value;

var client = new MailSlurpClient(apiKey);

var from = new EmailAddress("user@sender.com", "The Sender");

List<EmailAddress> tos = new List<EmailAddress>

{

new EmailAddress("user1@recipient.com", "The Recipient 1"),

new EmailAddress("user2@recipient.com", "The Recipient 2"),

new EmailAddress("user3@recipient.com", "The Recipient 3")

};

var subject = "Test Email with MailSlurp";

var htmlContent = "<strong>HTML text for the Test
Email</strong>";

var displayRecipients = false; // set this to true if you want
recipients to see each others mail id

var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos,
subject, "", htmlContent, false);

await client.SendEmailAsync(msg);

}

}

}

Call the AddAttachment method with the file name and Base64-encoded information specified if you wish to add an attachment to your email. For instance:

var attachment = new Attachment()

{

Content = Convert.ToBase64String(raw_content),

Type = "image/png",

Filename = "attachment.png",

Disposition = "inline",

ContentId = "attachment"

};

msg.AddAttachment(attachment);

Using MailSlurp to send emails from an Azure Automation runbook

Two steps are necessary here:

  • Make a key vault on Azure and put the MailSlurp API key in it.
  • Make a runbook that gets the API key and emails the user.

How to create an Azure KeyVault

Use the script below to build an Azure KeyVault. Run the Azure PowerShell code after adding your variables. If you have the Azure PowerShell Module installed, you may also run the code locally.

$SubscriptionId = "<subscription ID>"

Sign in to your Azure account and select your subscription

If you omit the SubscriptionId parameter, the default subscription is selected.

Connect-AzAccount -SubscriptionId $SubscriptionId

Use Get-AzLocation to see your available locations.

$region = "southcentralus"

$KeyVaultResourceGroupName = "mykeyvaultgroup"

$VaultName = "<Enter a universally unique vault name>"

$MailSlurpAPIKey = "<MailSlurp API key>"

$AutomationAccountName = "testaa"

Create new Resource Group, or omit this step if you already have a resource group.

New-AzResourceGroup -Name $KeyVaultResourceGroupName -Location
$region

Create the new key vault

$newKeyVault = New-AzKeyVault -VaultName $VaultName
-ResourceGroupName $KeyVaultResourceGroupName -Location $region

$resourceId = $newKeyVault.ResourceId
$Secret = ConvertTo-SecureString -String $MailSlurpAPIKey -AsPlainText
-Force

Set-AzKeyVaultSecret -VaultName $VaultName -Name 'MailSlurpAPIKey'
-SecretValue $Secret
$connection = Get-AzAutomationConnection -ResourceGroupName
$KeyVaultResourceGroupName -AutomationAccountName
$AutomationAccountName -Name AzureRunAsConnection

$appID = $connection.FieldDefinitionValues.ApplicationId

Set-AzKeyVaultAccessPolicy -VaultName $VaultName -ServicePrincipalName
$appID -PermissionsToSecrets Set, Get

An Azure KeyVault can be created in additional ways. One employing Portal is seen here.

Browse "Key Vault" after selecting Create a Resource. Press Create.

Click Review + Create after you have completed the relevant fields.

You must import the Az.Profile and Az.KeyVault modules to your Automation Account to use Azure KeyVault within a runbook. With the aid of PowerShell, you can:

Install-Module -Name Az.Profile
Install-Module -Name Az.KeyVault -RequiredVersion 1.3.1

Or you could just deploy these packages to Azure Automation.

Make a guide for sending emails.

Act as follows:

  • In your Azure Automation account, choose Process Automation and then Runbooks.

  • To create a runbook, select +.

  • As the runbook name, type Send-GridMailMessage. Click Create Runbook after selecting PowerShell as the runbook type.

  • In the Edit PowerShell Runbook page that has opened, paste the following PowerShell example.

Param(

[Parameter(Mandatory=$True)]

[String] $destEmailAddress,

[Parameter(Mandatory=$True)]

[String] $fromEmailAddress,

[Parameter(Mandatory=$True)]

[String] $subject,

[Parameter(Mandatory=$True)]

[String] $content

)

$Conn = Get-AutomationConnection -Name AzureRunAsConnection

Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID
-ApplicationId $Conn.ApplicationID -CertificateThumbprint
$Conn.CertificateThumbprint | Out-Null

$VaultName = "<Enter your vault name>"

$MailSlurp_API_KEY = (Get-AzKeyVaultSecret -VaultName $VaultName -Name
"MailSlurpAPIKey").SecretValueText

$headers = New-Object
"System.Collections.Generic.Dictionary[[String],[String]]"

$headers.Add("Authorization", "Bearer " + $MailSlurp_API_KEY)

$headers.Add("Content-Type", "application/json")

$body = @{

personalizations = @(

@{

to = @(

@{

email = $destEmailAddress

}

)

}

)

from = @{

email = $fromEmailAddress

}

subject = $subject

content = @(

@{

type = "text/plain"

value = $content

}

)

}

$bodyJson = $body | ConvertTo-Json -Depth 4

$response = Invoke-RestMethod -Uri
https://api.MailSlurp.com/v3/mail/send -Method Post -Headers $headers
-Body $bodyJson

Use MailSlurp to send emails.

MailSlurp Email Service is likewise offered on the Azure Marketplace, just like MailSlurp. to set up an Azure-integrated MailSlurp account. The process will be same as MailSlurp. The primary distinction is that MailSlurp offers 25K emails for free, while MailSlurp's free plan only offers 6K.

When deployment was successful, a pop-up message stated that a MailSlurp account had been created but was not yet active. On the newly opened screen, click Manage and then choose to Add a Sender Domain or Address.

Please wait for the confirmation email after entering your email address. After that, use MailSlurp to send emails from Azure. The page SMTP and SEND API Settings has the necessary SMTP credentials, while the page Master API Key & Sub API key management contains the necessary API key.

Similar to MailSlurp, the Maijet NuGet package may be installed to send emails via the SMTP API and the.NET class library. It contains two namespaces that must be defined at the beginning of a C# file: MailSlurp.Client and MailSlurp.Client.Resources.

As for the remainder, you can use MailSlurp to send emails from Azure by switching out the MailSlurp credentials in the code samples above. The code example for creating a MIME email and sending it via MailSlurp is shown below:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net.Mail;

using System.Net.Mime;

namespace SmtpMail

{

class Program

{

static void Main()

{

try

{

MailMessage mailMsg = new MailMessage();

mailMsg.To.Add(new MailAddress("user@recipient.com", "The
Recipient"));

mailMsg.From = new MailAddress("user@sender.com", "The Sender");

mailMsg.Subject = "Test Email";

string text = "Test Email with MaiJet using .NET's Built-in SMTP
Library";

string html = @"<strong>HTML text for the Test Email</strong>";

mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text,
null, MediaTypeNames.Text.Plain));

mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html,
null, MediaTypeNames.Text.Html));

SmtpClient smtpClient = new SmtpClient("in-v3.MailSlurp.com",
Convert.ToInt32(587));

System.Net.NetworkCredential credentials = new
System.Net.NetworkCredential("<MailSlurp-username>",
"<MailSlurp-password>");

smtpClient.Credentials = credentials;

smtpClient.Send(mailMsg);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

}

}

Utilizing Office 365 and Azure to send email

To send and receive emails via Azure web apps, you can use an Office 365 subscription if you have one. Use the System.Net.Mail class and your SMTP server credentials. Check out this script as an illustration:

namespace SmtpMail {

class Program {

static void Main() {

MailMessage msg = new MailMessage();

msg.To.Add(new MailAddress("user@recipient.com", "The
Recipient"));

msg.From = new MailAddress("user@sender.com", "The Sender");

msg.Subject = "Test Email from Azure Web App using Office365";

msg.Body = "<p>Test emails on Azure from a Web App via
Office365</p>";

msg.IsBodyHtml = true;

SmtpClient client = new SmtpClient();

client.UseDefaultCredentials = false;

client.Credentials = new
System.Net.NetworkCredential("<Office365-username>",
"<Office365-password>");#insert your credentials

client.Port = 587;

client.Host = "smtp.office365.com";

client.DeliveryMethod = SmtpDeliveryMethod.Network;

client.EnableSsl = true;

try {

client.Send(msg);

statusLabel.Text = "Email Successfully Sent";

}

catch(Exception ex) {

statusLabel.Text = ex.ToString();

}

}

}

}

Outlook connection for Office 365

A logic program from Microsoft Azure comes with a connector for Outlook Office 365. This enables you to set up an event or action to start sending emails. Azure will alert you, for instance, if a future event on your calendar is about to begin. Let's examine its operation.

  • You must first establish a link between your Office 365 account and your Azure account. Create a logic app on the Azure Portal for this.
  • Click Create after entering the name, resource group, and location.
  • Launch the logic app, then type "Office 365" into the search bar.
  • Choose a trigger and an action. For instance:
  • Action: Make an email.
  • Trigger: After logging into Office 365, when an impending event is about to begin.
  • The link has been established. Let's now adjust the action as well as the trigger:

The Deterrent

  • A calendar can be chosen from the drop-down menu.
  • Change the frequency and interval, which means we must start the action (Send an email) Ten minutes before the scheduled event is scheduled to begin: Set the Minute and 15 Second Interval parameters.
  • Save changes.

The Process

  • Add the action "Send an email."
  • Change variables, then save your changes.

The logic app has now been stored and turned on automatically.

With Gmail, can I send emails?

Some people believe that Gmail can be used as a relay server on port 587. However, you won't be able to send emails from Azure using any port for smtp.gmail.com. If you try it, you might encounter the following error:

[Error] Exception while executing function:
Functions.TimerTriggerCSharp1. Microsoft.Azure.WebJobs.Script: One or
more errors occurred. System: The SMTP server requires a secure
connection or the client was not authenticated. The server response was:
5.5.1 Authentication Required. Learn more at.

or another one:

[Error] Exception while executing function:
Functions.TimerTriggerCSharp1. Microsoft.Azure.WebJobs.Script: One or
more errors occurred. System: Failure sending mail. System: Unable to
read data from the transport connection: net_io_connectionclosed.

How to evaluate email delivery in Azure

Azure sends emails across external SMTP relays to test those. The general testing process looks like this:

  • Without requiring authentication, you must connect to the SMTP relay server and send an email from it.

Your SMTP server is an open relay and has to be corrected if the email has already been sent. Let's use Mail Server Testing Tool to test the MailSlurp SMTP relay as an illustration. What we have is as follows:

Avoid getting mixed up with the following:

Fail !! User@sender.com email addresses are not accepted by smtp.MailSlurp.net. Please check the mail server settings.

As a result, only authenticated senders can use the SMTP relay, which is acceptable.

Use specialized software, such as Fiddler or Postman, to test SMTP APIs.

Conclusion

SMTP relay services from other parties are typically required for email sending from Azure. The most popular and suggested remedy for it is MailSlurp. On how to send emails and combine Azure and MailSlurp, there are numerous examples and documents available. In addition, several options allow SMTP relay, like MailSlurp, SocketLabs, Elastic Email, and others: Office 365 also allows email sending, but this feature is primarily reserved for logic-based applications.

Related content

CSharp Email API and SMTP library

Receive email in DotNET Core using C# and MailSlurp

The Most Advanced Guide on Azure Email Sending.

The Most Advanced Guide on Azure Email Sending.

Disposable email accounts for DotNET core 6

Create real throw-away email addresses for testing and development in .NET core. Follow this guide to get started.

DotNET Core Cake Task Runner (CSharp Makefiles for coverlet code coverage and more)

Create cross platform build scripts for DotNET Core in a way similar to Makefiles.

Mailinator alternative

Alternatives to Mailinator for test email accounts. Create real email addresses using MailSlurp

How to send an email using Powershell (Windows and cross-platform)

Use Send-MailMessage in Windows Powershell to send emails using an SMTP server or MailSlurp's free email API.

Specflow user sign-up testing with MailSlurp accounts

How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.

.NET Selenium C#

Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.

CSharp Email Tutorial

SMTP mailserver testing and usage in CSharp using

Send email with CSharp using SMTP Client and MailSlurp

Create a custom SMTP client and access MailSlurp inboxes from CSharp/DotNET.

How to send emails in VBA

Send email in Visual basic

CSharp send SMTP email

How to use CSharp SMTP client to send email with MailSlurp mail server

Ready to dive in?Start building email applications today.