簡體   English   中英

如何通過 reactjs 中的“smtpjs”發送電子郵件

[英]How to send emails via "smtpjs" in reactjs

每當用戶單擊提交時,我想通過表單發送 email

為此我使用smtpjs package 你可以在這里查看網站https://smtpjs.com/

在純js中我們必須在html頭標簽中添加這行代碼

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

然后我們可以使用Email.send({})發送 email

但為了反應

我試圖在index.html的頭部添加提到的代碼(腳本標簽)
並嘗試將其用作Email.send({})window.Email.send({})
它不識別Email
所以我的問題是如何在反應中使用該庫,因為我將它添加到 index.html

編輯:

發送 email 時出現此錯誤
 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

我為谷歌啟用了不太安全的應用程序,還關閉了兩步驗證,但它沒有幫助

您的<script>標簽正在將屬性Email添加到全局window object,但 Z558B544CF685F39D3867E4903E39 不知道。 您需要告訴 TypeScript 該屬性存在以及它是什么類型。

由於這個 package 非常簡單,我繼續創建一個類型聲明文件。 我遵循了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 ,並且它應位於名稱為 package 的目錄中。 該目錄應位於 package 類型的目錄中。

如果您能夠將文件放在./src/@types/smtpjs/index.d.ts ,我認為您可以在此處跳過幾個步驟。 CodeSandbox 不允許名稱中包含特殊字符,因此我必須使用不帶@的位置./src/types/smtpjs/index.d.ts並使用 tsconfig.json 中的typeRoots編譯器選項告訴tsconfig.json有關此類型目錄的信息。

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

Once everything is set up, you get full TypeScript support when accessing window.Email or window.Email.send() . 如果要訪問特定類型以將它們用於變量,可以使用Email.EmailDataEmail.Attachement

CodeSandbox 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM