Search code examples
c#azureemailazure-communication-services

how to send emails from web api using azure communication service


I'm using Azure communication service to send an email, now I want to do it in web API. Whenever I call the web API post function, the records will be stored in the database as well as it has to be sent as an email to that particular user with their email id.

[HttpPost]
    public async Task<ActionResult<UserTable>> Post([FromBody] UserTable userinfo)
    {
        try
        {            
            var item = await _userTableRepository.AddUser(userinfo);          
            string recipientEmail = userinfo.Email;
            string subject = "Welcome to our platform";
            string body = $"Hello {userinfo.UserId}";
            await SendEmail(recipientEmail,subject, body);
            return Ok(item);
        }
        catch (Exception)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, "Error sending email or saving data");
        }
    }

    private async Task SendEmail(string recipientEmail, string subject, string body)
    {
        var client = new EmailClient(emailconnectionstring);
        var emailMessage = new EmailMessage()
        {
            From = new EmailAddress("sender@example.com"),
            To = new List<EmailAddress>()
            {
                new EmailAddress(recipientEmail)
            },
            Subject = subject,
            Body = new EmailBody()
            {
                ContentType = EmailBodyType.Text,
                Content = body
            }
        };
        await client.SendAsync(emailMessage);
    }

This is the code I'm using with the Azure communication service to send emails. But I'm getting lots of errors, when I tried the email code separately it works perfectly. When I use it in web API, I'm getting this kind of error.

  1. Error CS1729 'EmailMessage' does not contain a constructor that takes 0 arguments
  2. Error CS0117 'EmailMessage' does not contain a definition for 'From'
  3. Error CS0117 'EmailMessage' does not contain a definition for 'To'
  4. Error CS0117 'EmailMessage' does not contain a definition for 'Subject'
  5. Error CS0117 'EmailMessage' does not contain a definition for 'Body'
  6. Error CS0246 The type or namespace name 'EmailBody' could not be found (are you missing a using directive or an assembly reference?)
  7. Error CS0103 The name 'EmailBodyType' does not exist in the current context
  8. Error CS1501 No overload for method 'SendAsync' takes 1 arguments

I tried to solve it, but it's not working. Since I'm new to this, I couldn't find out whether it's right or wrong. Is there anything I'm missing in the code? Is there any other way to send emails from web API using Azure communication service?
Thanks!!!


Solution

  • The EmailMessage has no default constructors. Refer here.

    Also sending the email to multiple recipients need an additional variable of EmailRecipients which has the support for To, CC and BCC. Refer here.

    Modified code for your case.

    private async Task SendEmail(string recipientEmail, string subject, string body)
    {
        var client = new EmailClient(emailconnectionstring);
        
        // Fill the EmailMessage
        var sender = "sender@example.com";
        var subject = subject;
    
        var emailContent = new EmailContent(subject)
        {
            PlainText = body
        };
        
        var toRecipients = new List<EmailAddress>()
        {
            new EmailAddress(recipientEmail)
        };
        
        var emailRecipients = new EmailRecipients(toRecipients);
    
        var emailMessage = new EmailMessage(sender, emailRecipients, emailContent);
        
        await client.SendAsync(emailMessage);
    }
    

    Refer the GitHub repo for more samples.