F5 Sites
  • F5.com
  • LearnF5
  • NGINX
  • MyF5
  • Partner Central
Contact
  • Under Attack?
  • F5 Support
  • DevCentral Support
  • F5 Sales
  • NGINX Sales
  • F5 Professional Services
Brand LogoSkip to content
Forums
CrowdSRC
Articles
Groups
EventsSuggestionsHow Do I...?
RegisterSign In
  1. DevCentral
  2. CrowdSRC
  3. CodeShare

Send OTP via sendgrid(email) API

Problem this snippet solves: This is an example of how to send an OTP generated by the Big-IP via email using the sendgrid api. Preparations Register a free Sendgrid account: https://sendgr...
Updated Jun 06, 2023
Version 2.0
application delivery
BIG-IP Access Policy Manager (APM)
devops
iRulesLX
sendgrid
Alex_Nimo_26616's avatar
Alex_Nimo_26616
Icon for Altocumulus rankAltocumulus
Joined May 05, 2019
View Profile
playdohsniffer's avatar
playdohsniffer
Icon for Nimbostratus rankNimbostratus
Jan 28, 2020

Hi,

 

First off, good job on this article.

 

Did you actually test this with the simple email option enabled? I'm attempting to get it working on BIG-IP v 15.1.0, but I'm finding that your index.js TCL code for simple email doesn't seem to be working.

 

I've tried both importing your workspace archive, and rolling the entire config by hand, same result.

 

I started by created the iLX workspace from scratch, added a new extension, and finally installed the plugin using this command:

npm install --save --no-bin-links @sendgrid/mail

(BTW I was told by f5 support to always use the "--no-bin-links" option with npm so that no symbolic links create dependencies..there's a bug ID to require it on future versions). 

 

I wish to use the first (simple) email option. But when I disable (comment out) the default email option, and copy/paste the code into index.js, the TCL interpreter throws a number of warnings..which I've played with for 8 hours now...can't figure it out.

 

I've also tried just copying/using lines 1 - 44.

 

Can you verify if you can get the following working???

'use strict';
 
// Import the f5-nodejs module.
var f5 = require('f5-nodejs');
 
// Import the sendgrid module.
const sgMail = require('@sendgrid/mail');
 
//Set API key
var api_key = "PASTE API KEY HERE"
sgMail.setApiKey(api_key);
 
// Create a new rpc server for listening to TCL iRule calls.
var ilx = new f5.ILXServer();
 
//Construct email
ilx.addMethod('ilx_sendmail', function(tclArgs, funcResp) {
    console.log("Method Invoked, Args:", tclArgs.params());
    
    const userEmail = tclArgs.params()[2];
    var emailText = 'Dear' + tclArgs.params()[0] + ' Your OTP is: ' + tclArgs.params()[1];
    
// START OF METHOD 1: Use this method to send regular email
const msg = {
  to: userEmail,
  from: 'OTP_Admin@otptest.com',
  subject: 'Please See your OTP',
  text: emailText,
 // html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
 
//Send email
sgMail.send(msg, (error, result) => {
    if (error) {
      console.log("Error sending email, the issue is:" + error)
      funcResp.reply(error);
    }
    else {
      return result
      funcResp.reply("email sent");
    }
  });
// END OF METHOD 1 
 
/*
// START OF METHOD 2: Use this method to send email with dynamic template
 
var http = require("https");
 
var options = {
  "method": "POST",
  "hostname": "api.sendgrid.com",
  "port": null,
  "path": "/v3/mail/send",
  "headers": {
    "authorization": "Bearer " + api_key,
    "content-type": "application/json"
  }
};
 
var req = http.request(options, function (res) {
  var chunks = [];
 
  res.on("data", function (chunk) {
    chunks.push(chunk);
  });
 
  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});
 
 
req.write(JSON.stringify({ personalizations: 
   [ { to: [ { email: userEmail , name: tclArgs.params()[0] } ],
       dynamic_template_data: 
        { user: tclArgs.params()[0],
          otp: tclArgs.params()[1],
          partysize: 4,
          english: true } } ],
  from: { email: 'OTP_Admin@otptest.com', name: 'OTP Admin' },
  reply_to: { email: 'OTP_Admin@otptest.com', name: 'OTP Admin' },
  template_id: 'PASTE TEMPLATE ID HERE' }));
req.end();
funcResp.reply("email sent");
});
 
ilx.listen();
// END OF METHOD 2
*/

 

Additionally, would we not require the ilx listener uncommented at the very end, even when using the simple email method?

Otherwise how is your ilx_sendmail method gonna be called?

 

ilx.listen();

 

 

Cheers.

ABOUT DEVCENTRAL

DevCentral NewsTechnical ForumTechnical ArticlesTechnical CrowdSRCCommunity GuidelinesDevCentral EULAGet a Developer Lab LicenseBecome a DevCentral MVP

RESOURCES

Product DocumentationWhite PapersGlossaryCustomer StoriesWebinarsFree Online CoursesF5 CertificationLearnF5 Training

SUPPORT

Manage SubscriptionsProfessional ServicesProfessional ServicesCreate a Service RequestSoftware DownloadsSupport Portal

PARTNERS

Find a Reseller PartnerTechnology AlliancesBecome an F5 PartnerLogin to Partner Central

F5 logo©2024 F5, Inc. All rights reserved.
TrademarksPoliciesPrivacyCalifornia PrivacyDo Not Sell My Personal Information