1

每当用户单击提交时,我想通过表单发送电子邮件

为此我使用smtpjs包,您可以在此处查看站点https://smtpjs.com/

在纯js中我们必须在html头标签中添加这行代码

<script src=
    "https://smtpjs.com/v3/smtp.js">
  </script>

然后我们可以Email.send({})用来发送电子邮件

但为了反应

我试图在头中添加提到的代码(脚本标签)index.html
并尝试将其用作Email.send({})并且window.Email.send({})
它没有识别Email
所以我的问题是如何在反应中使用库,因为我在 index.html 中添加了它

编辑:

我在发送电子邮件时收到此错误
  The SMTP server requires a secure connection or the client was not 
  authenticated. The server response was: 5.7.0 Authentication Required. Learn 
  more at - Fix: Try a different SMTP server : 
  https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7- 
  911f6097521c

我为谷歌启用了不太安全的应用程序,还关闭了两步验证,但它没有帮助

4

1 回答 1

2

您的<script>标签正在向Email全局window对象添加一个属性,但 TypeScript 不知道这一点。你需要告诉 TypeScript 这个属性存在以及它是什么类型。

由于这个包非常简单,我继续创建了一个类型声明文件。我遵循了Global Libraries 上的 TypeScript 文档中的指南和示例。

// Type definitions for SmtpJs
// Project: https://smtpjs.com/
// Definitions by: Linda Paiste https://github.com/lindapaiste

// SmtpJS exposes a variable `Email` on the global `window` object
declare namespace Email {
  type Attachment =
    | {
        name: string;
        path: string;
      }
    | {
        name: string;
        data: string; // base64 format
      };

  interface EmailData {
    SecureToken: string;
    To: string | string[];
    From: string;
    Subject: string;
    Body: string;
    Attachments?: Attachment[];
  }

  function send(email: EmailData): Promise<string>;
}

我会将它发布到@types/smtpjs.com,但现在我将它包含在src项目的目录中。

现在我们需要让 TypeScript 来读取这个文件并包含它的类型。正如Matt McCutchen 在这个答案中所解释的,该文件应该被命名index.d.ts,并且它应该位于具有包名称的目录中。该目录应该在包类型的目录中。

我认为如果您能够将文件放在./src/@types/smtpjs/index.d.ts. CodeSandbox不允许名称中包含特殊字符,因此我必须使用没有 的位置,./src/types/smtpjs/index.d.ts@使用.typeRootstsconfig.json

"compilerOptions": {
...
  "typeRoots": [
    "./node_modules/@types/",
    "./src/types"
  ]
}

一切设置好后,您在访问window.Emailwindow.Email.send(). 如果要访问特定类型以将它们用于变量,可以使用Email.EmailDataEmail.Attachement

CodeSandbox 演示

于 2021-04-21T19:59:02.980 回答