Updated on 2024-09-06 GMT+08:00

Publishing a Message

Function

This API is used to publish messages to a topic. After the message ID is returned, the message has been saved and is to be pushed to the subscribers of the topic. Three message formats are supported:

message

message_structure

message_template_name

If the three formats are specified at the same time, they take effect in the following sequence:

message_structure > message_template_name > message

Calling Method

For details, see Calling APIs.

URI

POST /v2/{project_id}/notifications/topics/{topic_urn}/publish

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Specifies the project ID.For details about how to obtain the project ID, see Obtaining the Project ID.

topic_urn

Yes

String

Specifies the resource identifier of the topic, which is unique. To obtain the resource identifier, see Querying Topics.

Request Parameters

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

Specifies a user token.

It can be obtained by calling an IAM API. The value of X-Subject-Token in the response header is the user token.

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

subject

No

String

Specifies the message subject, which is used as the email subject when you publish email messages. The length of the subject cannot exceed 512 bytes.

message

No

String

Specifies the message content. The message content must be UTF-8-coded and can be no more than 256 KB. If the endpoint is a phone number, the SMS message length is limited to 490 characters. If it exceeds the limit, the message may be intercepted by operators. The SMS message cannot contain square brackets ([]).Note:Three message formats are supported:messagemessage_structuremessage_template_nameAt least one of them must be set. If they are set at the same time, the effective priority ismessage_structure > message_template_name > message

message_structure

No

String

Specifies the message structure, which is a JSON string. The following protocols are supported: email, sms, http, https, functiongraph, functionstage, dingding, or wechat, feishu, or welink. The default protocol is mandatory. If the system fails to match any other protocols, the message using the default protocol is sent. The msgType field must be specified for messages of the DingTalk chatbot, WeCom chatbot, Lark chatbot, or WeLink protocol. The DingTalk, WeCom, or Lark chatbot protocol support messages in text or markdown format. WeLink and WeLink (red version) chatbots support messages in text format.For the DingTalk chatbot protocol, SMN supports the @ group member function through the at fields. When you need to @ group members, set isAtAll to ""true"". You can enter the phone numbers of persons who need to be @ for the atMobiles field or enter the DingTalk user IDs of persons who need to be @ for the atUserIds field. When you use the atMobiles or atUserIds field, add @ before each phone number or user ID in the message content. For details about the display effect, see the official DingTalk document.Note:The following three message formats are supported:messagemessage_structuremessage_template_nameSet at least one of them. If you set all of them, they take effect in the following sequence:message_structure > message_template_name > message

message_template_name

No

String

Specifies the message template name. To obtain the name, see Querying Message Templates.Note:Three message formats are supported:messagemessage_structuremessage_template_nameAt least one of them must be set. If they are set at the same time, the effective priority ismessage_structure > message_template_name > message

tags

No

Map<String,String>

Specifies the dictionary consisting of variable parameters and values. The value cannot be left blank. This parameter is mandatory when you use a message template to publish messages. The key in the dictionary is the parameter name in the message template and contains a maximum of 21 characters. The value in the dictionary is the value after the key in the message template is replaced. The value cannot exceed 1 KB.

time_to_live

No

String

Specifies the maximum retention period of a message in SMN. After the retention period expires, SMN does not send this message. Unit: second Default value: 3600s (one hour) The retention period must be a positive integer less than or equal to 86,400 (3600 x 24).

message_attributes

No

Array of MessageAttribute objects

Specifies the message attribute list.

Table 4 MessageAttribute

Parameter

Mandatory

Type

Description

name

Yes

String

Specifies the attribute name. name can contain 1 to 32 characters, including only lowercase letters, digits, and underscores (_). name cannot start or end with an underscore, nor contain consecutive underscores.

type

Yes

String

Specifies the attribute type. The value can be one of the following:

STRING

STRING_ARRAY

PROTOCOL

value

Yes

Object

Specifies the attribute value.

When you set type to STRING, value can contain 1 to 32 characters, including only letters, digits, and underscores (). When you set type to STRING_ARRAY, value is an array containing 1 to 10 strings. Each string in the array must be unique. Each string in the array must contain 1 to 32 characters, including only letters, digits, and underscores ().

When you set type to PROTOCOL, value is a string array of supported protocol types.

Response Parameters

Status code: 200

Table 5 Response body parameters

Parameter

Type

Description

request_id

String

Specifies the request ID, which is unique.

message_id

String

Specifies the message ID, which is unique.

Status code: 400

Table 6 Response body parameters

Parameter

Type

Description

request_id

String

Specifies the request ID, which is unique.

code

String

Specifies the error code.

message

String

Describes the error message.

Status code: 403

Table 7 Response body parameters

Parameter

Type

Description

request_id

String

Specifies the request ID, which is unique.

code

String

Specifies the error code.

message

String

Describes the error message.

Status code: 404

Table 8 Response body parameters

Parameter

Type

Description

request_id

String

Specifies the request ID, which is unique.

code

String

Specifies the error code.

message

String

Describes the error message.

Status code: 429

Table 9 Response body parameters

Parameter

Type

Description

request_id

String

Specifies the request ID, which is unique.

code

String

Specifies the error code.

message

String

Describes the error message.

Status code: 500

Table 10 Response body parameters

Parameter

Type

Description

request_id

String

Specifies the request ID, which is unique.

code

String

Specifies the error code.

message

String

Describes the error message.

Example Requests

  • Publishing a message

    POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics/urn:smn:regionId: f96188c7ccaf4ffba0c9aa149ab2bd57:test_create_topic_v2/publish
    
    {
      "subject" : "test message v2",
      "message" : "Message test message v2",
      "time_to_live" : "3600",
      "message_attributes" : [ {
        "name" : "smn_protocol",
        "type" : "PROTOCOL",
        "value" : [ "email", "sms" ]
      } ]
    }
  • Publishing messages using a message structure

    POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics/urn:smn:regionId: f96188c7ccaf4ffba0c9aa149ab2bd57:test_create_topic_v2/publish
    
    {
      "subject" : "test message v2",
      "message_structure" : "{\n  \"default\": \"xxx\",\n  \"sms\": \"sms message\"\n}",
      "time_to_live" : "3600",
      "message_attributes" : [ {
        "name" : "smn_protocol",
        "type" : "PROTOCOL",
        "value" : [ "email", "sms" ]
      } ]
    }
  • Publishing messages using a template

    POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics/urn:smn:regionId: f96188c7ccaf4ffba0c9aa149ab2bd57:test_create_topic_v2/publish
    
    {
      "subject" : "test message template v2",
      "message_template_name" : "confirm_message",
      "time_to_live" : "3600",
      "tags" : {
        "topic_urn" : "topic_urn3331",
        "topic_id" : "topic_id3332"
      },
      "message_attributes" : [ {
        "name" : "smn_protocol",
        "type" : "PROTOCOL",
        "value" : [ "email", "sms" ]
      } ]
    }

Example Responses

Status code: 200

OK

{
  "request_id" : "6a63a18b8bab40ffb71ebd9cb80d0085",
  "message_id" : "bf94b63a5dfb475994d3ac34664e24f2"
}

SDK Sample Code

The SDK sample code is as follows.

Java

  • Publishing a message

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.smn.v2.region.SmnRegion;
    import com.huaweicloud.sdk.smn.v2.*;
    import com.huaweicloud.sdk.smn.v2.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class PublishMessageSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
            String projectId = "{project_id}";
    
            ICredential auth = new BasicCredentials()
                    .withProjectId(projectId)
                    .withAk(ak)
                    .withSk(sk);
    
            SmnClient client = SmnClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(SmnRegion.valueOf("<YOUR REGION>"))
                    .build();
            PublishMessageRequest request = new PublishMessageRequest();
            request.withTopicUrn("{topic_urn}");
            PublishMessageRequestBody body = new PublishMessageRequestBody();
            List<MessageAttribute> listbodyMessageAttributes = new ArrayList<>();
            listbodyMessageAttributes.add(
                new MessageAttribute()
                    .withName("smn_protocol")
                    .withType(MessageAttribute.TypeEnum.fromValue("PROTOCOL"))
                    .withValue("[email, sms]")
            );
            body.withMessageAttributes(listbodyMessageAttributes);
            body.withTimeToLive("3600");
            body.withMessage("Message test message v2");
            body.withSubject("test message v2");
            request.withBody(body);
            try {
                PublishMessageResponse response = client.publishMessage(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • Publishing messages using a message structure

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.smn.v2.region.SmnRegion;
    import com.huaweicloud.sdk.smn.v2.*;
    import com.huaweicloud.sdk.smn.v2.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class PublishMessageSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
            String projectId = "{project_id}";
    
            ICredential auth = new BasicCredentials()
                    .withProjectId(projectId)
                    .withAk(ak)
                    .withSk(sk);
    
            SmnClient client = SmnClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(SmnRegion.valueOf("<YOUR REGION>"))
                    .build();
            PublishMessageRequest request = new PublishMessageRequest();
            request.withTopicUrn("{topic_urn}");
            PublishMessageRequestBody body = new PublishMessageRequestBody();
            List<MessageAttribute> listbodyMessageAttributes = new ArrayList<>();
            listbodyMessageAttributes.add(
                new MessageAttribute()
                    .withName("smn_protocol")
                    .withType(MessageAttribute.TypeEnum.fromValue("PROTOCOL"))
                    .withValue("[email, sms]")
            );
            body.withMessageAttributes(listbodyMessageAttributes);
            body.withTimeToLive("3600");
            body.withMessageStructure("{
      "default": "xxx",
      "sms": "sms message"
    }");
            body.withSubject("test message v2");
            request.withBody(body);
            try {
                PublishMessageResponse response = client.publishMessage(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • Publishing messages using a template

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.smn.v2.region.SmnRegion;
    import com.huaweicloud.sdk.smn.v2.*;
    import com.huaweicloud.sdk.smn.v2.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    
    public class PublishMessageSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
            String projectId = "{project_id}";
    
            ICredential auth = new BasicCredentials()
                    .withProjectId(projectId)
                    .withAk(ak)
                    .withSk(sk);
    
            SmnClient client = SmnClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(SmnRegion.valueOf("<YOUR REGION>"))
                    .build();
            PublishMessageRequest request = new PublishMessageRequest();
            request.withTopicUrn("{topic_urn}");
            PublishMessageRequestBody body = new PublishMessageRequestBody();
            List<MessageAttribute> listbodyMessageAttributes = new ArrayList<>();
            listbodyMessageAttributes.add(
                new MessageAttribute()
                    .withName("smn_protocol")
                    .withType(MessageAttribute.TypeEnum.fromValue("PROTOCOL"))
                    .withValue("[email, sms]")
            );
            Map<String, String> listbodyTags = new HashMap<>();
            listbodyTags.put("topic_urn", "topic_urn3331");
            listbodyTags.put("topic_id", "topic_id3332");
            body.withMessageAttributes(listbodyMessageAttributes);
            body.withTimeToLive("3600");
            body.withTags(listbodyTags);
            body.withMessageTemplateName("confirm_message");
            body.withSubject("test message template v2");
            request.withBody(body);
            try {
                PublishMessageResponse response = client.publishMessage(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    

Python

  • Publishing a message

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    # coding: utf-8
    
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdksmn.v2.region.smn_region import SmnRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdksmn.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.environ["CLOUD_SDK_AK"]
        sk = os.environ["CLOUD_SDK_SK"]
        projectId = "{project_id}"
    
        credentials = BasicCredentials(ak, sk, projectId)
    
        client = SmnClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(SmnRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = PublishMessageRequest()
            request.topic_urn = "{topic_urn}"
            listMessageAttributesbody = [
                MessageAttribute(
                    name="smn_protocol",
                    type="PROTOCOL",
                    value="[email, sms]"
                )
            ]
            request.body = PublishMessageRequestBody(
                message_attributes=listMessageAttributesbody,
                time_to_live="3600",
                message="Message test message v2",
                subject="test message v2"
            )
            response = client.publish_message(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Publishing messages using a message structure

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    # coding: utf-8
    
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdksmn.v2.region.smn_region import SmnRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdksmn.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.environ["CLOUD_SDK_AK"]
        sk = os.environ["CLOUD_SDK_SK"]
        projectId = "{project_id}"
    
        credentials = BasicCredentials(ak, sk, projectId)
    
        client = SmnClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(SmnRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = PublishMessageRequest()
            request.topic_urn = "{topic_urn}"
            listMessageAttributesbody = [
                MessageAttribute(
                    name="smn_protocol",
                    type="PROTOCOL",
                    value="[email, sms]"
                )
            ]
            request.body = PublishMessageRequestBody(
                message_attributes=listMessageAttributesbody,
                time_to_live="3600",
                message_structure="{
      "default": "xxx",
      "sms": "sms message"
    }",
                subject="test message v2"
            )
            response = client.publish_message(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Publishing messages using a template

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    # coding: utf-8
    
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdksmn.v2.region.smn_region import SmnRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdksmn.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.environ["CLOUD_SDK_AK"]
        sk = os.environ["CLOUD_SDK_SK"]
        projectId = "{project_id}"
    
        credentials = BasicCredentials(ak, sk, projectId)
    
        client = SmnClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(SmnRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = PublishMessageRequest()
            request.topic_urn = "{topic_urn}"
            listMessageAttributesbody = [
                MessageAttribute(
                    name="smn_protocol",
                    type="PROTOCOL",
                    value="[email, sms]"
                )
            ]
            listTagsbody = {
                "topic_urn": "topic_urn3331",
                "topic_id": "topic_id3332"
            }
            request.body = PublishMessageRequestBody(
                message_attributes=listMessageAttributesbody,
                time_to_live="3600",
                tags=listTagsbody,
                message_template_name="confirm_message",
                subject="test message template v2"
            )
            response = client.publish_message(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    

Go

  • Publishing a message

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        smn "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
        projectId := "{project_id}"
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithProjectId(projectId).
            Build()
    
        client := smn.NewSmnClient(
            smn.SmnClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.PublishMessageRequest{}
    	request.TopicUrn = "{topic_urn}"
    	valueMessageAttributes:= "[email, sms]"
    	var valueMessageAttributesInterface interface{} = valueMessageAttributes
    	var listMessageAttributesbody = []model.MessageAttribute{
            {
                Name: "smn_protocol",
                Type: model.GetMessageAttributeTypeEnum().PROTOCOL,
                Value: &valueMessageAttributesInterface,
            },
        }
    	timeToLivePublishMessageRequestBody:= "3600"
    	messagePublishMessageRequestBody:= "Message test message v2"
    	subjectPublishMessageRequestBody:= "test message v2"
    	request.Body = &model.PublishMessageRequestBody{
    		MessageAttributes: &listMessageAttributesbody,
    		TimeToLive: &timeToLivePublishMessageRequestBody,
    		Message: &messagePublishMessageRequestBody,
    		Subject: &subjectPublishMessageRequestBody,
    	}
    	response, err := client.PublishMessage(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • Publishing messages using a message structure

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        smn "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
        projectId := "{project_id}"
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithProjectId(projectId).
            Build()
    
        client := smn.NewSmnClient(
            smn.SmnClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.PublishMessageRequest{}
    	request.TopicUrn = "{topic_urn}"
    	valueMessageAttributes:= "[email, sms]"
    	var valueMessageAttributesInterface interface{} = valueMessageAttributes
    	var listMessageAttributesbody = []model.MessageAttribute{
            {
                Name: "smn_protocol",
                Type: model.GetMessageAttributeTypeEnum().PROTOCOL,
                Value: &valueMessageAttributesInterface,
            },
        }
    	timeToLivePublishMessageRequestBody:= "3600"
    	messageStructurePublishMessageRequestBody:= "{
      "default": "xxx",
      "sms": "sms message"
    }"
    	subjectPublishMessageRequestBody:= "test message v2"
    	request.Body = &model.PublishMessageRequestBody{
    		MessageAttributes: &listMessageAttributesbody,
    		TimeToLive: &timeToLivePublishMessageRequestBody,
    		MessageStructure: &messageStructurePublishMessageRequestBody,
    		Subject: &subjectPublishMessageRequestBody,
    	}
    	response, err := client.PublishMessage(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • Publishing messages using a template

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        smn "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
        projectId := "{project_id}"
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithProjectId(projectId).
            Build()
    
        client := smn.NewSmnClient(
            smn.SmnClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.PublishMessageRequest{}
    	request.TopicUrn = "{topic_urn}"
    	valueMessageAttributes:= "[email, sms]"
    	var valueMessageAttributesInterface interface{} = valueMessageAttributes
    	var listMessageAttributesbody = []model.MessageAttribute{
            {
                Name: "smn_protocol",
                Type: model.GetMessageAttributeTypeEnum().PROTOCOL,
                Value: &valueMessageAttributesInterface,
            },
        }
    	var listTagsbody = map[string]string{
            "topic_urn": "topic_urn3331",
            "topic_id": "topic_id3332",
        }
    	timeToLivePublishMessageRequestBody:= "3600"
    	messageTemplateNamePublishMessageRequestBody:= "confirm_message"
    	subjectPublishMessageRequestBody:= "test message template v2"
    	request.Body = &model.PublishMessageRequestBody{
    		MessageAttributes: &listMessageAttributesbody,
    		TimeToLive: &timeToLivePublishMessageRequestBody,
    		Tags: listTagsbody,
    		MessageTemplateName: &messageTemplateNamePublishMessageRequestBody,
    		Subject: &subjectPublishMessageRequestBody,
    	}
    	response, err := client.PublishMessage(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    

More

For SDK sample code of more programming languages, see the Sample Code tab in API Explorer. SDK sample code can be automatically generated.

Status Codes

Status Code

Description

200

OK

400

Bad Request

403

Unauthorized

404

Not Found

429

Too Many Requests

500

Internal Server Error

Error Codes

See Error Codes.