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

React中使用EmailJS发送消息失败:公钥无效问题求助

EmailJS公钥无效问题排查与解决

问题描述

我在React项目中使用EmailJS发送消息,最初代码如下:

import emailjs from '@emailjs/browser'
const sendEmail = (e) => {
        e.preventDefault();

        emailjs.sendForm('gmail', 'service_*', form.current, 'template_*','public key', )
        .then(
            () => {
            alert('Message successfully sent!');
            window.location.reload(false)
        }, (error) => {
            console.error('Failed to send the message:', error);
            alert(`Failed to send the message: ${error.text}`);
        });
    };

执行后收到错误提示:Failed to send the message: The Public Key is invalid.

我尝试刷新公钥并修改代码为以下形式,问题仍然存在:

const sendEmail = {
  name: 'James',
  notes: 'Check this out!',
};

emailjs
  .send('SERVICE_ID', 'TEMPLATE_ID', sendEmail, {
    publicKey: 'PUBLIC_KEY',
  })
  .then(
    (response) => {
      console.log('SUCCESS!', response.status, response.text);
    },
    (err) => {
      console.log('FAILED...', err);
    },
  );

排查与解决步骤

  • 确认公钥来源与格式
    公钥需从EmailJS控制台的「Account」→「API Keys」页面获取,确保复制的是Public Key而非Private Key。注意公钥是一串无空格的字符串,不要复制到多余的空格或换行符。

  • 修正sendForm方法的参数顺序
    最初的sendForm调用参数顺序错误,正确的sendForm签名为:

    emailjs.sendForm(serviceID, templateID, formElement, options)
    

    其中options是包含publicKey的对象,而非单独传参。修正后的代码示例:

    emailjs.sendForm('你的服务ID', '你的模板ID', form.current, {
      publicKey: '你的公钥'
    })
    
  • 验证服务ID与模板ID的正确性
    确保serviceID是EmailJS中已配置的服务ID(格式如service_xxxxxx),templateID是对应模板的ID(格式如template_xxxxxx),二者需与控制台中的信息完全一致,不要使用占位符或错误ID。

  • 更新EmailJS依赖版本
    确认安装的@emailjs/browser是最新稳定版,可通过重新安装更新:

    npm uninstall @emailjs/browser
    npm install @emailjs/browser
    
  • 直接测试公钥有效性
    在EmailJS控制台的「API Keys」页面使用「Test」功能验证公钥是否有效,若测试失败,重新生成公钥并复制使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 03:34:59