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.
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!!!
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.