×
Community Blog How to Send Emails Using DirectMail on Alibaba Cloud

How to Send Emails Using DirectMail on Alibaba Cloud

In this article, we will go through the overall architecture and business process of DirectMail email service, and follow up with single mail sending .

By Juan Patrick, Solution Architect Intern

Introduction

Direct Mail is email service from Alibaba Cloud allows you to send emails without setting up your own email server. This article provides the complete guide on how to set up DirectMail and use DirectMail as a mail service for sending emails to your users. There are two types of email services on DirectMail, which are Single Mail and Batch Mail.

In this article, we will go through the overall architecture and business process of DirectMail email service, and follow up with single mail sending for Forget Password use case and batch mail sending for Email Marketing use case.

System Architecture

The following diagram describes the system architecture of the sample application to be setup for the use cases in this article:
5ADEED38_717D_47d8_8ABF_07DB1660E366

In the region of Singapore, we build web application on Alibaba Cloud ECS instance. When the user requests to reset their password, the web server processes the request and generates a forget password link. The web application can interact with DirectMail to generate an email with reset password URL and send it to the user. In DirectMail, we can also track the history of message delivery with email log.

DirectMail Setup

To use DirectMail, you need to firstly register your email domain name with DirectMail. Please follow setup steps from here: https://www.alibabacloud.com/help/en/directmail/latest/simplified-procedure-of-configuring-email-delivery

After the setup of email domain name, you can setup the sender email addresses in DirectMail.

  1. Go back to console DirectMail and choose Sender Addresses, then click Create Sender Address.
  2. Set up your email sender for Batch Emails and Triggered Emails.
  3. Set password for them with SMTP Password, which will be used later when you configure SMTP Server.

Send Triggered Email

Triggered emails are emails to be sent out immediately from your application to customers, for those and transactional communications, such as purchase confirmations or password reset. In this section, we will show the steps of how to send out triggered email using DirectMail.

From SDK
User can send triggered email by using DirectMail SDK. There are several programming languages can use SDK, like Java, Python, Go, PHP, and more else, you can check for explanation on here https://www.alibabacloud.com/help/en/alibaba-cloud-sdk-262060 . We are using NodeJS in this example.

1) Install the SDK Alibaba Cloud package on Node.js ( https://www.npmjs.com/package/@alicloud/pop-core )

npm install @alicloud/pop-core

For other language programming, you can check at: https://www.alibabacloud.com/help/en/alibaba-cloud-sdk-262060

2) Log in to https://usercenter.console.aliyun.com/ and go to AccessKey Management.

3) Copy your AccessKey ID and AccessKey Secret (if you don’t have them, just create a new access by clicking Create AccessKey) and store them in your project. Make sure, keep the access keys safe. This means that we should not make our access keys available to the public. It is important, especially on your root access key, because we can control all operations on cloud resources Alibaba Cloud by API.

If your project is accessible through Git Hosting Services (like GitHub, GitLab, or any other), you can install dotenv (https://www.npmjs.com/package/dotenv ). After that, create .env and store your access keys in your root project. For keys and values, like this:

Key Value
ACCESS_ID <your-access-key-id>
ACCESS_SECRET <your-access-key-secret>

Now, we have secured the access key by storing it locally, and it should not be written directly on the code. We can call these variables as follows:

require("dotenv").config();
const Core = require('@alicloud/pop-core').RPCClient;

const client = new Core({
  accessKeyId: process.env.ACCESS_ID,
  accessKeySecret: process.env.ACCESS_SECRET,
  endpoint: 'https://dm.ap-southeast-1.aliyuncs.com', //Direct Mail region Singapore
  apiVersion: '2015-11-23'
});

//Make Call API: action, param, options
client.request('DescAccountSummary', {}, {
  method: 'POST',
  formatParams: false,
}).then((result) => {
  console.log(JSON.stringify(result));
}, (ex) => {
  console.log(ex);
})

The sample code above is to check your account for usage summary of Alibaba Cloud's DirectMail. We initialize the client, which contains the configuration of Alibaba Cloud Core. There are access key ID, access key secret, endpoint, and API version. To make a request, we write in the RPC (Remote Procedure Call) method and use actions and parameters to pass the API and get the response in JSON format, then print it to the console. Alternatively, you can use the ROA (Resource-oriented architecture) style, but I recommend writing in RPC for the convenience of making requests. In the ROA method, we need to arrange resource URI parameters to create requests, but this is not discussed in this article.

On Alibaba Cloud, we can manage IAM Roles to achieve the principle of least privilege. IAM Role is an account that has been granted access to the resource cloud with more specific permission.

First, open console RAM https://ram.console.aliyun.com/ and choose Identities -> Users. Then, click Create User.
2

Fill the Logon Name, Display Name, and check the Open API Access in Access Mode. Click OK
3

Now, you can see your RAM account, and you can see your AccessKey ID and AccessKey Secret. On the column Action, click Copy.
4

Replace your access key with the access key obtained from the IAM Role on environment .env file project. Go back to console RAM on Users, select your account and click Add Permissions.
5

On Select Policy, type “direct” on the search bar and choose AliyunDirectMailFullAccess and AliyunDirectMailReadOnlyAccess. Leave it to default. Click OK and click Complete
6

Now, you have configured permission of RAM user to access DirectMail only.

For more information about RAM access control, you can check at: https://www.alibabacloud.com/help/en/resource-access-management

From SMTP
User can send triggered email by SMTP. We build the SMTP sender program on Alibaba Cloud ECS instance using NodeJS library nodemailer.
1) Install nodemailer package

npm install nodemailer

2) Open your console DirectMail and go to Email Settings -> Sender Addresses. Choose your sender address and set the password for your code SMTP later.

3) This is an example code to send email via SMTP. Before running the code, fill in the sender address, password used as SMTP password, target email, and try to customize your message email. You can try to store the key email and password in an environment file.

// load nodemailer as follows.
var nodemailer = require('nodemailer');
// create reusable transporter object using SMTP transport.
var transporter = nodemailer.createTransport({
    "host": "smtpdm-ap-southeast-1.aliyun.com", // Singapore
    "port": 25,
    "secureConnection": true, // use SSL
    "auth": {
        "user": ‘<your-sender-address>', // user name
        "pass": '<password>'         // password
    }
});
// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails.
// setup e-mail data with unicode symbols.
var mailOptions = {
    from: '<your-sender-address>', // sender address mailfrom must be same with the user.
    to: '<taget-email>', // list of receivers
    subject: 'Greetings Message', 
    html: '<b>Hello, thank you for trying!</b>', // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
    if(error){
        return console.log(error);
    }
    console.log('Message sent: ' + info.response);
});

For more details, you can check at: https://www.alibabacloud.com/help/en/directmail/latest/smtp-reference

Forget Password Use Case
This is a general flow diagram to describe the email service workflow of forgot password use case. We focus on how to create email services sent to a target address from a server.
7

When a user resets his/her password, the system will check to see if the email address is registered. If yes, the server processes the request to create a link renew password. If not, the server will give an error response in a visual form or it will not be processed by the server depending on business requirements. The link of reset password has an expiration date for the user to apply for a new password. When the user successfully updates the password, the new password will replace the old password and update the data in the database.

1) Create HTML for email template forgot password

const emailBody = `
  <div style="font-family: Arial; color: #000000;">
<div style="width : 400px; height: 300px; background-color: #eceef1; margin: auto; padding: 20px 18px; text-align: center;">
<h1>Password Reset</h1>
<article style="text-align: left; padding-top: 7px;">
<p>Hello,</p>
<p>We've received a request to reset the password, use the link below to get started</p>
</article>
<div style="margin-top: 30px;">
<a href="<link-forgot-password>" role="button" target="_blank"
style="background-color:#38BDF8;
color: #ffffff !important;
border: 0px solid #000000;
border-radius: 3px;
box-sizing: border-box;
font-size: 13px;
font-weight: 700;
line-height: 40px;
padding: 12px 24px;
text-align: center;
text-decoration: none;
vertical-align: middle;">
Reset My Password
</a>
</div>
</div>
</div>
`

And you will get the web page looks like this:
8

2) Create NodeJS code to call SingleSendMail API

require("dotenv").config();
const Core = require('@alicloud/pop-core').RPCClient;
const client = new Core({
…
});
const emailBody = …
client.request('SingleSendMail', {
  AccountName: "<your-triggered-email>",
  AddressType: 1,
  ReplyToAddress: "true",
  ToAddress: "<target-email>",
  Subject: "Password Reset",
  HtmlBody: emailBody
}, { method: 'POST', formatParams: false })

The above code will send the forgot password email to the user's mailbox.

Send Batch Email

Batch email will be used to promote your products and services such as special offers and newsletters, or to send bulk communications, such as announcements and notifications.

You can manage the recipient list to send bulk communications instead of sending every single email one by one with better efficiency. The procedure to setup Batch Mail are described in this diagram:
9

1) Create email tag on the email settings.
10

2) Go to Email Settings -> Email Templates and click on Create Email Template. Fill in all required input. You can try using this body mail sample, if necessary:

Hey {UserName},
Are you going to the Music Festival? So are we!
We're looking forward to seeing your favorite artist live in concert, but if 
you need a little help figuring out what else to do at the festival, here are 
some of our favorites:
-Explore the festival grounds
-Get a drink and watch the sunset at one of our favorite bars in town 
-Visit our booth and get 20% off on one of our products
-Watch a movie at the outdoor theatre. It's all free!
See you there!

If already done, you can confirm the template by Submit to Review

3) Create a recipient list by going to DirectMail -> Send Emails -> Recipient Lists and click on New Recipient List. Fill in the list name, alias address, and description.
11

4) There are several ways to create the recipient list. We can import txt or csv file contains the list customer data, including email, name, mobile, and etc., to create recipient list. Alternatively, we can write code to call DirectMail API SaveReceiverDetail, for example:

require("dotenv").config();
const Core = require('@alicloud/pop-core').RPCClient;const client = new Core({
  …
});
client.request('SaveReceiverDetail', {
  "ReceiverId": "<receiver-id>",
  "Detail": JSON.stringify([{
    "b": "YYYY/MM/DD",
    "e": “<email>”,
    "g": "<gender>",
    "m": "<mobile>",
    "n": "<nickname>",
    "u": “<username>”
  }])
}, { method: 'POST', formatParams: false })

If you don’t know about your Receiver ID, you can try make request action QueryReceiverByParam and search “ReceiverId” on body response.

5) Go to DirectMail -> Send Emails -> Email Tasks and click on Create Email Task. Fill in parameters according to the configuration that has been made.
12

6) You can view the result and status of this batch email task at Send Emails -> Email Tasks and Reporting -> Delivery Log for more details about the email delivery status.
13

Conclusion

There are also many other ways to send out emails using DirectMail, such as API, you check here for more details: https://www.alibabacloud.com/help/en/directmail/latest/api-reference

With the support of DirectMail, Alibaba Cloud users can make use of email service for marketing, notification and authentication. If you want to improve deliverability of your email service with DirectMail, please check https://www.alibabacloud.com/blog/how-to-improve-directmail-deliverability_598437

For other details of DirectMail, please check: https://www.alibabacloud.com/blog/a-comprehensive-guide-to-using-alibaba-cloud-directmail_593946

Explore more about OpenAPI: https://www.alibabacloud.com/help/en/openapi-explorer

0 1 0
Share on

Alibaba Cloud Indonesia

91 posts | 12 followers

You may also like

Comments