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

Angular v15使用@sendgrid/mail发送邮件报错求助

解决Angular v15中使用@sendgrid/mail的模块缺失问题

问题根源

@sendgrid/mail是Node.js环境专属的包,它依赖Node.js内置的https、http等核心模块。而Angular应用运行在浏览器环境中,浏览器并不提供这些Node.js专属模块,所以直接在Angular项目中导入该包会触发Cannot find module 'https'的错误。你在纯Node.js环境测试能成功,正是因为Node环境自带这些核心模块。

正确解决方案:通过后端接口发送邮件(推荐)

前端直接调用SendGrid API会暴露你的API密钥,存在严重的安全风险。正确的做法是在后端(比如Node.js/Express)封装邮件发送逻辑,前端通过HTTP请求调用后端接口。

步骤1:编写后端邮件接口(基于Express)

// 后端server.js文件
require("dotenv").config();
const express = require("express");
const sgMail = require("@sendgrid/mail");
const cors = require("cors");

const app = express();
app.use(cors());
app.use(express.json());

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

app.post("/send-email", async (req, res) => {
  const { to, from, subject, html } = req.body;
  try {
    await sgMail.send({ to, from, subject, html });
    res.status(200).json({ message: "邮件发送成功" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "邮件发送失败", details: error.response?.body });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

步骤2:Angular中调用后端接口

  1. 先创建一个邮件服务:
// email.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EmailService {
  private apiUrl = 'http://localhost:3000/send-email';

  constructor(private http: HttpClient) {}

  sendEmail(emailData: { to: string; from: string; subject: string; html: string }): Observable<any> {
    return this.http.post(this.apiUrl, emailData);
  }
}
  1. 在组件中使用该服务:
// app.component.ts
import { Component } from '@angular/core';
import { EmailService } from './email.service';

@Component({
  selector: 'app-root',
  template: `<button (click)="sendTestEmail()">发送测试邮件</button>`
})
export class AppComponent {
  constructor(private emailService: EmailService) {}

  sendTestEmail() {
    this.emailService.sendEmail({
      to: 'xyz@gmail.com',
      from: 'ptj@hotmail.com',
      subject: 'Hello Test',
      html: `<p style="font-weight: 600; background-color: #ff0000">Hello This is test email</p>`
    }).subscribe({
      next: (res) => console.log(res.message),
      error: (err) => console.error(err)
    });
  }
}

不推荐的前端直接调用方案(存在安全风险)

如果因为特殊需求必须在前端处理,不要使用@sendgrid/mail包,而是直接通过Angular的HttpClient调用SendGrid的REST API。注意:此方法会暴露你的SendGrid API密钥,恶意用户可能会盗用你的配额发送垃圾邮件,仅用于测试场景。

示例代码:

// email.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EmailService {
  private sendGridUrl = 'https://api.sendgrid.com/v3/mail/send';
  private apiKey = '你的SendGrid API密钥'; // 这里会暴露密钥,生产环境绝对不能这么做

  constructor(private http: HttpClient) {}

  sendEmail(emailData: { to: string; from: string; subject: string; html: string }): Observable<any> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${this.apiKey}`
    });

    const payload = {
      personalizations: [{ to: [{ email: emailData.to }] }],
      from: { email: emailData.from },
      subject: emailData.subject,
      content: [{ type: 'text/html', value: emailData.html }]
    };

    return this.http.post(this.sendGridUrl, payload, { headers });
  }
}

额外说明

  • 你安装的@types/node仅对Node.js项目有效,Angular浏览器环境无法识别Node.js的核心模块类型,所以这个依赖无法解决问题。
  • SendGrid官方明确不推荐在前端环境使用其Node.js SDK,核心原因就是API密钥的安全问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:37:04