How to Send Confirmation Email using Nodemailer and SendGrid

Learn how to create a confirmation link and then send it to the registered user using nodemailer and send grid email service.

#nuxtjs #apolloserver   #sendgrid #Nodemailer

How to Send Confirmation Email using Nodemailer and SendGrid
React Tutorial

React Tutorial

1629268725

How to Send Emails in a React App using Netlify Functions and SendGrid

Automatically send emails to users of your React app without setting up a server by using Netlify Functions.

With popular JavaScript frameworks and libraries such as React, Angular, and Vue, you can develop complex single-page applications and host them on platforms such as Netlify in only a few steps.

However, you might want to use these apps to run jobs, such as sending emails and accessing secret API credentials, which ordinarily requires setting up a server. Such jobs are usually impossible or ill-advised to run on the frontend. However, Netlify provides features for performing such actions from your Jamstack application without having to deploy a server.

One such feature is Netlify Functions. The goal of this article is to teach you how to send emails in a React application using event-driven Netlify Functions and SendGrid. The email will be in response to a form submission by a client.

Though we will be using React, the process should be similar for other frameworks with some slight variations.

#react #netlify #sendgrid

How to Send Emails in a React App using Netlify Functions and SendGrid
Erna  Herzog

Erna Herzog

1626495180

Send Emails From Your Next.js App With Sendgrid

Learn how to send transactional emails from your Next.js application using Sendgrid and Dynamic Templates.

🗂 CODE: https://gum.co/klXhE

⏰ TIMESTAMPS ⏰

Introduction: 0:00

Email Template: 0:57

Inline the CSS: 5:00

Add the Dynamic Template in Sendgrid: 6:20

Create the Email Class in Next.js: 7:49

Using the Email Class in Login Route: 10:53

Demo: 13:07

#next #javascript #nextjs #dev #sendgrid

Send Emails From Your Next.js App With Sendgrid
Franz  Becker

Franz Becker

1623927240

Full Testing of HTML Emails using SendGrid and Ethereal Accounts

Imagine you are sending beautiful HTML emails using your own SMTP server or even a 3rd party service like SendGrid. What if the emails are formatted incorrectly? What if the template string is incorrect and the user sees Dear <<undefined>>? Can you test the emails to make sure they really work?

In this blog post I will describe the full cycle email testing. We will send actual emails using 3rd party service SendGrid and we will fetch that email from a temporary email account hosted by Ethereal.email service to test it using Cypress Test Runner.

You can find the full source code for this blog post at cypress-ethereal-email-example.

The application

Our application is a Next.js web app where the user can register for a service. To cut down on bots, the registration sends the user an email with the confirmation code to be entered by the user to complete the registration process.

The user enters their email to register

The email is sent by the application using the SendGrid SMTP server. The email includes the plaintext and rich HTML versions.

If we click on the “Confirm registration” button, the browser opens at the app’s URL, in the simplest case at localhost:3000/confirm and if the user enters the right code the registration is complete.

Let’s look how we can test the confirmation email flow.

#tutorials #html #emails #sendgrid #ethereal accounts

Full Testing of HTML Emails using SendGrid and Ethereal Accounts
Royce  Reinger

Royce Reinger

1623735840

Build a Serverless Delivery Command Center on GCP

Combine Maps, OR-Tools, SendGrid and Cloud Functions to commandeer a delivery fleet

This article shows how to:

1. Set up a Cloud Storage in GCP that triggers a Cloud Function when a file is uploaded;

2. Set up a Cloud Function that calculates the optimal routing strategies with Google Maps and Google OR-Tools;

3. Send instruction emails to the carriers via SendGrid;

4. Set up Cloud Build for continuous deployment.

It is amazing how many modern business solutions can be built on the cloud with just a few services. Developers can combine cloud components to make a pipeline that goes from data ingestion to sending the results via emails with just a few clicks. The pricing is flexible. Hardware provision is minimal, especially with the serverless option. As a result, small businesses can now afford a huge amount of computational capacities. This democratization of computing power rapidly modernizes many traditional businesses. One of them must be the delivery service.

I came across two articles here on Medium: one by  Sebastian Telsemeyer  about building a time series forecast pipeline on GCP with Cloud Run and Pub/Sub:

The second one is by  Samir Saci, who uses the Goolge OR-Tools to optimize the last-mile delivery (the  solution was proposed first by Goolge in 2020 however):

Optimize E-Co

Sebastian’s article is inspiring. In his pipeline, a Pub/Sub monitors a specific GCP bucket. When a TSV file is uploaded, it activates a Cloud Run computation that generates the results in a second bucket. His whole infrastructure is serverless and codified in Terraform. In my opinion, his pipeline can even be simpler: a Cloud Function triggered by a Finalise/Create  event can replace the “Pub/Sub + Cloud Run” combination. The simpler version requires fewer setups. Because Cloud Function is basically a Lambda function, it thus gets rid of the whole Docker part and the Gunicorn + Flask dependency.

#sendgrid #delivery #google-or-tools #gcp

Build a Serverless Delivery Command Center on GCP

Send Emails with SendGrid & Next.js Serverless Functions - Contact Form Tutorial

Learn how to programmatically send emails from Serverless functions with SendGrid and Next.js.

🧐 What’s Inside

  • 00:00 Intro to sending emails with SendGrid and Next.js Serverless Functions
  • 00:10 Tools we’re using like SendGrid and Next.js API Routes
  • 00:49 Creating a new Next.js app with Create Next App
  • 01:26 Setting up and styling a basic contact form with React in Next.js
  • 03:21 Capturing form submissions events and data in React with onSubmit
  • 05:56 Adding a new Next.js API route to POST contact form data to
  • 08:42 Configuring custom domain authentication in SendGrid
  • 10:26 Installing CNAME DNS records for SendGrid in Google Domains
  • 12:19 Creating a SendGrid API key and adding it as a Next.js environment variable
  • 13:59 Installing SendGrid mail SDK to programmatically send emails
  • 17:43 Outro

🗒️ Read More
https://spacejelly.dev/posts/how-to-send-emails-with-sendgrid-and-next-js-serverless-functions-for-a-contact-form/

#serverless #next #sendgrid

Send Emails with SendGrid & Next.js Serverless Functions - Contact Form Tutorial

How to Send Emails with Node.js using SendGrid

Learn how to use Node.js and SendGrid, the industry leader in the transactional email space, to send an order confirmation email to customers.

Email remains one of the most widely used methods of written communication, especially for businesses. Whether to share marketing info, transactional records, or anything else, there are multiple ways to send emails. In this post, we’ll see how we can use Node.js and SendGrid to send an order confirmation (transactional) email to our customers when they place an order.

Why use SendGrid to send emails with Node.js?

We can send emails in a variety of ways from any programming language, Node.js included. We could use a package like Nodemailer, for example, which can use multiple transports like SMTP, Sendmail, or even Amazon SES.

The problem with a random SMTP or Sendmail, however, is that the emails will most likely be classified as spam and land in our customers’ junk folders. And we definitely don’t want that to happen.

To tackle this issue, it is best to use a trusted third-party email SaaS. SendGrid is arguably the industry leader in the transactional email space. Their pricing starts at $14.95 for 50K emails per month.

For our purposes, though, they have a free plan that still lets us send up to 100 emails a day. In addition to better delivery, they provide essential features like analytics and a template editor.

Prerequisites

Below are some of the prerequisites for this hands-on tutorial:

  1. You are generally aware of how JavaScript and Node.js work
  2. You know about the async/await syntax in JavaScript
  3. You know how to use the node command in the command line
  4. You are aware of the Express.js function and how middlewares work in Express.js

Next, we’ll get started with setting up SendGrid to send emails. Let’s get cracking!

How to send emails with Node.js and SendGrid

To send emails using SendGrid from Node.js, we will first need to register for a free SendGrid account. Then we can follow their step-by-step email API integration guide as follows.

#node #ndoejs #javascript #sendgrid #email

How to Send Emails with Node.js using SendGrid
Fredy  Larson

Fredy Larson

1601353260

Low Code Serverless Integration With SendGrid Using Kumologica

When making an online purchase, customers expect to receive purchase receipt emails from the vendor they do business with. Any delays in receipt of email, or emails being delivered to the spam folder can lead to a poor customer experience and may impact your brand and potentially may impact revenue.

Few aspects for having a good purchase receipts are :

  1. Proper branding and design of your purchase receipt.
  2. Proper furnishing of purchase content.- Price, Shipping, order date etc.
  3. Responsive nature of purchase receipt email.

SendGrid is a communication platform for transactional and marketing email delivery. It provides features for configuring email templates that can be used for the email delivery for different scenarios such as transaction emails, account creation emails, password reset emails, purchase receipt emails, account notification emails and more. In this article, we see how to build a simple order management service that will furnish and send a purchase receipt email using SendGrid. The service will integrate with SendGrid using Kumologica SendGrid node.

Kumologica is a free low-code development tool to build serverless integrations. You can learn more about Kumologica in this medium article or subscribe to our YouTube channel for the latest videos.


Use Case

We are going to implement a simple order management service for an online shopping portal. This service will accept the request from the shopping portal (UI) when the customer makes a purchase. The request will be first stored in an order management System database and then the price calculation is carried out by the service before sending the purchase receipt email to the customer.

Flow logic

#integration #aws #serverless #microservice #aws lambda #low code #sendgrid #kumologica

Low Code Serverless Integration With SendGrid Using Kumologica
Terry  Tremblay

Terry Tremblay

1601233680

Handling user registration

In this post we will add an endpoint to handle user registration request, including:

  • Add an endpoint /register to handling user registration progress
  • Hashing password with bcrypt
  • Sending notifications via SendGrid mail service

Registering a new user

Generate a register controller.

nest g controller user/register --flat

Fill the following content into the RegisterController.

// user/register.controller.ts

@Controller('register')
export class RegisterController {
    constructor(private userService: UserService) { }
    @Post()
    register(
        @Body() registerDto: RegisterDto,
        @Res() res: Response): Observable<Response> {
        const username = registerDto.username;
        return this.userService.existsByUsername(username).pipe(
            flatMap(exists => {
                if (exists) {
                    throw new ConflictException(`username:${username} is existed`)
                }
                else {
                    const email = registerDto.email;
                    return this.userService.existsByEmail(email).pipe(
                        flatMap(exists => {
                            if (exists) {
                                throw new ConflictException(`email:${email} is existed`)
                            }
                            else {
                                return this.userService.register(registerDto).pipe(
                                    map(user =>
                                        res.location('/users/' + user.id)
                                            .status(201)
                                            .send()
                                    )
                                );
                            }
                        })
                    );
                }
            })
        );
    }
}

In the above codes, we will check user existence by username and email respectively, then save the user data into the MongoDB database.

In the UserService, add the missing methods.

@Injectable()
export class UserService {

  existsByUsername(username: string): Observable<boolean> {
    return from(this.userModel.exists({ username }));
  }
  existsByEmail(email: string): Observable<boolean> {
    return from(this.userModel.exists({ email }));
  }
  register(data: RegisterDto): Observable<User> {
    const created = this.userModel.create({
      ...data,
      roles: [RoleType.USER]
    });
    return from(created);
  }
  //...
}

Create a DTO class to represent the user registration request data. Generate the DTO skeleton firstly.

nest g class user/register.dto --flat

And fill the following content.

import { IsEmail, IsNotEmpty, MaxLength, MinLength } from "class-validator";

export class RegisterDto {
    @IsNotEmpty()
    readonly username: string;
    @IsNotEmpty()
    @IsEmail()
    readonly email: string;
    @IsNotEmpty()
    @MinLength(8, { message: " The min length of password is 8 " })
    @MaxLength(20, { message: " The password can't accept more than 20 characters " })
    // @Matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,20}$/,
    //     { message: " A password at least contains one numeric digit, one supercase char and one lowercase char" }
    // )
    readonly password: string;
    @IsNotEmpty()
    readonly firstName?: string;
    @IsNotEmpty()
    readonly lastName?: string;
}

#nestjs #nodejs #sendgrid #javascript #programming

Handling user registration
Enoch Barcenas

Enoch Barcenas

1594956444

Receiving Emails with Bref PHP and SendGrid

Bref is a composer package that makes it easy to run serverless PHP applications on AWS Lambda. It achieves this by providing the required layers needed to run PHP applications since they are not supported natively on Lambda.

In this tutorial, we will be building and deploying a serverless PHP application that processes incoming emails programmatically using SendGrid Inbound Parse.

Prerequisites

To follow along, you will need:

  • PHP >= 7.2 (to use the latest version of Bref)
  • Composer, npm, and the serverless CLI installed
  • SendGrid Inbound Parse configured for your domain/subdomain (so that SendGrid can handle all incoming emails for such domain)
  • Ngrok installed (to expose your Bref application while developing locally)

Installing Bref and application dependencies

To get started, create a folder for your application (I am naming mine bref-email-watch) and enter into the directory with the command below:

$ mkdir bref-email-watch && cd bref-email-watch

Install the application dependencies which comprise the bref CLI, phpdotenv to enable us to load environment variables from a .env file, and nexylan/slack to interact with Slack’s API:

$ composer require bref/bref vlucas/phpdotenv nexylan/slack php-http/discovery

With our dependencies installed, initialize Bref by running ./vendor/bin/bref in the project directory and select the HTTP option from the interactive menu.

Output of “bref init” commandOutput of “bref init” command

The command will create a serverless.yml file which acts as the manifest for how the serverless framework will deploy your application as well as an index.php file to serve as an entry point into the application.

Next, create a .env file in the project folder and add the Slack hook URL:

SLACK_HOOK_URL="HERE_LIVES_YOUR_SLACK_HOOK_URL"

Parsing incoming emails from SendGrid

The application works by receiving JSON payloads (in the form of HTTP post requests) from SendGrid each time there is a new mail on the configured domain. We will modify the generated index.php file to parse these payloads, extract the sender and the recipient (using regex and PHP’s preg_match()), and send a Slack message to the relevant channel containing the extracted data.

Open the index.php file and replace its content with the code block below:

try {
    if (strtoupper($_SERVER['REQUEST_METHOD'] != 'POST')) {
        throw new Exception("Received non-post request on webhook handler");
    }

    if (json_last_error() != JSON_ERROR_NONE) {
        $em = "Error while parsing payload: ".json_last_error_msg();
        throw new Exception($em);
    }

    $from = $_POST['from'];
    $to = $_POST['to'];

    preg_match("#<(.*?)>#", $from, $sender);
    preg_match("#<(.*?)>#", $to, $recipient);
    $senderAddr = $sender[1];
    $recipientAddr = $recipient[1];

    $message = "*You've got mail!*\n";
    $message .= "*To:* ".$recipientAddr."\n";
    $message .= "*From:* ".$senderAddr;

    notifyOnSlack($message, true);

    // send OK back to SendGrid so they stop bothering our webhook
    header("Content-type: application/json; charset=utf-8");
    echo json_encode(["message" => "OK"]);
    exit(0);
} catch (Exception $e) {
    notifyOnSlack($e->getMessage());
    header("Content-type: application/json; charset=utf-8");
    http_response_code(400);
    echo json_encode(["message" => $e->getMessage()]);
    exit(0);
}

Sending slack notifications for new emails

In the previous code block, we referenced a notifyOnSlack function that doesn’t exist yet. This function is responsible for sending the $message parameter it receives to Slack. To implement it, load the variables declared in the .env file into your application by adding the following code to the top of the index.php file (just before the try block):

require_once './vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

Next, wire up the function implementation, like this:

function notifyOnSlack($message, $markdown = false)
{
    $slackHookUrl = $_ENV["SLACK_HOOK_URL"];
    $options = [
        "channel" => "#general",
        "allow_markdown" => $markdown,
        "username" => "bref-email-watch",
    ];
    $client = new Nexy\Slack\Client(
        \Http\Discovery\Psr18ClientDiscovery::find(),
        \Http\Discovery\Psr17FactoryDiscovery::findRequestFactory(),
        \Http\Discovery\Psr17FactoryDiscovery::findStreamFactory(),
        $slackHookUrl,
        $options
    );
    $client->send($message);
}

The function loads the SLACK_HOOK_URL environment variable from the .env file and then sets up the options, which includes the channel the message is to be sent to, to then be passed to the Slack client. We also instantiate the client by passing in the HTTPlug discovery services which allow it to find and use any HTTP client that conforms to the PSR standard.

Testing the serverless functions locally

Now that our application is set up, start the built-in PHP server on port 3000 and open an ngrok tunnel on the same port:

$ php -S localhost:3000
$ ngrok http 3000

The ngrok command generates Forwarding URL, like this_:_

ngrok command output

Copy the URL and visit your SendGrid’s Inbound Parse settings page. Now, click on the Add Host & URL button and paste in the copied URL in the Destination URL field.

Inbound Parse webhook settings

You may want to set up a proper subdomain since SendGrid will notify your webhook of EVERY email that comes to the domain name (irrespective of the username).

Next, send an email to an email address on the domain you specified and the notification should show up on Slack like this:

sample slack notificationsample slack notification

#php #sendgrid #serverless #developer

Receiving Emails with Bref PHP and SendGrid