本文介绍使用Python SDK发布主题消息的示例代码,当需要将消息推送到邮箱或者以短信的方式推送到指定的手机,需要在发布消息设置额外的属性,具体设置方式参考代码。

#you can get $accountid from https://account.console.aliyun.com/#/secure
#you can get $accid and $acckey from https://ak-console.aliyun.com/#/accesskey
#you can generate $endpoint: http://$accountid.mns.cn-hangzhou.aliyuncs.com, eg. http://1234567890123456.mns.cn-hangzhou.aliyuncs.com
my_account = Account("$endpoint", "$accid", "$acckey")
topic_name = "TestTopic"
my_topic = my_account.get_topic(topic_name)

#attributes for Mail
direct_mail = DirectMailInfo(account_name="direct_mail_account_name@aliyun-inc.com", subject="TestMailSubject", address_type=0, is_html=0, reply_to_address=0)

#attributes for SMS
direct_sms = DirectSMSInfo(free_sign_name="SignName", template_code="TemplateCode", single=False)
direct_sms.add_receiver(receiver="$phone1", params={"name": "Tom"})
direct_sms.add_receiver(receiver="$phone2", params={"name": "David"})

#init TopicMessage
msg_body = "I am test message."
msg = TopicMessage(msg_body, "msg_tag", direct_mail, direct_sms)
try:
    re_msg = my_topic.publish_message(msg)
    print "Publish Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id)
except MNSExceptionBase,e:
    if e.type == "TopicNotExist":
        print "Topic not exist, please create it."
        sys.exit(1)
    print "Publish Message Fail. Exception:%s" % e