All Products
Search
Document Center

Direct Mail:Sample Signature Request (Java)

Last Updated:Sep 30, 2024

Example

package com.aliyun.test;

import codec.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

public class SampleAPI {
    /**
     * https://dm.aliyuncs.com/?Action=SingleSendMail
     * &AccountName=test***@example.net
     * &ReplyToAddress=true
     * &AddressType=1
     * &ToAddress=test1***@example.net
     * &Subject=Subject
     * &HtmlBody=body
     * &<Public request parameters>
     */
    @Test
    public void testSingleSendMail() {
        Map<String, Object> params = new TreeMap<String, Object>();
        params.put("AccessKeyId", AccessKeyId);
        params.put("Action", "SingleSendMail");
        params.put("Format", Format);
        params.put("RegionId", RegionId);
        params.put("SignatureMethod", SignatureMethod);
        params.put("SignatureNonce", UUID.randomUUID().toString());
        params.put("SignatureVersion", SignatureVersion);
        params.put("Timestamp", getUTCTimeStr());
        params.put("Version", Version);
        params.put("AccountName", AccountName);
        params.put("AddressType", AddressType);
        params.put("HtmlBody", HtmlBody);
        params.put("ReplyToAddress", ReplyToAddress);
        params.put("Subject", Subject);
        params.put("TagName", TagName);
        params.put("ToAddress", ToAddress);

        Long start = System.currentTimeMillis();
        httpRequestSendEmail(params);
        System.out.println("Processing time: " + (System.currentTimeMillis() - start));
    }

    public String httpRequestSendEmail(Map<String, Object> params) {
        String result = null;
        try {
            params.put("Signature", getSignature(prepareParamStrURLEncoder(params), method));
            String param = prepareParamStrURLEncoder(params);
            String url = protocol + "://" + host + "/?" + param;
            System.out.println("-----url-----" + url);

            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse response = null;
            if (method.equals(HttpMethod.GET)) {
                HttpGet request = new HttpGet(url);
                response = httpClient.execute(request);
            } else {
                HttpPost request = new HttpPost(url);
                response = httpClient.execute(request);
            }
            System.out.println(response);
            if (null != response){
                result = EntityUtils.toString(response.getEntity());
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("-----httpRequestSendEmail result-----" + result);
        return result;
    }

    private final static String protocol = "https";
    private final static String host = "dm.aliyuncs.com";
    private final static String AccessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private final static String AccessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    //The sender address.
    private final static String AccountName = "test***@example.net";
    //The recipient address.
    private final static String ToAddress = "test1***@example.net";
    private final static String Format = "JSON";
    private final static String SignatureMethod = "HMAC-SHA1";
    private final static String SignatureVersion = "1.0";
    private final static String Version = "2015-11-23";
    private final static String AddressType = "1";
    private final static String RegionId = "cn-hangzhou";
    private final static Boolean ReplyToAddress = Boolean.TRUE;
    private final static String HtmlBody = "<html><body><h3>Test send to email! </h3></body></html>";
    private final static String Subject = "Test topic";
    private final static String TagName = "Test tag";
    private final static HttpMethod method = HttpMethod.POST;

    public String prepareParamStrURLEncoder(Map<String, Object> params) {
        try {
            StringBuffer param = new StringBuffer();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (StringUtils.isBlank(entry.getKey()) || null == entry.getValue()) {
                    continue;
                }
                param.append(getUtf8Encoder(entry.getKey()) + "=" + getUtf8Encoder(entry.getValue().toString()) + "&");

            }
            return param.substring(0, param.lastIndexOf("&"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Obtain a signature.
     *
     * @param param
     * @param method
     * @return
     * @throws Exception
     */
    private String getSignature(String param, HttpMethod method) throws Exception {
        String toSign = method + "&" + URLEncoder.encode("/", "utf8") + "&"
                + getUtf8Encoder(param);
        byte[] bytes = HmacSHA1Encrypt(toSign, AccessKeySecret + "&");
        return Base64.encode(bytes);
    }

    private String getUtf8Encoder(String param) throws UnsupportedEncodingException {
        return URLEncoder.encode(param, "utf8")
                .replaceAll("\\+", "%20")
                .replaceAll("\\*", "%2A")
                .replaceAll("%7E", "~");
    }

    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";

    /**
     * Use the HMAC-SHA1 algorithm to sign encryptText.
     *
     * @param encryptText: the string to sign.
     * @param encryptKey: the key.
     * @return
     * @throws Exception
     */
    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        //Construct a key based on the given byte array and specify the name of an algorithm for the second parameter.
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // Generate a Mac object with a specified Mac algorithm.
        Mac mac = Mac.getInstance(MAC_NAME);
        //Initialize the Mac object by using the given key.
        mac.init(secretKey);

        byte[] text = encryptText.getBytes(ENCODING);
        //Complete Mac operations.
        return mac.doFinal(text);
    }

    private static DateFormat daetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * The UTC time of the string type is returned. The format is "yyyy-MM-dd HH:mm"<br />.
     * If the request fails, null is returned.
     *
     * @return
     */
    public static String getUTCTimeStr() {
        //1. Obtain the local time.
        Calendar cal = Calendar.getInstance();
        // 2. Retrieve the time offset.
        int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
        // 3. Retrieve the Daylight Saving Time (DST) offset.
        int dstOffset = cal.get(Calendar.DST_OFFSET);
        // 4. Deduct the offsets from the local time to obtain the UTC time.
        cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
        String date = daetFormat.format(cal.getTime());
        System.out.println("time------" + date);
        String[] strs = date.split(" ");
        return strs[0] + "T" + strs[1] + "Z";
    }

}

Reminder

Hangzhou:
host = "dm.aliyuncs.com";
AccountName = "Specify a sender address in the China (Hangzhou) region";
Version = "2015-11-23";
RegionId = "cn-hangzhou";

Singapore (Singapore):
host = "dm.ap-southeast-1.aliyuncs.com";
AccountName = "Specify a sender address in the Singapore (Singapore) region";
Version = "2017-06-22";
RegionId = "ap-southeast-1";

Australia (Sydney):
host = "dm.ap-southeast-2.aliyuncs.com";
AccountName =" Specify a sender address in the Australia (Sydney) region";
Version = "2017-06-22";
RegionId = "ap-southeast-2";

--- Example of the last url request sent by the Hangzhou service area ---

https://dm.aliyuncs.com/?AccessKeyId=xxxxxxx&AccountName=noreply%40xxxxxxxx.club&Action=SingleSendMail&AddressType=1&Format=JSON&HtmlBody=%3Chtml%3E%3Cbody%3E%3Cimg%20alt%3D%22Go%E8%AF%AD%E8%A8%80%E4%B8%AD%E6%96%87%E7%BD%91%22%20src%3D%22https%3A%2F%2Fstatic.studygolang.com%2Fimg%2Flogo1.png%22%20%3E%3Cimg%20alt%3D%22%22%20src%3D%22https%3A%2F%2Fgoss4.vcg.com%2Fcreative%2Fvcg%2F400%2Fnew%2FVCG211173951082.jpg%22%20%3E%3Ch3%3ETest%20send%20to%20email%20%EF%BC%88%EF%BC%89%EF%BC%81%3C%2Fh3%3E%3C%2Fbody%3E%3C%2Fhtml%3E%20%3Ca%25b%27%20%2B%20%2A%20%257E%3E%20%E6%B5%8B%E8%AF%95%E9%82%AE%E4%BB%B6%E6%AD%A3%E6%96%87%E3%80%82%E4%BD%A0%E6%AD%A4%E6%AC%A1%E7%94%B3%E8%AF%B7%E6%B3%A8%E5%86%8C%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E4%B8%BA%EF%BC%9A123456&RegionId=cn-hangzhou&ReplyToAddress=true&Signature=1PysI0HsZeOEHqQ%3D&SignatureMethod=HMAC-SHA1&SignatureNonce=37161234-7747-419f-b433-bc4719504b01&SignatureVersion=1.0&Subject=%E6%B5%8B%E8%AF%95%E4%B8%BB%E9%A2%98&TagName=%E6%B5%8B%E8%AF%95Tag&Timestamp=2018-11-07T09%3A40%3A13Z&ToAddress=xxxxx%40xxx.com&Version=2015-11-23