"smtplib" --- SMTP プロトコルクライアント
*****************************************

**ソースコード:** Lib/smtplib.py

======================================================================

"smtplib" モジュールは、SMTPまたはESMTPのリスナーデーモンを備えた任意
のインターネット上のホストにメールを送るために使用することができる
SMTPクライアント・セッション・オブジェクトを定義します。 SMTPおよび
ESMTPオペレーションの詳細は、 **RFC 821** (Simple Mail Transfer
Protocol) や **RFC 1869** (SMTP Service Extensions)を調べてください。

利用可能な環境: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは
、WebAssembly プラットフォーム を見てください。

class smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None)

   "SMTP" インスタンスはSMTP接続をカプセル化します。SMTPとESMTP操作の
   完全なレパートリーをサポートするメソッドがあります。オプションパラ
   メータの *host* および *port* が指定されている場合、SMTPの
   "connect()" メソッドは初期化中にこれらのパラメータを使って呼び出さ
   れます。 *local_hostname* を指定した場合、それはHELO/EHLOコマンドの
   ローカルホストのFQDNとして使用されます。指定しない場合、ローカルホ
   スト名は "socket.getfqdn()" を使用して検索されます。 "connect()" 呼
   び出しが成功コード以外を返すと、 "SMTPConnectError" が送出されます
   。オプションの *timeout* パラメータは、接続試行のようなブロッキング
   操作のタイムアウトを秒単位で指定します（指定されていない場合、グロ
   ーバルなデフォルトのタイムアウト設定が使用されます）。タイムアウト
   が切れると、 "TimeoutError" が送出されます。オプションの
   *source_address* パラメータを使用すると、複数のネットワークインター
   フェースを持つマシンの特定の送信元アドレス、かつ（または）特定の送
   信元TCPポートにバインドできます。接続する前にソケットを送信元アドレ
   スとしてバインドするためにタプル "(host, port)" が必要です。省略さ
   れた場合（あるいは、*host* または *port* がそれぞれ "''" かつ/また
   は "0" の場合）、OSのデフォルト動作が使用されます。

   普通に使う場合は、初期化と接続を行ってから、 "sendmail()" と
   "SMTP.quit()" メソッドを呼びます。使用例は先の方で記載しています。

   "SMTP" クラスは "with" 構文をサポートしています。 このように使用す
   ると、 "with" 構文が終了すると、SMTPの "QUIT" コマンドが自動的に発
   行されます。 例えば次のように使います。

      >>> from smtplib import SMTP
      >>> with SMTP("domain.org") as smtp:
      ...     smtp.noop()
      ...
      (250, b'Ok')
      >>>

   全てのコマンドは引数 "self" と "data" を指定して auditing event
   "smtplib.SMTP.send" を送出します。 ここで "data" はリモートホストに
   送信されるバイト列です。

   バージョン 3.3 で変更: "with" 構文のサポートが追加されました。

   バージョン 3.3 で変更: *source_address* 引数が追加されました。

   Added in version 3.5: SMTPUTF8 拡張 (**RFC 6531**) がサポートされま
   した。

   バージョン 3.9 で変更: *timeout* パラメータが0に設定されている場合
   、非ブロッキングソケットの作成を防ぐために "ValueError" を送出しま
   す。

class smtplib.SMTP_SSL(host='', port=0, local_hostname=None, *, [timeout, ]context=None, source_address=None)

   An "SMTP_SSL" instance behaves exactly the same as instances of
   "SMTP". "SMTP_SSL" should be used for situations where SSL is
   required from the beginning of the connection and using
   "starttls()" is not appropriate. If *host* is not specified, the
   local host is used. If *port* is zero, the standard SMTP-over-SSL
   port (465) is used.  The optional arguments *local_hostname*,
   *timeout* and *source_address* have the same meaning as they do in
   the "SMTP" class.  *context*, also optional, can contain a
   "SSLContext" and allows configuring various aspects of the secure
   connection.  Please read セキュリティで考慮すべき点 for best
   practices.

   バージョン 3.3 で変更: *context* が追加されました。

   バージョン 3.3 で変更: *source_address* 引数が追加されました。

   バージョン 3.4 で変更: このクラスは "ssl.SSLContext.check_hostname"
   によるホスト名の検証と、*Server Name Indication* に対応しました
   ("ssl.HAS_SNI" を参照)。

   バージョン 3.9 で変更: *timeout* パラメータが0に設定されている場合
   、非ブロッキングソケットの作成を防ぐために "ValueError" を送出しま
   す。

   バージョン 3.12 で変更: 非推奨の *keyfile* と *certfile* 引数を削除
   しました。

class smtplib.LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None[, timeout])

   The LMTP protocol, which is very similar to ESMTP, is heavily based
   on the standard SMTP client. It's common to use Unix sockets for
   LMTP, so our "connect()" method must support that as well as a
   regular host:port server. The optional arguments *local_hostname*
   and *source_address* have the same meaning as they do in the "SMTP"
   class. To specify a Unix socket, you must use an absolute path for
   *host*, starting with a '/'.

   認証は、通常のSMTP機構を利用してサポートされています。 Unixソケット
   を利用する場合、LMTPは通常認証をサポートしたり要求したりはしません
   。 ただし、環境によって異なる場合があります。

   バージョン 3.9 で変更: オプションの *timeout* 引数が追加されました
   。

このモジュールの例外には次のものがあります:

exception smtplib.SMTPException

   "OSError" の派生クラスで、このモジュールが提供する他の全ての例外の
   基底クラスです。

   バージョン 3.4 で変更: SMTPException が "OSError" の派生クラスにな
   りました。

exception smtplib.SMTPServerDisconnected

   サーバーとの接続が予期せず切断された場合や、サーバーに接続する前に
   "SMTP" インスタンスを使おうとした場合に送出されます。

exception smtplib.SMTPResponseException

   Base class for all exceptions that include an SMTP error code.
   These exceptions are generated in some instances when the SMTP
   server returns an error code.

   smtp_code

      The error code.

   smtp_error

      The error message.

exception smtplib.SMTPSenderRefused

   送信者のアドレスが拒否されたときに送出されます。
   "SMTPResponseException" に共通する属性に加え、"sender" 属性に SMTP
   サーバーが拒否したアドレスの文字列が設定されます。

exception smtplib.SMTPRecipientsRefused

   All recipient addresses refused.

   recipients

      A dictionary of exactly the same sort as returned by
      "SMTP.sendmail()" containing the errors for each recipient.

exception smtplib.SMTPDataError

   SMTPサーバが、メッセージのデータを受け入れることを拒絶したときに送
   出される例外です。

exception smtplib.SMTPConnectError

   サーバへの接続時にエラーが発生したときに送出される例外です。

exception smtplib.SMTPHeloError

   サーバーが "HELO" メッセージを弾いたときに送出される例外です。

exception smtplib.SMTPNotSupportedError

   試行したコマンドやオプションはサーバにサポートされていません。

   Added in version 3.5.

exception smtplib.SMTPAuthenticationError

   SMTP 認証が失敗しました。最もあり得るのは、サーバーがユーザ名/パス
   ワードのペアを受け付なかった事です。

参考:

  **RFC 821** - Simple Mail Transfer Protocol
     SMTP のプロトコル定義です。このドキュメントでは SMTP のモデル、操
     作手順、プロトコルの詳細についてカバーしています。

  **RFC 1869** - SMTP Service Extensions
     SMTP に対する ESMTP 拡張の定義です。このドキュメントでは、新たな
     命令による SMTP の拡張、サーバによって提供される命令を動的に発見
     する機能のサポート、およびいくつかの追加命令定義について記述して
     います。


SMTP オブジェクト
=================

"SMTP" クラスインスタンスは次のメソッドを提供します:

SMTP.set_debuglevel(level)

   デバッグ出力レベルを設定します。*level* が 1 や "True" の場合、接続
   ならびにサーバとの送受信のメッセージがデバッグメッセージとなります
   。*level* が 2 の場合、それらのメッセージにタイムスタンプが付きます
   。

   バージョン 3.5 で変更: デバッグレベル2が追加されました。

SMTP.docmd(cmd, args='')

   サーバにコマンド *cmd* を送信します。 省略可能な *args* 引数は、ス
   ペースで区切ってコマンドに単純に連結します。

   数値応答コードと実際の応答行 (複数の応答は 1 つの長い行に結合されま
   す) からなる 2 値タプルを返します。

   通常、このメソッドを明示的に使う必要はありません。他のメソッドを実
   装するのに使い、自分で拡張したものをテストするのに役立つかもしれま
   せん。

   応答待ちのときにサーバへの接続が切れると "SMTPServerDisconnected"
   が送出されます。

SMTP.connect(host='localhost', port=0)

   ホスト名とポート番号をもとに接続します。 デフォルトはlocalhostの標
   準的なSMTPポート(25番)に接続します。 もしホスト名の末尾がコロン
   ("':'")で、後に番号がついている場合は、「ホスト名:ポート番号」とし
   て扱われます。 このメソッドはコンストラクタにホスト名が指定されてい
   る場合、自動的に呼び出されます。 戻り値は、この接続の応答内でサーバ
   によって送信された応答コードとメッセージの2要素タプルです。

   引数 "self", "host", "port" を指定して 監査イベント
   "smtplib.connect" を送出します。

SMTP.helo(name='')

   SMTPサーバに "HELO" コマンドで身元を示します。 ホスト名を指定する引
   数のデフォルトは、ローカルホストの完全修飾ドメイン名です。 サーバー
   が返したメッセージは、オブジェクトの "helo_resp" 属性に格納されます
   。

   通常は "sendmail()" が呼びだすため、これを明示的に呼び出す必要はあ
   りません。

SMTP.ehlo(name='')

   "EHLO" を利用し、ESMTPサーバに身元を明かします。デフォルトでは
   hostname引数はローカルホストのFQDNです。また、ESMTPオプションのため
   に応答を調べたものは、 "has_extn()" に備えて保存されます。また、幾
   つかの情報を属性に保存します: サーバーが返したメッセージは
   "ehlo_resp" 属性に、 "does_esmtp" 属性はサーバーがESMTPをサポートし
   ているかどうかによって "True" か "False" に、 "esmtp_features" 属性
   は辞書で、サーバーが対応しているSMTP サービス拡張の名前と、もしあれ
   ばそのパラメータを格納します。

   メールを送信する前に "has_extn()" を使おうとしない限り、このメソッ
   ドを明示的に呼ぶ必要はないはずです。必要な場合は "sendmail()" に暗
   黙的に呼ばれます。

SMTP.ehlo_or_helo_if_needed()

   このメソッドは、現在のセッションでまだ "EHLO" か "HELO" コマンドが
   実行されていない場合、 "ehlo()" and/or "helo()" メソッドを呼び出し
   ます。このメソッドは先に ESMTP "EHLO" を試します。

   "SMTPHeloError"
      サーバーが "HELO" に正しく返答しませんでした。

SMTP.has_extn(name)

   *name* が拡張SMTPサービスセットに含まれている場合には "True" を返し
   、そうでなければ "False" を返します。大小文字は区別されません。

SMTP.verify(address)

   "VRFY" を利用してSMTPサーバにアドレスの妥当性をチェックします。妥当
   である場合はコード250と完全な **RFC 822** アドレス (人名を含む) の
   タプルを返します。それ以外の場合は、400以上のエラーコードとエラー文
   字列を返します。

   注釈:

     スパマーによる悪用を防ぐため、多くのサイトでは SMTP の "VRFY" を
     無効にしています。

SMTP.login(user, password, *, initial_response_ok=True)

   認証が必要な SMTP サーバにログインします。 引数は認証に使用するユー
   ザ名とパスワードです。 このセッションでまだ "EHLO" または "HELO" コ
   マンドを送信していない場合は、まず ESMTP の "EHLO" を試みます。 認
   証に成功するとこのメソッドは正常に戻りますが、次の例外を送出する場
   合があります:

   "SMTPHeloError"
      サーバーが "HELO" に正しく返答しませんでした。

   "SMTPAuthenticationError"
      サーバがユーザ名/パスワードでの認証に失敗しました。

   "SMTPNotSupportedError"
      "AUTH" コマンドはサーバにサポートされていません。

   "SMTPException"
      適当な認証方法が見付かりませんでした。

   Each of the authentication methods supported by "smtplib" are tried
   in turn if they are advertised as supported by the server.  See
   "auth()" for a list of supported authentication methods.
   *initial_response_ok* is passed through to "auth()".

   オプションのキーワード引数 *initial_response_ok* は、それをサポート
   する認証方法に対して、チャレンジ/レスポンスを要求するのではなく、
   "AUTH"コマンドとともに **RFC 4954** で指定された"初期応答"を送信で
   きるかどうかを指定します。

   バージョン 3.5 で変更: "SMTPNotSupportedError" が送出される場合があ
   ります。*initial_response_ok* 引数が追加されました。

SMTP.auth(mechanism, authobject, *, initial_response_ok=True)

   指定した認証方式 *mechanism* で "SMTP" の "AUTH" コマンドを発行し、
   *authobject* を通してチャレンジレスポンスを処理します。

   *mechanism* は、"AUTH" コマンドの引数として指定する認証方式です。
   有効な値は "esmtp_features" の "auth" 要素に列挙されているものです
   。

   *authobject* は、省略可能な引数を一つ取る呼び出し可能オブジェクトで
   なければなりません。

      data = authobject(challenge=None)

   省略可能なキーワード引数 *initial_response_ok* が真の場合、まず引数
   なしで "authobject()" を呼び出します。 この呼び出しでは、**RFC
   4954** の「初期応答」を ASCII の "str" で返せます。 その文字列は、
   下記のようにエンコードして "AUTH" コマンドとともに送信します。
   "authobject()" が初期応答に対応しない場合 (例えばチャレンジが必要な
   場合) は、"challenge=None" で呼び出されたときに "None" を返してくだ
   さい。 *initial_response_ok* が偽の場合、最初に "None" を指定して
   "authobject()" を呼び出すことはありません。

   初期応答の確認で "None" が返った場合、または *initial_response_ok*
   が偽の場合は、サーバのチャレンジレスポンスを処理するために
   "authobject()" を呼び出します。 渡される *challenge* 引数は "bytes"
   です。 ASCII の "str" で *data* を返す必要があり、その値を base64
   でエンコードしてサーバに送信します。

   "SMTP" クラスは、"CRAM-MD5"、"PLAIN"、"LOGIN" の各方式に対応する
   "authobjects" として、それぞれ "SMTP.auth_cram_md5"、
   "SMTP.auth_plain"、"SMTP.auth_login" を提供します。 いずれも、
   "SMTP" インスタンスの "user" と "password" プロパティに適切な値を設
   定しておく必要があります。

   User code does not normally need to call "auth" directly, but can
   instead call the "login()" method, which will try each of the above
   mechanisms in turn, in the order listed.  "auth" is exposed to
   facilitate the implementation of authentication methods not (or not
   yet) supported directly by "smtplib".

   Added in version 3.5.

SMTP.starttls(*, context=None)

   SMTP 接続を TLS (Transport Layer Security) モードに切り替えます。
   続く全てのSMTP コマンドは暗号化されます。 その後、もう一度 "ehlo()"
   を呼んでください。

   If *keyfile* and *certfile* are provided, they are used to create
   an "ssl.SSLContext".

   Optional *context* parameter is an "ssl.SSLContext" object; This is
   an alternative to using a keyfile and a certfile and if specified
   both *keyfile* and *certfile* should be "None".

   もしまだ "EHLO" か "HELO" コマンドが実行されていない場合、このメソ
   ッドは ESMTP "EHLO" を先に試します。

   バージョン 3.12 で変更: 非推奨の *keyfile* と *certfile* 引数を削除
   しました。

   "SMTPHeloError"
      サーバーが "HELO" に正しく返答しませんでした。

   "SMTPNotSupportedError"
      サーバーが STARTTLS 拡張に対応していません。

   "RuntimeError"
      実行中の Python インタプリタで、SSL/TLS サポートが利用できません
      。

   バージョン 3.3 で変更: *context* が追加されました。

   バージョン 3.4 で変更: The method now supports hostname check with
   "ssl.SSLContext.check_hostname" and *Server Name Indicator* (see
   "HAS_SNI").

   バージョン 3.5 で変更: STARTTLS に対応していない場合の例外は、基底
   の "SMTPException" ではなく、そのサブクラスの
   "SMTPNotSupportedError" になりました。

SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())

   Send mail.  The required arguments are an **RFC 822** from-address
   string, a list of **RFC 822** to-address strings (a bare string
   will be treated as a list with 1 address), and a message string.
   The caller may pass a list of ESMTP options (such as ""8bitmime"")
   to be used in "MAIL FROM" commands as *mail_options*. ESMTP options
   (such as "DSN" commands) that should be used with all "RCPT"
   commands can be passed as *rcpt_options*. Each option should be
   passed as a string containing the full text of the option,
   including any potential key (for instance,
   ""NOTIFY=SUCCESS,FAILURE""). (If you need to use different ESMTP
   options to different recipients you have to use the low-level
   methods such as "mail()", "rcpt()" and "data()" to send the
   message.)

   注釈:

     *from_addr* と *to_addrs* 引数は、配送エージェントが使うメッセー
     ジエンベロープの作成に使われます。 "sendmail" はメッセージヘッダ
     ーを一切変更しません。

   *msg* には、ASCII 範囲の文字からなる文字列、またはバイト列を指定で
   きます。 文字列は ascii コーデックでバイト列にエンコードし、単独の
   "\r" と "\n" を "\r\n" に変換します。 バイト列は変更しません。

   このセッションでまだ "EHLO" または "HELO" コマンドを送っていない場
   合、まず ESMTP の "EHLO" を試みます。 サーバーが ESMTP に対応してい
   れば、メッセージサイズと、指定された各オプションのうちサーバーが対
   応を通知したものを渡します。 "EHLO" が失敗すると "HELO" を試み、
   ESMTP オプションは渡しません。

   このメソッドは少なくとも 1 人の受信者宛てのメールが受理されたときは
   正常に戻ります。 そうでない場合は例外を投げます。 つまり、このメソ
   ッドが例外を送出しないときは誰かにはメールが届くはずです。 また、例
   外を送出しない場合は拒絶された受信者ごとに項目のある辞書を返します
   。 各項目はサーバーが送ったSMTPエラーコードと付随するエラーメッセー
   ジのタプルを持ちます。

   *mail_options* に "SMTPUTF8" があり、サーバがサポートしている場合は
   、*from_addr* と *to_addrs* に非 ASCII 文字を含めることが出来ます。

   このメソッドは次の例外を送出することがあります:

   "SMTPRecipientsRefused"
      All recipients were refused.  Nobody got the mail.

   "SMTPHeloError"
      サーバーが "HELO" に正しく返答しませんでした。

   "SMTPSenderRefused"
      サーバが *from_addr* を受理しませんでした。

   "SMTPDataError"
      サーバが予期しないエラーコードを返しました (受信拒否以外)。

   "SMTPNotSupportedError"
      *mail_options* に "SMTPUTF8" が与えられましたが、サーバがサポー
      トしていません。

   特に記載がない限り、例外が送出された後もコネクションは開いたままに
   なっています。

   バージョン 3.2 で変更: *msg* はバイト文字列でも構いません。

   バージョン 3.5 で変更: "SMTPUTF8" のサポートが追加されました。
   "SMTPUTF8" が与えられたが、サーバがサポートしていない場合は
   "SMTPNotSupportedError" が送出されます。

SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())

   "email.message.Message" オブジェクトで表されたメッセージを使って
   "sendmail()" を呼び出すための便利なメソッドです。 引数の意味は
   "sendmail()" と同じですが、*msg* は "Message" オブジェクトです。

   *from_addr* または *to_addrs* が "None" の場合、"send_message" は
   **RFC 5322** に従って *msg* のヘッダーからアドレスを取り出し、その
   引数を補います。 *from_addr* は、*Sender* フィールドがあればその値
   、なければ *From* フィールドの値になります。 *to_addrs* は、*msg*
   にある *To*、*Cc*、*Bcc* フィールドの値をまとめたものになります。
   メッセージに *Resent-** ヘッダーの組がちょうど一つあれば、通常のヘ
   ッダーを無視して *Resent-** ヘッダーを使います。 *Resent-** ヘッダ
   ーの組が複数ある場合、どの *Resent-* ヘッダーの組が最新かを一意に特
   定できないため、"ValueError" を送出します。

   "send_message" serializes *msg* using "BytesGenerator" with "\r\n"
   as the *linesep*, and calls "sendmail()" to transmit the resulting
   message.  Regardless of the values of *from_addr* and *to_addrs*,
   "send_message" does not transmit any *Bcc* or *Resent-Bcc* headers
   that may appear in *msg*.  If any of the addresses in *from_addr*
   and *to_addrs* contain non-ASCII characters and the server does not
   advertise "SMTPUTF8" support, an "SMTPNotSupportedError" is raised.
   Otherwise the "Message" is serialized with a clone of its "policy"
   with the "utf8" attribute set to "True", and "SMTPUTF8" and
   "BODY=8BITMIME" are added to *mail_options*.

   Added in version 3.2.

   Added in version 3.5: 国際化アドレスのサポート ("SMTPUTF8")。

SMTP.quit()

   SMTPセッションを終了し、接続を閉じます。SMTP "QUIT" コマンドの結果
   を返します。

下位レベルのメソッドは標準SMTP/ESMTPコマンド "HELP" 、 "RSET" 、
"NOOP" 、 "MAIL" 、 "RCPT" 、 "DATA" に対応しています。通常これらは直
接呼ぶ必要はなく、また、ドキュメントもありません。詳細はモジュールのコ
ードを調べてください。

Additionally, an SMTP instance has the following attributes:

SMTP.helo_resp

   The response to the "HELO" command, see "helo()".

SMTP.ehlo_resp

   The response to the "EHLO" command, see "ehlo()".

SMTP.does_esmtp

   A boolean value indicating whether the server supports ESMTP, see
   "ehlo()".

SMTP.esmtp_features

   A dictionary of the names of SMTP service extensions supported by
   the server, see "ehlo()".


SMTP 使用例
===========

This example prompts the user for addresses needed in the message
envelope ('To' and 'From' addresses), and the message to be delivered.
Note that the headers to be included with the message must be included
in the message as entered; this example doesn't do any processing of
the **RFC 822** headers.  In particular, the 'To' and 'From' addresses
must be included in the message headers explicitly:

   import smtplib

   def prompt(title):
       return input(title).strip()

   from_addr = prompt("From: ")
   to_addrs  = prompt("To: ").split()
   print("Enter message, end with ^D (Unix) or ^Z (Windows):")

   # 最初に From: と To: ヘッダーを追加します。
   lines = [f"From: {from_addr}", f"To: {', '.join(to_addrs)}", ""]
   while True:
       try:
           line = input()
       except EOFError:
           break
       else:
           lines.append(line)

   msg = "\r\n".join(lines)
   print("Message length is", len(msg))

   server = smtplib.SMTP("localhost")
   server.set_debuglevel(1)
   server.sendmail(from_addr, to_addrs, msg)
   server.quit()

注釈:

  多くの場合、 "email" パッケージの機能を使って email メッセージを構築
  し、それを、 "send_message()" で送信する、という手順を用います。
  email: 使用例 を参照してください。
