简体   繁体   中英

AWS SNS how to add line breaks in message

I'm trying to send SNS messages via CLI in json format.

aws sns publish --cli-input-json "{\"TopicArn\":\"xxx\",\"Message\":\"first line\n second line\",\"Subject\":\"Empty subject\"}"

But the \n doesn't work. Neither is "\r\n" or "\n". I think the string is escaped by SNS so \n doesn't work. Does anyone know how to send a message of 2 lines?(Sending 2 messages is not an option) Appreciate your advice!

I think \\\\n is actually what you are looking for. I've just tested it by sending push notifications to my device through AWS SNS.

So your message should look like this:

aws sns publish --cli-input-json "{\"TopicArn\":\"xxx\",\"Message\":\"first line\\nsecond line\",\"Subject\":\"Empty subject\"}"

Note, you should not leave the white space after the line break symbol, otherwise, your new line would start with that space.

aws sns publish --topic-arn "arn:aws:sns:us-west-2:0123456789012:my-topic" --message file://message.txt

message.txt is a text file containing the message to publish:

Hello World Second Line

Putting the message in a text file allows you to include line breaks .

这对我有用:

"first line
second line"

four backslash works for me

using Aws SNS with Firebase

EX: backslashbackslashbackslashbackslash+n

I am publishing messages using the email protocol using the NodeJs aws-sdk . In order for exceptions to appear correctly, I needed to replace both \n and \\n , and to appease both windows and mac clients, used \r\n .

message.replace(/\n|\\n/g, '\r\n')

For anyone who needs full code, this is how I am handling errors in typescript

public prepareMessage(header: string, error: any) {
    const data = (error instanceof Error)
        ? JSON.stringify(error, Object.getOwnPropertyNames(error), 2)
        : JSON.stringify(error, null, 2);

    const replaceNewlines = (str: string) => str?.replace(/\n|\\n/g, '\r\n') || '';

    return `${replaceNewlines(header)}\r\n${replaceNewlines(data)}`;
}

After testing all suggested answers, here's what worked in my case (running from a python lambda function, publishing from boto3 sns client):

This created 2 new lines: message.replace('\n', '\r\n')

This created 1 new line: message.replace('\n', '\r')

Example:

message = message.replace('\n', '\r').replace('\t', '    ')

# Sending the notification...
snsclient.publish(
    TargetArn=SNS_EMAIL_ALERTS_ARN,
    Subject=f'{filter_name} Alert: ({lambda_func_name[3]})',
    Message=message
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM