You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Angular项目调用C#邮件发送接口?

Angular与C#邮件发送功能衔接方案

我目前正在学习Angular,测试站点除邮件发送功能外其他均正常运行。联系页面的提交逻辑代码如下:

onSubmit(): void {
this.submitted = true;
if (this.form.invalid) { return; }
else if (this.form.valid) {
  //now to send the email
}

当表单验证通过后,我希望调用之前在非Angular项目中使用的C#邮件发送代码,但不清楚如何将两者衔接,具体C#代码如下:

namespace test.Controllers
{
  public class Email
  {
    public string To { get; set; }
    public string Subject { get; set; }
    public string Text { get; set; }
  }

  public class ContactService : Controller
  {
    public async Task<IActionResult> SendMail([FromBody] Email email)
    {
      var client = new System.Net.Mail.SmtpClient("mail.abcabc.com");
      client.Port = 25;
      client.UseDefaultCredentials = false;
      client.Timeout = 5000;
      client.EnableSsl = true;
      client.Credentials = new System.Net.NetworkCredential("fred@abcabc.com", "~~~~~~~~~~~~");
      var mailMessage = new System.Net.Mail.MailMessage();
      mailMessage.From = new System.Net.Mail.MailAddress("fred@abcabc.com");
      mailMessage.To.Add(email.To);
      mailMessage.Body = email.Text;
      mailMessage.Subject = email.Subject;
      mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
      mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
      await client.SendMailAsync(mailMessage);
      return Ok();
    }
  }
}

衔接思路

  • 完善后端接口配置:给C#的SendMail方法添加HTTP路由特性,比如[HttpPost("api/contact/send-mail")],确保后端能接收POST请求;同时修正原代码中的语法错误(client.Timeout = 5000缺少分号)。
  • Angular端配置HTTP服务:在项目的AppModule中导入HttpClientModule,并在提交表单的组件中注入HttpClient服务。
  • 构造请求并调用接口:在onSubmit的表单有效分支中,从表单提取对应字段,构造与C#Email类结构一致的对象,通过HttpClient.post方法发送请求到后端接口地址。示例代码如下:
    import { HttpClient } from '@angular/common/http';
    // ... 其他必要导入
    
    constructor(private http: HttpClient) {}
    
    onSubmit(): void {
      this.submitted = true;
      if (this.form.invalid) { return; }
      
      // 从表单控件中获取数据,需对应表单控件名称
      const emailData = {
        To: this.form.get('to')?.value,
        Subject: this.form.get('subject')?.value,
        Text: this.form.get('text')?.value
      };
      
      // 发送POST请求到后端接口
      this.http.post('/api/contact/send-mail', emailData)
        .subscribe({
          next: () => {
            // 发送成功后的处理,如提示用户邮件已发送
            console.log('邮件发送成功');
          },
          error: (err) => {
            // 处理错误,如提示用户发送失败
            console.error('邮件发送失败', err);
          }
        });
    }
    
  • 跨域问题处理:如果Angular前端和C#后端运行在不同端口/域名下,需在后端配置CORS策略,允许前端的请求来源。比如在ASP.NET Core中,可在Program.cs中添加builder.Services.AddCors(options => ...)相关配置。

内容的提问来源于stack exchange,提问作者Kev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:42:51