如何使用Azure通信服务从Web API发送电子邮件。

huangapple go评论60阅读模式
英文:

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

英文:

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&lt;ActionResult&lt;UserTable&gt;&gt; Post([FromBody] UserTable userinfo)
    {
        try
        {            
            var item = await _userTableRepository.AddUser(userinfo);          
            string recipientEmail = userinfo.Email;
            string subject = &quot;Welcome to our platform&quot;;
            string body = $&quot;Hello {userinfo.UserId}&quot;;
            await SendEmail(recipientEmail,subject, body);
            return Ok(item);
        }
        catch (Exception)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, &quot;Error sending email or saving data&quot;);
        }
    }

    private async Task SendEmail(string recipientEmail, string subject, string body)
    {
        var client = new EmailClient(emailconnectionstring);
        var emailMessage = new EmailMessage()
        {
            From = new EmailAddress(&quot;sender@example.com&quot;),
            To = new List&lt;EmailAddress&gt;()
            {
                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!!!

答案1

得分: 2

EmailMessage没有默认构造函数。请参考这里

同时,发送邮件给多个收件人需要额外的EmailRecipients变量,该变量支持To、CC和BCC。请参考这里

针对您的情况修改的代码如下:

private async Task SendEmail(string recipientEmail, string subject, string body)
{
    var client = new EmailClient(emailconnectionstring);
    
    // 填充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);
}

更多示例请参考GitHub仓库

英文:

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 = &quot;sender@example.com&quot;;
	var subject = subject;

	var emailContent = new EmailContent(subject)
	{
		PlainText = body
	};
	
	var toRecipients = new List&lt;EmailAddress&gt;()
	{
		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.

huangapple
  • 本文由 发表于 2023年6月12日 03:12:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定