求推荐:Azure上React应用结合Dotnet+SendGrid实现表单邮件发送教程
实现React表单提交后通过.NET+SendGrid发送邮件的方案
第一步:搭建基础.NET Web API服务
- 用.NET CLI新建Web API项目:
dotnet new webapi -n EmailSenderApi - 安装SendGrid的NuGet包:
dotnet add package SendGrid - 在
appsettings.json中配置SendGrid参数(后续可迁移至Azure环境变量):"SendGridSettings": { "ApiKey": "你的SendGrid API密钥", "FromEmail": "your-app@domain.com", "FromName": "你的应用名称" }
第二步:实现邮件发送服务
- 定义邮件服务接口:
public interface ISendGridEmailService { Task SendEmailAsync(string toEmail, string subject, string content); } - 实现接口逻辑:
public class SendGridEmailService : ISendGridEmailService { private readonly IConfiguration _configuration; public SendGridEmailService(IConfiguration configuration) { _configuration = configuration; } public async Task SendEmailAsync(string toEmail, string subject, string content) { var apiKey = _configuration["SendGridSettings:ApiKey"]; var client = new SendGridClient(apiKey); var fromAddress = new EmailAddress( _configuration["SendGridSettings:FromEmail"], _configuration["SendGridSettings:FromName"] ); var toAddress = new EmailAddress(toEmail); var message = MailHelper.CreateSingleEmail(fromAddress, toAddress, subject, "", content); await client.SendEmailAsync(message); } } - 在
Program.cs中注册服务:builder.Services.AddScoped<ISendGridEmailService, SendGridEmailService>();
第三步:创建接收表单数据的API接口
- 新建
EmailController处理前端请求:[ApiController] [Route("api/email")] public class EmailController : ControllerBase { private readonly ISendGridEmailService _emailService; public EmailController(ISendGridEmailService emailService) { _emailService = emailService; } [HttpPost("send")] public async Task<IActionResult> SendFormEmail([FromBody] FormEmailRequest request) { if (!ModelState.IsValid) { return BadRequest("表单数据格式错误"); } try { await _emailService.SendEmailAsync(request.RecipientEmail, request.Subject, request.FormContent); return Ok("邮件发送成功"); } catch (Exception ex) { return StatusCode(500, $"发送失败:{ex.Message}"); } } } public class FormEmailRequest { public string RecipientEmail { get; set; } public string Subject { get; set; } public string FormContent { get; set; } }
第四步:前端React调用API
- 在表单提交函数中,通过
fetch发送请求:const handleFormSubmit = async (e) => { e.preventDefault(); const formData = { RecipientEmail: 'your-target-email@domain.com', Subject: '用户表单提交通知', FormContent: `用户名:${nameInput.value}\n留言:${messageInput.value}` }; try { const response = await fetch('https://your-api-domain/api/email/send', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }); if (response.ok) { alert('提交成功,邮件已发送'); } else { const errorMsg = await response.text(); alert(`提交失败:${errorMsg}`); } } catch (err) { console.error('请求出错:', err); alert('网络错误,请稍后重试'); } };
Azure部署注意事项
- 将.NET API部署到Azure App Service,和React应用配置同域或在API中开启CORS:
builder.Services.AddCors(options => { options.AddPolicy("AllowReactApp", policy => policy.WithOrigins("https://your-react-app-domain") .AllowAnyHeader() .AllowAnyMethod()); }); // 在app.UseRouting()之后添加 app.UseCors("AllowReactApp"); - 在Azure App Service的「配置」-「应用程序设置」中添加
SendGridSettings:ApiKey等环境变量,避免硬编码敏感信息
内容的提问来源于stack exchange,提问作者user20347759
相关产品推荐
相关产品推荐

