How to use @sendgrid/mail - 10 common examples

To help you get started, we’ve selected a few @sendgrid/mail examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github madhums / node-notifier / lib / notifier.js View on Github external
if(!/\@/.test(obj.to) || !/\@/.test(obj.from)) {
    throw new Error('Please specify proper to and from address');
  }

  if (this.config.service === 'postmark') {
    var Postmark = require('postmark');
    var postmark = new Postmark.ServerClient(this.config.key)
    options = {
      'From': obj.from,
      'To': obj.to,
      'Subject': obj.subject,
      'HtmlBody': html
    };
  } else if (this.config.service === 'sendgrid') {
    var sendgrid = require('@sendgrid/mail')
    sendgrid.setApiKey(this.config.key);
    options = {
      'to': obj.to,
      'from': obj.from,
      'subject': obj.subject,
      'html': html
    };
  }

  // as you don't want to send emails while development or testing
  if (process.env.NODE_ENV === 'test'
    || process.env.NODE_ENV === 'development') {
    // don't log during tests
    if (process.env.NODE_ENV !== 'test') {
      console.log(options);
    }
    cb();
github jpchip / giveaway-grabber / src / giveaways.js View on Github external
if (
				process.env.SENDGRID_API_KEY &&
				process.env.SENDGRID_API_KEY !== ''
			) {
				sgMail.setApiKey(process.env.SENDGRID_API_KEY);
				const msg = {
					to: process.env.AMAZON_USERNAME,
					from: process.env.AMAZON_USERNAME,
					subject: 'giveaway-grabber: You won!',
					text: winningEntryUrl
				};
				if (process.env.SENDGRID_CC && process.env.SENDGRID_CC !== '') {
					msg.cc = process.env.SENDGRID_CC;
				}
				console.log('sending email');
				await sgMail.send(msg);
			}
			//Store that we won
			await setProcessingCode(urlTypes.WIN, currentGiveawayUrl);
		} else {
			// Store that we lost
			await setProcessingCode(urlTypes.LOST, currentGiveawayUrl);
		}
		return true;
	} catch (error) {
		console.log('could not get result, oh well. Moving on!');
		return false;
	}
}
github OriginProtocol / origin / infra / bridge / src / utils / log-chat.js View on Github external
}

  const username = String(message.from.username || message.from.id)
  const messageText = message.text

  const email = {
    to:
      process.env.TELEGRAM_BOT_EMAIL ||
      'support+telegram-bot@originprotocol.com',
    from: process.env.SENDGRID_FROM_EMAIL,
    subject: `${username} has replied to Telegram Bot`,
    text: `> ${messageText}`
  }

  try {
    await sendgridMail.send(email)
  } catch (error) {
    logger.error(`Could not send email via SendGrid: ${error}`)
  }

  // Insert to DB
  await TelegramChatLog.create({
    rawPayload: message,
    message: messageText,
    userId: message.from.id,
    username
  })

  logger.debug('Logged chat from ', username)
}
github Lambda-School-Labs / CS9-KnowledgeRocket / server / mail / MailRouter.js View on Github external
personalizations,
            template_id: SG_TEMPLATE_ID,
            from: { email: 'noreply@krocket.com' },
            subject: `Knowledge Rocket: ${subject}`,
        });

        // DANGER
        // INEFFECIENT
        const [twoDayEmails, twoWeekEmails, twoMonthEmails] = emails.map(email =>
            email.map(handleEmailCreation(createPersonalization, createEmail))
        );

        const emailBatch = [
            sgMail.send(twoDayEmails),
            sgMail.send(twoWeekEmails),
            sgMail.send(twoMonthEmails),
        ];

        try {
            await Promise.all(emailBatch);
            res.json({
                success: true,
            });
        } catch (error) {
            res.json({
                error,
                success: false,
            });
        }
    } catch (err) {
        res.json({
            err,
github OriginProtocol / origin / infra / token-transfer-server / src / login.js View on Github external
process.env.ENCRYPTION_SECRET,
      { expiresIn: '5m' }
    )

    const data = {
      to: email,
      from: emailFrom,
      subject: 'Your T3 verification code',
      text: `Welcome to the Origin Investor Portal. Here is your single-use sign in link.

        ${process.env.PORTAL_URL ||
          'http://localhost:3000'}/login_handler/${token}.

        It will expire in 5 minutes. You can reply directly to this email with any questions.`
    }
    await sendgridMail.send(data)
    logger.info(`Sent email code to ${email}`)
  } else {
    // Do nothing in case email not found in our DB.
    // But do not let the caller know by returning anything different,
    // to avoid tipping them on whether or not the email exists.
    logger.info(`Email ${email} not found in DB. No code sent.`)
  }

  res.setHeader('Content-Type', 'application/json')
  res.send(JSON.stringify({ email }))
}
github Lambda-School-Labs / CS10-restaurant-pos / api / controllers / employees / adminRegister.js View on Github external
const mjml2html = require('mjml').default;

const keys = require('../../../config/keys');

const sendGridKey = keys.sendGrid;
// For emails
const sgMail = require('@sendgrid/mail'); // eslint-disable-line

sgMail.setApiKey(sendGridKey);

// verifyFields verifies that all required fields are provided
const verifyFields = require('../../validation/verifyFields');
const Employee = require('../../models/Employee');

// @route   POST api/employees/admin/register
// @desc    Adds an administrator to the DB
// @access  Public
const adminRegister = (req, res) => {
  const {
    name, pass, email, images
  } = req.body;

  // Validate Fields
  const missingFields = verifyFields(['name', 'pass', 'email'], req.body, res);
github OriginProtocol / origin / infra / token-transfer-server / src / lib / email.js View on Github external
const template = require('lodash/template')
const sendgridMail = require('@sendgrid/mail')
const jwt = require('jsonwebtoken')
const mjml2html = require('mjml')
const Sequelize = require('sequelize')

const { User } = require('../models')
const {
  encryptionSecret,
  clientUrl,
  sendgridFromEmail,
  sendgridApiKey
} = require('../config')
const logger = require('../logger')

sendgridMail.setApiKey(sendgridApiKey)

// Load and compile the email templates.
const templateDir = `${__dirname}/../templates`
const welcomeTextTemplate = template(
  fs.readFileSync(`${templateDir}/welcome.txt`).toString()
)
const welcomeMjmlTemplate = template(
  fs.readFileSync(`${templateDir}/welcome.mjml`).toString()
)
const loginTextTemplate = template(
  fs.readFileSync(`${templateDir}/login.txt`).toString()
)
const loginMjmlTemplate = template(
  fs.readFileSync(`${templateDir}/login.mjml`).toString()
)
const transferTextTemplate = template(
github ZolaApp / zola-api / src / server / sendGrid.js View on Github external
// @flow
import sendGrid from '@sendgrid/mail'

sendGrid.setApiKey(process.env.SENDGRID_API_KEY || '')
sendGrid.setSubstitutionWrappers('{{', '}}')

export default sendGrid
github CommerceQL / commerceql / oldsrc / sendOrderEmail.ts View on Github external
return new Promise((resolve, reject) => {
    sgMail
      .send(message)
      .then(() => {
        return resolve()
      })
      .catch(error => {
        console.log('Email could not be sent because an error occured:')
        console.log(error)

        return resolve({ error: error.message })
      })
  })
}
github jbergant / chatbot-facebook-v2-final / app.js View on Github external
function sendEmail(subject, content) {
	console.log('sending email!');
    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(config.SENGRID_API_KEY);
    const msg = {
        to: config.EMAIL_TO,
        from: config.EMAIL_FROM,
        subject: subject,
        text: content,
        html: content,
    };
    sgMail.send(msg)
		.then(() => {
        console.log('Email Sent!');
    })
	.catch(error => {
		console.log('Email NOT Sent!');
		console.error(error.toString());
	});

}

@sendgrid/mail

Twilio SendGrid NodeJS mail service

MIT
Latest version published 1 month ago

Package Health Score

95 / 100
Full package analysis

Similar packages