Question

In: Computer Science

How do i send random numbers in my Amazon SES email? What is the code for...

How do i send random numbers in my Amazon SES email? What is the code for it and where would it go Lambda or SES? Please provide step by step instructions

Solutions

Expert Solution

Table of Contents

Part 0: Introduction to the Complete AWS Web Boilerplate

Part 1: User Authentication with AWS Cognito (3 parts)

Part 2: Saving File Storage Costs with Amazon S3 (1 part)

Part 3: Sending Emails with Amazon SES (1 part)

Part 4: Manage Users and Permissions with AWS IAM [Coming Soon]

Part 5: Cloud Server Hosting with AWS EC2 and ELB[Coming Soon]

Part 6: The MongoDB Killer: AWS DynamoDB [Coming Soon]

Part 7: Painless SQL Scaling using AWS RDS [Coming Soon]

Part 8: Serverless Architecture with Amazon Lambda [Coming Soon]

Download the Github here.

Setup

Sending emails with Amazon SES is really straightforward. Let’s start at the set-up. Go to Amazon SES and click Email Addresses in the sidebar. Then click Verify a New Email Address and enter an email you want to use for messaging in the app.

Now go to your email provider and click the verification link. After verifying, go back to Amazon SES Email Addresses tab. You should now see your email verified.

This was necessary for 2 reasons. First is that we need an email for sending a message, and the second is because we are in a sandbox environment. A sandbox environment means you can only send and receive emails from verified addresses, and prevents you from spamming people. This is all the set-up we need for this boilerplate.

If you want be able to send emails to any email address, you need to make a written request to Amazon to graduate from the sandbox environment. To do this, navigate to the top-right hand corner at Support > Support Center.

At this next screen, click Create case.

This is a straightforward form, but we’ll briefly explain. Select Service Limit Increase and set the Limit Type to SES Sending Limits. Now create 2 requests, one where Limit is Desired Daily Sending Quota (how many emails can be sent in one day), and the other where Limit is Desired Maximum Send Rate. Set the New limit value to the amount that you need. Finally, optionally set the Mail Type as it increases you odds of approval. Use transactional if your emails are generated as a request of a user’s activity. There are others available for other use cases.

The rest of the request is easy. Make sure you agree to comply with the Terms of Service, and you have a process to handle bounces and complaints (for when users mark your email as spam). Finally, give a brief explanation of your use case.

Submit your code and you should get an email from Amazon with the results of your service increase request. Once approved, your app can send messages to any email.

The Code

We’re ready to dig into the code! Go to App/src/api/aws/aws_ses.js where the bulk of the code resides. Let’s take a look at the main function sendAWSEmail():

export function sendAWSEmail(email, message){ const ses = new AWS.SES({ region: 'us-east-1' }) const p = new Promise((res, rej)=>{ if(!email|| message){   rej('Missing user email or message content') }else{   const params = createInquiryParamsConfig(email, message)   // console.log('Sending email with attached params!')   AWS.config.credentials.refresh(function(){    // console.log(AWS.config.credentials)    ses.sendEmail(params, function(err, data) {      if(err){        // console.log(err, err.stack); // an error occurred        rej(err)      }else{       // console.log(data);           // successful response     res('Success! Email sent')      }    })   }) } }) return p}

This is extremely straightforward. We receive two arguments, an email to send to, and a message to be sent. The first thing we do in this function is instantiate the AWS SES object for interacting with AWS by simply passing in the region. Next we check if there is a recipient email and a message. If both are provided, then we can actually send the email.

Assuming we have both a recipient email and message, we will create a params object for AWS SES to read for all the info & options necessary. This params object is created with createInquiryParamsConfig(). Before we dive into that rabbit hole, let’s just quickly finish up explaining the rest of sendAWSEmail(). We refresh AWS Cognito user’s credentials (that we set with AWS Cognito, explained in my other tutorial) and call ses.sendEmail with params and a response callback passed in. Reject the promise if there is an error, and resolve with a success message if there is no error. ses.sendEmail is the only AWS function we will use, and everything else is we need is determined in params.

Now let’s see how to make params with createInquiryParamsConfig().

function createInquiryParamsConfig(email, message){ const params = {   Destination: {      BccAddresses: [],     CcAddresses: [],     ToAddresses: [ email ]   },   Message: {      Body: {        Html: {         Data: generateHTMLInquiryEmail(landlordEmail, message),         Charset: 'UTF-8'       }     },     Subject: {        Data: 'Kangzeroos Boilerplate says hi ' + email,       Charset: 'UTF-8'     }   },   Source: '[email protected]',    ReplyToAddresses: [ '[email protected]' ],   ReturnPath: '[email protected]' } return params}

Pretty straightforward, we pass in email and message, and return a big javascript object. All the values you see here are necessary, but you can add a ton of other optional configurations too. The function we must pay attention to is generateHTMLInquiryEmail(). Let’s look at that.

function generateHTMLInquiryEmail(email, message){ return `  <!DOCTYPE html>  <html>    <head>      <meta charset='UTF-8' />      <title>title</title>    </head>    <body>     <table border='0' cellpadding='0' cellspacing='0' height='100%' width='100%' id='bodyTable'>      <tr>          <td align='center' valign='top'>              <table border='0' cellpadding='20' cellspacing='0' width='600' id='emailContainer'>                  <tr style='background-color:#99ccff;'>                      <td align='center' valign='top'>                          <table border='0' cellpadding='20' cellspacing='0' width='100%' id='emailBody'>                              <tr>                                  <td align='center' valign='top' style='color:#337ab7;'>                                      <h3>${message}</h3>                                  </td>                              </tr>                          </table>                      </td>                  </tr>                  <tr style='background-color:#74a9d8;'>                      <td align='center' valign='top'>                          <table border='0' cellpadding='20' cellspacing='0' width='100%' id='emailReply'>                              <tr style='font-size: 1.2rem'>                                  <td align='center' valign='top'>                                      <span style='color:#286090; font-weight:bold;'>Send From:</span> <br/> ${email}                                  </td>                              </tr>                          </table>                      </td>                  </tr>              </table>          </td>      </tr>      </table>    </body>  </html> `}

All we are doing here is creating an HTML file and passing in the email and message to create a custom email. We use ES6 string literals to add in string variables with ${ } like so: <h3>${message}</h3>.

And that’s it! You can use whatever front end code you want, simply pass in an email and message to sendAWSEmail(). Just remember sendAWSEmail() returns a promise, so you will have to handle that accordingly.

Both of those values are with regards to SES's antispam mechanisms. They are implemented so that an out going message can be tracked back and reported as spam to the SES servers.

Message-ID is a globally unique identifer that uniquely identifies the message (against every other email ever sent)

Return-path tells the client where reports concerning non-delivery can be sent.

The mix of these two headers means that SES know the reasons that messages are returned and can give you opportunity to deal with them. This is done in order to keep them off blacklists.

The only way that you could remove these headers would be to switch mail senders.

Considering the breadth of businesses that use SES it surprises me that it is blocked as a sender. That would surely mean a lot of missing messages.

Hope that Answers the Question. Thankyou


Related Solutions

Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
I need to send my students I am doing distant classes a test How do I...
I need to send my students I am doing distant classes a test How do I do this and have them answer it without the ability for the to keep it or print it out
How do I convert the integers in my 2D array list to output decimals numbers? My...
How do I convert the integers in my 2D array list to output decimals numbers? My program works accepting regular integers, but crashes when decimals are entered into my 2D array list. Can someone improve it so it accepts decimal numbers? Here is my code: import javax.swing.*; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class TwoDimArray { private int numbers[][]; public TwoDimArray() { loadArray(); } public void loadArray() { /* //loadArray() method loads the users defined filename //@return returns the...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
How do I add the information below to my current code that I have also posted...
How do I add the information below to my current code that I have also posted below. <!DOCTYPE html> <html> <!-- The author of this code is: Ikeem Mays --> <body> <header> <h1> My Grocery Site </h1> </header> <article> This is web content about a grocery store that might be in any town. The store stocks fresh produce, as well as essential grocery items. Below are category lists of products you can find in the grocery store. </article> <div class...
Can you send the excel file if I provide an email address? This is a question...
Can you send the excel file if I provide an email address? This is a question on managerial decision making with excel spreadsheet. A step wise how to solve this will be appreciated for homework and not any exam. A model in excel will really help. John’s Truck John owns John’s Truck Rental, which is currently for sale for $650,000. He would like you to develop a five-year spreadsheet model to assist buyers in their evaluation of the company. The...
JAVA: How do I fix the last "if" statement in my code so that outputs the...
JAVA: How do I fix the last "if" statement in my code so that outputs the SECOND HIGHEST/MAXIMUM GPA out of the given classes? public class app { private static Object minStudent; private static Object maxStudent; public static void main(String args[ ]) { student st1 = new student("Rebecca", "Collins", 22, 3.3); student st2 = new student("Alex", "White", 19, 2.8); student st3 = new student("Jordan", "Anderson", 22, 3.1); student[] studentArray; studentArray = new student[3]; studentArray[0] = st1; studentArray[1] = st2; studentArray[2]...
MTAs are unauthenticated. What effect would requiring user authentication to send email have on the email...
MTAs are unauthenticated. What effect would requiring user authentication to send email have on the email system?
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
I am to write a code that uses two queues, and print the generated random numbers...
I am to write a code that uses two queues, and print the generated random numbers and content of both queues. I need to use the enqueue and dequeue functions in the code.  The instructions are below. Program should be in C Instructions: Generate n random numbers with values between 10 - 100. Note: n>9 if u write a function (for example, called generateRand) to do this - what is the data or input we have to give it? Create a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT