Skip to content

Instantly share code, notes, and snippets.

@tofran
Created April 24, 2023 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tofran/adbf0ced80e102f2963ae9f48138acec to your computer and use it in GitHub Desktop.
Save tofran/adbf0ced80e102f2963ae9f48138acec to your computer and use it in GitHub Desktop.
COMMUNICATION_SERVICES_CONNECTION_STRING=
EMAIL_SENDER=
{
"name": "sample-azure-email-sending",
"version": "0.0.1",
"type": "module",
"main": "index.js",
"scripts": {
"run": "./send-email.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@azure/communication-email": "^1.0.0",
"dotenv": "^16.0.3",
"inquirer": "^9.2.0"
}
}
import { EmailClient, KnownEmailSendStatus } from "@azure/communication-email";
import inquirer from "inquirer";
import dotenv from "dotenv";
dotenv.config();
const connectionString = process.env.COMMUNICATION_SERVICES_CONNECTION_STRING;
const emailClient = new EmailClient(connectionString);
async function sendEmail(destinationEmail, destinationName) {
const POLLER_WAIT_TIME_SECONDS = 10;
const message = {
senderAddress: process.env.EMAIL_SENDER,
content: {
subject: "Azure test email",
plainText:
"This email message is sent from Azure Communication Services Email using the JavaScript SDK.",
},
recipients: {
to: [
{
address: destinationEmail,
displayName: destinationName,
},
],
},
};
const poller = await emailClient.beginSend(message);
if (!poller.getOperationState().isStarted) {
throw "Poller was not started.";
}
// From now on, this code is just to demo that we can listen for events,
// and check the email status. It does not need to be implemented most situations,
// as we might not need the status to be reported (or may not want the long delay).
let timeElapsed = 0;
while (!poller.isDone()) {
poller.poll();
console.log("Email send polling in progress");
await new Promise((resolve) =>
setTimeout(resolve, POLLER_WAIT_TIME_SECONDS * 1000)
);
timeElapsed += 10;
if (timeElapsed > 18 * POLLER_WAIT_TIME_SECONDS) {
throw "Polling timed out.";
}
}
if (poller.getResult().status === KnownEmailSendStatus.Succeeded) {
console.log(
`Successfully sent the email (operation id: ${poller.getResult().id})`
);
} else {
throw poller.getResult().error;
}
}
inquirer
.prompt([
{
type: "input",
name: "email",
message: "Destination email address:",
},
{
type: "input",
name: "name",
message: "Destination name:",
},
])
.then((answers) => {
sendEmail(answers.email, answers.name);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment