Guide d'utilisation de SparkPost avec Node.js

Guide d'utilisation de SparkPost avec Node.js

Guide d'utilisation de SparkPost avec Node.js

Sep 1, 2017

Publié par

Publié par

Bird

Bird

-

Catégorie :

Catégorie :

Courriel :

Courriel :

Ready to see Bird
in action?

Ready to see Bird
in action?

A Guide to Using SparkPost with Node.js

Introduction à Node.js

As a Developer Advocate for SparkPost, I write a lot of sample applications. My background is mostly front-end development, therefore my strongest language is JavaScript. Thanks to Node.js, I’m a decent backend developer as well. Does this mean I’m a full stack developer now? Anyway, it was important for me that we had an awesome SparkPost client library for Node.js. So, I dove right in and became a contributor (avant même que je sois embauché).

Permettez-moi de vous aider à commencer à envoyer des e-mails avec SparkPost sur votre projet Node.js.


Installing & Setup

I’m going to assume that you have Node.js installé. Because we follow the Calendrier du support à long terme de Node.js (LTS), you’ll need to be running version 4 or higher. You can see which version you’re running using the `node –version` command in your terminal window.

Créons un nouveau projet npm. Si vous en avez déjà un, vous pouvez sauter cette partie.

> mkdir sparkpost-test > cd sparkpost-test > npm init --yes

Cela créera un nouveau projet et acceptera toutes les valeurs par défaut. Vous pouvez aussi lancer `npm init` et répondre à toutes les questions.

Now we can install node-sparkpost:

> npm install sparkpost --save

Une fois installé, vous pouvez importer et créer une instance de la classe SparkPost :

const SparkPost = require('sparkpost') const client = new SparkPost('YOUR API KEY')

It’s good practice to avoid putting your API key in code. We highly recommend storing it outside your code, so we set up the client library to detect the SPARKPOST_API_KEY  environment variable.


Envoi d'un courriel

Maintenant que vous avez une instance SparkPost, vous êtes prêt à envoyer. Il existe un grand nombre d'options disponibles pour l'envoi, mais commençons par un exemple simple. Voici comment envoyer un email à un seul destinataire, en spécifiant le contenu en ligne :

client.transmissions.send({ content: { from: 'test@your-sending-domain.com', subject: 'Hello from node-sparkpost', html: '<p>Hello world</p>' }, recipients: [ {address: 'someone@somedomain.com'} ] }) .then(data => { console.log('Woohoo! You just sent your first mailing!') console.log(data) }) .catch(err => { console.log('Whoops! Something went wrong') console.log(err) })

Note: This example uses Promises, but don’t worry. We also support des fonctions de rappel.

There are more options available with transmissions, including specifying stored templates or recipient lists, cc and bcc, adding attachments, specifying a campaign, using substitution data, and much more. Check out the examples, docs pour la ressource Transmissions, and the Documentation de l'API Transmissions for more info.


Bonus : Envoi d'e-mails avec Nodemailer

Nodemailer is a popular library for Node.js that make sending email “easy as cake.” For those of you choosing to use this library, we created a Transport SparkPost pour Nodemailer. You’ll need to install the nodemailer  and nodemailer-sparkpost-transport packages in your project.

> npm install nodemailer nodemailer-sparkpost-transport --save

Vous pouvez maintenant créer une instance de transport nodemailer :

const nodemailer = require('nodemailer') const sparkPostTransport = require('nodemailer-sparkpost-transport') const transporter = nodemailer.createTransport(sparkPostTransport({ 'sparkPostApiKey': process.env.SPARKPOST_API_KEY }))

 

Remarquez comment je lis la clé API à partir d'une variable d'environnement. C'est toujours une bonne pratique de ne jamais mettre cela directement dans votre code.

There are several options that can passed into the SparkPost transport, like campaign id and whether or not the message is transactional. Take a look au README.md for all the options.

Voici comment vous enverriez le même message ci-dessus en utilisant Nodemailer :

transporter.sendMail({ from: 'test@your-sending-domain.com', to: 'someone@somedomain.com', subject: 'Hello from nodemailer-sparkpost-transport', html: '<p>Hello world</p>' }, (err, info) => { if (err) { console.error(err); } else { console.log(info); } })


Double bonus : envoi d'e-mails avec notif.moi

We all know that email is king of communication but sometimes you want to be able to reach people via multiple channels. notif.me is a Node.js library for sending all kinds of transactional messages. Whether you want to send an email, sms, push, or webpushes, you can do it with ease. It also has built in fall and round robin strategies for multiple providers. We recently worked with the creators to build a SparkPost provider. You’ll need to install the `notifme-sdk` package in your project.

> npm install notifme-sdk --save

Vous pouvez maintenant créer une instance de notifme avec le fournisseur SparkPost :

const NotifmeSdk = require('notifme-sdk').default const notifmeSdk = new NotifmeSdk({ channels: { email: { providers: [{ type: 'sparkpost', apiKey: process.env.SPARKPOST_API_KEY, }] } } })

Encore une fois, nous tirons la clé API d'une variable d'environnement. Nous l'avons dit trois fois - c'est aussi important que cela 🙂 .

Répétons maintenant ce même exemple, en utilisant cette fois notif.me :

notifmeSdk.send({ email: { from: 'test@your-sending-domain.com', to: 'someone@somedomain.com', subject: 'Hello from the SparkPost notif.me provider', html: '<p>Hello world</p>' } }).then(console.log)

It’s really easy to use and I recommend looking au autres caractéristiques.

Il n'y a pas de mauvaise façon d'utiliser Node

Quand il s'agit d'envoyer des e-mails en utilisant Node.js, vous avez de nombreuses options. Nous avons travaillé dur pour vous aider à rendre cela aussi facile que possible.

Your new standard in Marketing, Pay & Sales. It's Bird

Le right message -> à la right person -> at the right time.

By clicking "See Bird" you agree to Bird's Avis de confidentialité.

Your new standard in Marketing, Pay & Sales. It's Bird

Le right message -> à la right person -> at the right time.

By clicking "See Bird" you agree to Bird's Avis de confidentialité.