メニュー

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Twilio SMS Python クイックスタート

With just a few lines of code, your Python application can send SMS messages with Twilio Programmable Messaging.

This Programmable Messaging Quickstart will walk you through the entire process step-by-step, starting with setting up your Twilio account all the way through sending an SMS using a Messaging Service.

このクイックスタートでは、下記のことを学んでいきます:

  • Twilioにサインアップして、SMS機能を持ったはじめてのTwilio電話番号を入手する
  • Set up your development environment to send outbound messages
  • Send your first outbound SMS
  • Set up your first Twilio Messaging Service
  • Send a second SMS from that Messaging Service

By the end of this Quickstart, you’ll have a solid foundation for building and scaling with Twilio’s Programmable Messaging for your specific use cases.

Show me how it's done!

Already have a Twilio account? Go ahead and skip this section.

You can sign up for a free Twilio trial account here.

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
  • Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID an authentication token, find a Twilio phone number, and more.
I've got an account! What's next?

Install the Twilio CLI

We'll use the Twilio CLI (command line interface) for a few tasks, so let's install that next.

One of the easiest ways to install the CLI on Mac OS X is to use Homebrew. If you don't already have it installed, visit the Homebrew site for installation instructions and then return here.

Once Homebrew is installed, simply run the following command to install the CLI:

brew tap twilio/brew && brew install twilio

Updating

If you already installed the CLI with brew and want to upgrade to the latest version, run:

brew upgrade twilio

Warning for Node.js developers

If you have installed Node.js version 10.12 or higher on your Mac, you can avoid potential Node.js version conflicts by installing the CLI using npm:

npm install twilio-cli -g

Before we can install, we need to make sure you have Node.js installed (version 10.12 or above). To see if you have node installed, try running this command:

node -v

If your system reports v10.12.0 or above, you can skip the next step.

Installing Node.js on Windows

Using the Windows Installer (.msi) is the recommended way to install Node.js on Windows. You can download the installer from the Node.js download page.

Installing Twilio CLI

The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:

npm install twilio-cli -g

Note the -g option is what installs the command globally so you can run it from anywhere in your system.

Updating

If you already installed the CLI with npm and want to upgrade to the latest version, run:

npm install twilio-cli@latest -g

Before we can install, we need to make sure you have Node.js installed (version 10.12 or above). Even if you already installed Node yourself, the CLI works best when you install it using nvm. Here's how to get nvm installed on most Linux systems:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

Please visit the nvm installation instructions for additional options and troubleshooting steps. Once you have nvm installed, run the following to install and use the most recent LTS release of Node.js:

nvm install --lts
nvm use <insert version reported from above>

Installing other Twilio CLI prerequisites for Linux

Depending on your distribution, you will need to run one of the following commands:

  • Debian/Ubuntu: sudo apt-get install libsecret-1-dev
  • Red Hat-based: sudo yum install libsecret-devel
  • Arch Linux: sudo pacman -S libsecret

Installing Twilio CLI

The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:

npm install twilio-cli -g

Note the -g option is what installs the command globally so you can run it from anywhere in your system.

Updating

If you already installed the CLI with npm and want to upgrade to the latest version, run:

npm install twilio-cli@latest -g

Run twilio login to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to provide to the CLI.

認証トークンは、目玉アイコンをクリックすると表示されます:

認証トークンを表示する

Now to get a phone number...

Get a phone number

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. With the CLI, run:

twilio phone-numbers:buy:local --country-code US --sms-enabled

Replace US with your ISO-3166-1 country code if you would like a phone number in another country. If you aren't finding any SMS enabled numbers, try looking for a mobile number instead of a local number: twilio phone-numbers:buy:mobile --country-code DE --sms-enabled

Select a phone number to add it to your account.

Next, we need to install Python and the Twilio Python Helper Library.

バッチリです! セットアップ方法を教えてください。

すでに他のPythonクイックスタートを終えていて、PythonおよびTwilio Pythonヘルパーライブラリーがインストールされている場合は、このステップを読み飛ばしてすぐに最初のテキストメッセージを送信できます。

To send your first SMS, you’ll need to have Python and the Twilio Python helper library installed.

Pythonをインストールする

あなたがMacやLinuxマシン上にある場合、あなたはおそらくすでにPythonがインストールされています。 ターミナルを開いて下記のコマンドを入力することでこれを確認できます:

python --version

下記のように表示されます:

$ python --version
Python 3.4

Windows users can follow this excellent tutorial for installing Python on Windows, or follow the instructions from Python's documentation.

Twilio’s Python server-side SDK supports both Python 2 and Python 3. You can use either version for this quickstart, but we recommend using Python 3 for future projects with Twilio unless there are specific libraries your project needs which are only compatible with Python 2.

Install the Twilio Python Server-side SDK

The easiest way to install the library is using pip, a package manager for Python that makes it easier to install the libraries you need. Simply run this in the terminal:

pip install twilio

If you get a pip: command not found error, you can also use easy_install by running this in your terminal:

easy_install twilio

If you'd prefer a manual installation, you can download the source code (ZIP) for twilio-python and then install the library by running:

python setup.py install

in the folder containing the twilio-python server-side SDK library code.

All set! Let's send a text message.

PythonでSMSを送信する

これでNode.jsとTwilio Pythonライブラリーがインストールできたので、今しがた購入したTwilio電話番号から、1回のAPIリクエストでSMSを送信できます。 send_sms.pyという名前のファイルを作成して開き、下記のコードサンプルを入力またはペースとします。

        
        
        
        
        This code creates a new instance of the Message resource and sends an HTTP POST to the Message resource URI.

        Twilioを使用してSMSを送信する

        This code creates a new instance of the Message resource and sends an HTTP POST to the Message resource URI.

        You’ll need to edit your send_sms.py file a little more before your message will send:

        プレースホルダーのクレデンシャル値を置き換える

        Swap the placeholder values for account_sid and auth_token with your personal Twilio credentials. Go to https://www.twilio.com/console and log in. On this page, you’ll find your unique Account SID and Auth Token, which you’ll need any time you send messages through the Twilio Client like this. You can reveal your auth token by clicking on the 'view' link:

        Reveal your Auth Token in the Twilio Console

        send_sms.pyを開き、account_sidおよびauth_tokenに対応する値をご使用のアカウントの一意な値に置き換えます。

        ご注意ください: 初めのうちは認証情報をハードコーディングしても構いませんが、本番環境にデプロイするにあたっては、環境変数を使用してこれらが漏洩しないようにしてください。 追加情報については、環境変数の設定方法を参照してください。

        from 電話番号を置き換える

        Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from_ number with that one, making sure to use E.164 formatting:

        [+][country code][phone number including area code]

        to 電話番号を置き換える

        Replace the to phone number with your mobile phone number. This can be any phone number that can receive text messages, but it’s a good idea to test with your own phone so you can see the magic happen! As above, you should use E.164 formatting for this value.

        トライアルアカウントをご使用の場合、Twilioで検証済みの電話番号に送信先が制限されます。電話番号はTwilioコンソール内の検証済み発信者番号にて検証できます。 

        When you send an SMS from your free trial phone number, it will always begin with "Sent from a Twilio trial account." We remove this message after you upgrade.

        変更を保存し、ターミナルからこのスクリプトを実行します:

        python send_sms.py
        

        一丁上がり! ほどなくして、Twilio電話番号から携帯電話にSMSが受信されるはずです。

        米国かカナダに顧客がいますか? もう1行コードを追加すれば、そのお客様にMMSも送信可能です。 方法を確認するには、MMS送信のガイドを参照してください。

        In this code sample, we are making a POST request to the Programmable Messaging API’s Message endpoint in order to create a new outbound message. We are using the twilio-python library’s built-in create method, but you could make this request using the Twilio CLI (that you already installed), curl, or a request module of your choosing.

        Check out the code samples to send an SMS with the Twilio CLI and curl. Don't forget to update the body, to, and from parameters!

              
              
              
              
              This code sample makes a request to the Message resource using the Twilio CLI

              Use the Twilio CLI to send an SMS

              This code sample makes a request to the Message resource using the Twilio CLI
                    
                    
                    
                    
                    This code sample makes a request to the Message resource using curl

                    Use curl to send an SMS

                    This code sample makes a request to the Message resource using curl
                    I got the message. What's next?

                    Set up a Twilio Messaging Service

                    Congratulations, you’ve sent your first SMS with Twilio Programmable Messaging and received it on your personal device.

                    At this point, we have acquired one Twilio phone number and used it to send one outbound SMS. You can imagine a time in the not-so-distant future where you'll need a more robust, feature-rich way to send messages, such as:

                    • sending many messages over a short period of time
                    • handling opt-ins and opt-outs
                    • ensuring that your customers always receive a consistent messaging experience with the same phone number.

                    In the next part of the Quickstart, we’ll walk through setting up your first Messaging Service. You can think of a Messaging Service as a container to hold all of your available phone numbers (and other senders) and comes with features that you may need along your messaging journey.

                    Create a Messaging Service with your phone number

                    Run the following Twilio CLI command to create a Messaging Service that we will use to send our first programmable SMS.

                    twilio api:messaging:v1:services:create --friendly-name "My first Messaging Service"
                    

                    Take note of the Messaging Service SID (It starts with “MGXXX...”). We'll need it to send our next message.

                    Next, add the phone number you just purchased. Forgot the number already? No worries, you can list it with the Twilio CLI:

                    twilio phone-numbers:list
                    # Grab the SID ("PNXXXX...") of your number
                    

                    Add your phone number to your newly created Messaging Service with the following command:

                    twilio api:messaging:v1:services:phone-numbers:create --service-sid MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --phone-number-sid PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                    
                    Okay, I'm ready to send from my service.

                    Send an SMS from your Messaging Service

                    Sending an outbound SMS from a Messaging Service is similar to sending from an individual Twilio phone number. The primary difference is replacing the from_ parameter with the messaging_service_sid to indicate that you are sending from a phone number within your Messaging Service’s sender pool. (Currently, there is only one phone number in your sender pool, so we'll be sending from that one.)

                          
                          
                          
                          
                          This code creates a new instance of the Message resource, this time with a messaging_service_sid parameter

                          Send an SMS using a Messaging Service

                          This code creates a new instance of the Message resource, this time with a messaging_service_sid parameter

                          Replace the messaging_service_sid parameter

                          Remember that Messaging Service you just created? Instead of the from_ parameter and your phone number, use the messaging_service_sid parameter with the "MGXXXX..." of your Messaging Service SID. Save your changes and run this script from your terminal:

                          python send_sms.py
                          

                          And that’s in to send an SMS using a Twilio Messaging Service! In a few seconds, you should receive a second SMS on your phone from your Twilio phone number. The Messaging Service seamlessly selected your number from its Sender Pool to send that second outbound message.

                          It worked! All done - what's next?

                          関連トピック

                          Now that you've send your first SMS messages, check out the following resources to continue your messaging journey with Twilio:

                          皆さまが何を開発されるのか、目にするのが待ちきれません!

                          Rate this page:

                          ヘルプが必要ですか?

                          誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。