Twilio error 21211 "Invalid 'To' Phone Number" in CI
Twilio returns error 21211 "The 'To' number ... is not a valid phone number" when the recipient is not valid E.164 (a leading + and country code, digits only). In CI the number often arrives empty or with spaces, dashes, or a missing country code.
What this error means
A Twilio Messages request fails with HTTP 400 and {"code":21211,"message":"The 'To' number is not a valid phone number."}. No SMS is sent.
< HTTP/1.1 400 Bad Request
{"code": 21211, "message": "The 'To' number 5558675310 is not a valid phone number.", "status": 400}Common causes
The number is not E.164
A To like 5558675310 or (555) 867-5310 lacks the + and country code Twilio requires.
The recipient value was empty
An unset secret or variable produces an empty To, which is invalid.
How to fix it
Send E.164 formatted numbers
- Store recipients as full E.164 strings, including the
+and country code. - Strip spaces and dashes before sending.
- Reject an empty value before the API call.
TO="+15558675310"
[ -n "$TO" ] || { echo "no recipient"; exit 1; }
curl -sS -X POST ".../Messages.json" \
--user "$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN" \
--data-urlencode "To=$TO" --data-urlencode "From=$TWILIO_FROM" \
--data-urlencode "Body=CI alert"Store recipients as variables
Keep the E.164 number in a workflow variable so formatting is consistent.
env:
ALERT_TO: ${{ vars.ALERT_TO }} # +15558675310How to prevent it
- Store all phone numbers in E.164 format.
- Validate the recipient is non-empty before calling the API.
- Normalize away spaces and punctuation in the notify script.