
Amazon SES is a simple email service used to send and receive emails from your verified domain using any application. AWS SNS is a Simple Notification Service used to notify/publish messages from an application to the subscribed endpoint user/server & customers. In my previous article(read here), I had discussed how to send email using AWS SES, in this article we are going to learn how to receive email using AWS SES & AWS SNS.
Step 1. AWS Setup
- Create an AWS account here https://portal.aws.amazon.com/billing/signup#/start
- Now go to IAM(Identity and Access Management — IAM user creation is required for giving access to your application to perform the action.)
a. Add new User
b. Select AWS access type as“Programmatic access”
c. Set permissions -> Attach existing policy -> i. AmazonSESFullAccess ii. AmazonSNSFullAccess
d. select the permission Boundry
e. give the tag
f. Review & create a user.
g. download the access key & Id for future use. - Go to SES ->Domains -> Verify New domain. This step is necessary to allow SES to process the incoming email.
Step 2. Node.js Setup
1. Install AWS-SDK & mail parser using npm or bower:
npm i aws-sdk
bower install aws-sdk-js
npm i mailparser
2. Store AWS access key & secret access to config.js file:
{
"accessKeyId":"AWS_ACCESS_KEY_ID",
"secretAccessKey":"AWS_SECRET_ACCESS_KEY",
"region":"AWS_DEFAULT_REGION"
}
3. Let’s create an SNS-helper.js to notify about incoming email
a. Import AWS module:
const AWS = require('aws-sdk')
const config = require('../config.json')
b. Initialize SNS instance with access info:
const snsConfig = {
apiVersion: '2010-03-31',
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.region,
}
const SMS = new AWS.SNS(snsConfig)
c. create a topic & subscription endpoint to notify about incoming email
module.exports.createTopic = async() => {
const topic = await sns.createTopic({
Name: 'receive-email-poc',
Attributes: {
FifoTopic: true,
DisplayName: 'Receive-email'
}
}).promise()
const params = {
Protocol: 'HTTPS',
TopicArn: topic.TopicArn,
Attributes: {
RawMessageDelivery: false,
},
Endpoint: 'https://app.example.com/emails/receive-email',
};
const subscription = await sns.subscribe(params).promise();
}
Creation of topic is required to notify our server/your email about incoming emails.
- Create the topic with a name & attribute. Topics in AWS are communication channel which allows us to group multiple endpoints where SNS will notify the specific event action.
- Create a subscription to register the server endpoint where we want notification. Topic ARN is a unique id of the topic.
- Confirm the subscription & AWS will send a notification to the endpoint.
4. Let’s create a ses-helper.js to set up rules of incoming email
a. Import AWS module:
const AWS = require('aws-sdk')
const config = require('../config.json')
b. Initialize SES instance with access info:
const sesConfig = {
apiVersion: '2010-12-01',
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.region,
}
const ses = new AWS.SES(sesConfig)
c. Create Rule Set & rules to setup incoming emails
module.exports.createRules = async () => {
const ruleSet = await ses.createReceiptRuleSet({
RuleSetName: 'ReceiveEmails-POC'
}).promise()
const params = {
After: "",
Rule: {
Name: "S3Rule",
Enabled: true,
TlsPolicy: "Optional",
Actions: [{
S3Action: {
BucketName: "EmailBucket",
ObjectKeyPrefix: "email",
KmsKeyArn: "arn:aws:kms:.....",
TopicArn: "arn:aws:sns:......"
}
}],
Recipients: [
"@example.com",
"@email.example.com",
],
ScanEnabled: true,
},
RuleSetName: "ReceiveEmails-POC"
};
const rules = await ses.createReceiptRule(params).promise()
}
You need to set certain rules to accept the incoming emails like first create ruleset which is a group of rules to be applied when SES receives an email. Then create individual rules to the set like
i. Rule object contains:
- a. Name specifies the name of the rule.
- b.Enabled specifies whether this rule is activated or not.
- c.TlsPolicy specifies whether SES should require that incoming email is delivered over a connection encrypted with Transport Layer Security (TLS). If this parameter is set to “Require”, Amazon SES will bounce emails that are not received over TLS. The default is “Optional”.
- d. Recipients specifies an array of domains or email address that the receipt rule applies to. If this field is not specified, this rule will match all recipients under all verified domains.
- e. ScanEnabled specifies boolean value, if set to true it will scan the email for spam and virus.
- f. Actions contain an array of actions to be applied when this rule is activated like perform s3action which means storing the incoming email into the S3 bucket. If the topic ARN is specified it will notify the subscriber of the SNS topic. KmsKeyArn specifies the customer master key that Amazon SES should use to encrypt incoming emails before saving them to the S3 bucket. There are other actions available to be performed for setting rules like directly send the mails to SNS subscribers using SNSAction. You can read more action here.
ii. RuleSetName specifies this rule belongs to which Rule Set.
iii. After specifies the name of an existing rule after which the new rule will be placed. If this parameter is not specified, the new rule will be inserted at the beginning of the rule list.
You need to create these rules for the first time. After this rule is processed you can reply to a specified domain and you will receive it in your S3 bucket.
5. create an email-receiver.js file in your node project to process incoming emails.
const { simpleParser } = require('mailparser')
const AWS = require('aws-sdk')
const S3 = new AWS.S3({
apiVersion: '2006-03-01',
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.region
})
router.post('/emails/receive-email', async(req, res) => {
try {
const message = JSON.parse(req.rawBody)
const s3Data = await S3.getObject({
Bucket: 'EmailBucket',
Key: message.mail.messageId
}).promise()
const parsed = await simpleParser(s3Data.Body)
let emailResponse = parsed.text
console.log(emailResponse)
res.status(200)
}
catch (err) {
console.log(err)
res.status(501)
}
})
Once you receive the incoming email you need to parse it to read. We are using a mail parser to read the incoming email. Each incoming email contains a messageId that is unique to store the message. We can access the email from the S3 bucket using messageId. Once you parse the email, it will give you data like HTML format of the message, text format of the message, CC, BCC, subject, reply to, and much more.
That’s it. You can set up incoming emails to reroute to your specified email address.
Thank you for reading.
Leonard rNVlFSgLIcFTvdjmnK 6 18 2022 cialis generic name
To the noob2geek.in admin, Your posts are always well thought out.
Hello noob2geek.in owner, Thanks for the post!
Dear noob2geek.in owner, Thanks for the informative post!
Cool. I spent a long time looking for relevant content and found that your article gave me new ideas, which is very helpful for my research. I think my thesis can be completed more smoothly. Thank you.
Hello noob2geek.in webmaster, You always provide helpful information.
Dear noob2geek.in owner, You always provide valuable information.
Hi, і think tһat i saw you visited my web site so
i came to “return the favor”.I am tryіng to find things to enhance my website!I suppose
its ok tߋ use а few of your ideas!!
Dear noob2geek.in administrator, Keep it up!
Hi noob2geek.in admin, Your posts are always well-balanced and objective.
Dear noob2geek.in owner, Your posts are always a great read.
Hello noob2geek.in admin, Your posts are always well-referenced and credible.
Hi noob2geek.in administrator, Good job!
Dear noob2geek.in owner, Thanks for the great post!
Hi noob2geek.in admin, You always provide great examples and real-world applications.
Hi noob2geek.in administrator, Nice post!
Xm36n5Fa4rWaqsiH0fAgNBpENaqEZ2Q0GzXnwlvcqyg81SgrpoHbOJfvX5CRP7V1jumP6RHBUgH7aD0yUvooGjel4BRKnQIDIQjN5B9hDEiTdZlrnWmSfIf9mLzaxjE9dXuc5aXB8RqFfLEINPF29otSDKo2BTH4tPwoqHHXg
Dear noob2geek.in admin, Good to see your posts!
Hi noob2geek.in owner, Your posts are always interesting.
Hello noob2geek.in admin, Your posts are always well-timed and relevant.
Dear noob2geek.in webmaster, Thanks for the comprehensive post!
To the noob2geek.in admin, Keep up the great work!
LTt0arkYn8jhVYKHpVJkqgiyyqBmcoKoCEE4kLoX1AFVZI5O7sdwCzC4YEartJc149EbvJfLo4UG23ym1MneRqeaU8G7fN5frXfAFkw852losSoqw1JywbNtBHkj2Pvy0vAi9cuyOieyYsr82YwCSiaR1oxPsQ2j0558HRuC
To the noob2geek.in admin, Thanks for sharing your thoughts!
Hi noob2geek.in webmaster, Excellent work!
mMh96ahX5Va7BrKItn15RexIthG3gWG8LkBZsvE8w2KcgNOqguiuCdekasdngE6KBLwV5JIY7wjn99yJlD2YQ94yEV0Z2IhhUGJ5b27FrPdhcn77XZaw2YExqUtgOmVXs7txwW7GK
Pingback: AWS SES, SNS, CloudWatch Integration with Node.js | Noob2Geek