Thierry  Perret

Thierry Perret

1658973600

Envoyer Des E-mails AWS SES Avec NodeJS Et TypeScript

Comment envoyer un e-mail avec AWS SES ? Ici, nous envoyons un e-mail de confirmation d'inscription à un utilisateur.

import { getHTMLTemplate, fillHtmlTemplate, sendEmail } from "../email"

export const sendEmailConfirmationLink = async (
  email: string,
  authLink: string
) => {
  const html = await getHTMLTemplate("auth")

  await sendEmail({
    email,
    body: fillHtmlTemplate(html, {
      "auth-link": authLink,
      email,
    }),
    subject: "Log in to Increaser",
    source: `Login <noreply@increaser.org>`,
  })
}

Tout d'abord, nous voulons prendre un modèle HTML. La fonction prend le nom du modèle et le lit à partir du fichier. Je rends les noms de modèles identiques au HtmlTemplatetype.

export const getHTMLTemplate = memoize((template: HtmlTemplate) => {
  return readFile(
    path.resolve(__dirname, `../../templates/${template}.html`),
    "utf8"
  )
})

Je n'envoie généralement pas d'e-mails avec un style fantaisiste pour ne pas apparaître dans les spams ou les onglets de promotion des destinataires.

Dans le auth-emailmodèle, nous attendons deux variables - auth-link et email.

<p>Click the link below to sign in to <b>Increaser</b>.</p>

<p>This link will expire in 20 minutes.</p>

<a href={{auth-link}}>Sign in to Increaser</a>

<p>Confirming this request will securely sign you in using {{email}}.</p>

- Increaser Team

Une fois que nous aurons lu le fichier dans une chaîne, nous utiliserons la fillHtmlTemplatefonction pour insérer des variables dans un e-mail html.

export const fillHtmlTemplate = (
  html: string,
  variables: Record<string, string>
) => {
  let result = html
  Object.entries(variables).forEach(([key, value]) => {
    result = result.split(`{{${key}}}`).join(value)
  })

  return result
}

Nous transmettons l'e-mail du destinataire, le corps HTML, l'objet et la source à la sendEmailfonction.

J'ai exécuté mon Lambda dans la région européenne, mais AWS SES ne fonctionne pas là-bas. Je passe donc explicitement la région de Virginie au constructeur SES.

interface SendEmailParameters {
  email: string
  body: string
  subject: string
  source: string
}

const ses = new aws.SES({ region: "us-east-1" })

export const sendEmail = ({
  email,
  body,
  subject,
  source,
}: SendEmailParameters) =>
  ses
    .sendEmail({
      Destination: {
        ToAddresses: [email],
      },
      Message: {
        Body: {
          Html: {
            Data: body,
          },
        },
        Subject: {
          Data: subject,
        },
      },
      Source: source,
    })
    .promise()

Nous passons Destination, Messageet Sourceà la méthode SES et en faisons une promesse.

Source : https://radzion.com/blog/ses-send

#typescript #nodejs #aws 

What is GEEK

Buddha Community

Envoyer Des E-mails AWS SES Avec NodeJS Et TypeScript
Thierry  Perret

Thierry Perret

1658973600

Envoyer Des E-mails AWS SES Avec NodeJS Et TypeScript

Comment envoyer un e-mail avec AWS SES ? Ici, nous envoyons un e-mail de confirmation d'inscription à un utilisateur.

import { getHTMLTemplate, fillHtmlTemplate, sendEmail } from "../email"

export const sendEmailConfirmationLink = async (
  email: string,
  authLink: string
) => {
  const html = await getHTMLTemplate("auth")

  await sendEmail({
    email,
    body: fillHtmlTemplate(html, {
      "auth-link": authLink,
      email,
    }),
    subject: "Log in to Increaser",
    source: `Login <noreply@increaser.org>`,
  })
}

Tout d'abord, nous voulons prendre un modèle HTML. La fonction prend le nom du modèle et le lit à partir du fichier. Je rends les noms de modèles identiques au HtmlTemplatetype.

export const getHTMLTemplate = memoize((template: HtmlTemplate) => {
  return readFile(
    path.resolve(__dirname, `../../templates/${template}.html`),
    "utf8"
  )
})

Je n'envoie généralement pas d'e-mails avec un style fantaisiste pour ne pas apparaître dans les spams ou les onglets de promotion des destinataires.

Dans le auth-emailmodèle, nous attendons deux variables - auth-link et email.

<p>Click the link below to sign in to <b>Increaser</b>.</p>

<p>This link will expire in 20 minutes.</p>

<a href={{auth-link}}>Sign in to Increaser</a>

<p>Confirming this request will securely sign you in using {{email}}.</p>

- Increaser Team

Une fois que nous aurons lu le fichier dans une chaîne, nous utiliserons la fillHtmlTemplatefonction pour insérer des variables dans un e-mail html.

export const fillHtmlTemplate = (
  html: string,
  variables: Record<string, string>
) => {
  let result = html
  Object.entries(variables).forEach(([key, value]) => {
    result = result.split(`{{${key}}}`).join(value)
  })

  return result
}

Nous transmettons l'e-mail du destinataire, le corps HTML, l'objet et la source à la sendEmailfonction.

J'ai exécuté mon Lambda dans la région européenne, mais AWS SES ne fonctionne pas là-bas. Je passe donc explicitement la région de Virginie au constructeur SES.

interface SendEmailParameters {
  email: string
  body: string
  subject: string
  source: string
}

const ses = new aws.SES({ region: "us-east-1" })

export const sendEmail = ({
  email,
  body,
  subject,
  source,
}: SendEmailParameters) =>
  ses
    .sendEmail({
      Destination: {
        ToAddresses: [email],
      },
      Message: {
        Body: {
          Html: {
            Data: body,
          },
        },
        Subject: {
          Data: subject,
        },
      },
      Source: source,
    })
    .promise()

Nous passons Destination, Messageet Sourceà la méthode SES et en faisons une promesse.

Source : https://radzion.com/blog/ses-send

#typescript #nodejs #aws 

Mélanie  Faria

Mélanie Faria

1658973600

Envie E-mails Do AWS SES Com NodeJS E TypeScript

Como enviar um e-mail com o AWS SES? Aqui, enviamos um e-mail de confirmação de inscrição para um usuário.

import { getHTMLTemplate, fillHtmlTemplate, sendEmail } from "../email"

export const sendEmailConfirmationLink = async (
  email: string,
  authLink: string
) => {
  const html = await getHTMLTemplate("auth")

  await sendEmail({
    email,
    body: fillHtmlTemplate(html, {
      "auth-link": authLink,
      email,
    }),
    subject: "Log in to Increaser",
    source: `Login <noreply@increaser.org>`,
  })
}

Primeiro, queremos pegar um modelo HTML. A função pega o nome do modelo e o lê do arquivo. Eu faço nomes de modelo iguais ao HtmlTemplatetipo.

export const getHTMLTemplate = memoize((template: HtmlTemplate) => {
  return readFile(
    path.resolve(__dirname, `../../templates/${template}.html`),
    "utf8"
  )
})

Não costumo enviar e-mails com um estilo sofisticado para não aparecer nas guias de spam ou promoção do destinatário.

No auth-emailmodelo, esperamos duas variáveis ​​- auth-link e email.

<p>Click the link below to sign in to <b>Increaser</b>.</p>

<p>This link will expire in 20 minutes.</p>

<a href={{auth-link}}>Sign in to Increaser</a>

<p>Confirming this request will securely sign you in using {{email}}.</p>

- Increaser Team

Depois de lermos o arquivo em uma string, usaremos a fillHtmlTemplatefunção para inserir variáveis ​​em um html de e-mail.

export const fillHtmlTemplate = (
  html: string,
  variables: Record<string, string>
) => {
  let result = html
  Object.entries(variables).forEach(([key, value]) => {
    result = result.split(`{{${key}}}`).join(value)
  })

  return result
}

Passamos o email do destinatário, corpo HTML, assunto e fonte para a sendEmailfunção.

Executei meu Lambda na região europeia, mas o AWS SES não funciona lá. Então, passo explicitamente a região da Virgínia para o construtor SES.

interface SendEmailParameters {
  email: string
  body: string
  subject: string
  source: string
}

const ses = new aws.SES({ region: "us-east-1" })

export const sendEmail = ({
  email,
  body,
  subject,
  source,
}: SendEmailParameters) =>
  ses
    .sendEmail({
      Destination: {
        ToAddresses: [email],
      },
      Message: {
        Body: {
          Html: {
            Data: body,
          },
        },
        Subject: {
          Data: subject,
        },
      },
      Source: source,
    })
    .promise()

Passamos Destination, Messagee Sourcepara o método SES e o transformamos em uma promessa.

Fonte: https://radzion.com/blog/ses-send

#typescript #nodejs #aws 

Send AWS SES Emails with NodeJS & TypeScript

How to send an email with AWS SES? Here we send a signup confirmation email to a user.

See more at: https://radzion.com/blog/ses-send

#typescript #nodejs #aws 

Hong  Nhung

Hong Nhung

1658977380

Gửi Email AWS SES Bằng NodeJS & TypeScript

Làm cách nào để gửi email với AWS SES? Tại đây, chúng tôi gửi một email xác nhận đăng ký đến người dùng.

import { getHTMLTemplate, fillHtmlTemplate, sendEmail } from "../email"

export const sendEmailConfirmationLink = async (
  email: string,
  authLink: string
) => {
  const html = await getHTMLTemplate("auth")

  await sendEmail({
    email,
    body: fillHtmlTemplate(html, {
      "auth-link": authLink,
      email,
    }),
    subject: "Log in to Increaser",
    source: `Login <noreply@increaser.org>`,
  })
}

Đầu tiên, chúng tôi muốn lấy một mẫu HTML. Hàm lấy tên mẫu và đọc nó từ tệp. Tôi đặt tên mẫu giống như HtmlTemplatekiểu.

export const getHTMLTemplate = memoize((template: HtmlTemplate) => {
  return readFile(
    path.resolve(__dirname, `../../templates/${template}.html`),
    "utf8"
  )
})

Tôi không thường gửi email có kiểu dáng lạ mắt để không xuất hiện trong các tab thư rác hoặc quảng cáo của người nhận.

Trong auth-emailmẫu, chúng tôi mong đợi hai biến - liên kết auth và email.

<p>Click the link below to sign in to <b>Increaser</b>.</p>

<p>This link will expire in 20 minutes.</p>

<a href={{auth-link}}>Sign in to Increaser</a>

<p>Confirming this request will securely sign you in using {{email}}.</p>

- Increaser Team

Khi chúng tôi đã đọc tệp thành một chuỗi, chúng tôi sẽ sử dụng fillHtmlTemplatehàm để chèn các biến vào một email html.

export const fillHtmlTemplate = (
  html: string,
  variables: Record<string, string>
) => {
  let result = html
  Object.entries(variables).forEach(([key, value]) => {
    result = result.split(`{{${key}}}`).join(value)
  })

  return result
}

Chúng tôi chuyển email người nhận, nội dung HTML, chủ đề và nguồn cho sendEmailhàm.

Tôi đã chạy Lambda của mình ở khu vực Châu Âu, nhưng AWS SES không hoạt động ở đó. Vì vậy, tôi chuyển vùng Virginia một cách rõ ràng cho hàm tạo SES.

interface SendEmailParameters {
  email: string
  body: string
  subject: string
  source: string
}

const ses = new aws.SES({ region: "us-east-1" })

export const sendEmail = ({
  email,
  body,
  subject,
  source,
}: SendEmailParameters) =>
  ses
    .sendEmail({
      Destination: {
        ToAddresses: [email],
      },
      Message: {
        Body: {
          Html: {
            Data: body,
          },
        },
        Subject: {
          Data: subject,
        },
      },
      Source: source,
    })
    .promise()

Chúng tôi vượt qua Destination, MessageSourceđến phương pháp SES và biến nó thành một lời hứa.

Nguồn: https://radzion.com/blog/ses-send

#typescript #nodejs #aws 

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource