smtplib --- SMTP プロトコルクライアント¶
ソースコード: Lib/smtplib.py
smtplib モジュールは、SMTPまたはESMTPのリスナーデーモンを備えた任意のインターネット上のホストにメールを送るために使用することができる SMTPクライアント・セッション・オブジェクトを定義します。 SMTPおよびESMTPオペレーションの詳細は、 RFC 821 (Simple Mail Transfer Protocol) や RFC 1869 (SMTP Service Extensions)を調べてください。
Availability: 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()メソッドを呼びます。使用例は先の方で記載しています。The
SMTPclass supports thewithstatement. When used like this, the SMTPQUITcommand is issued automatically when thewithstatement exits. E.g.:>>> from smtplib import SMTP >>> with SMTP("domain.org") as smtp: ... smtp.noop() ... (250, b'Ok') >>>
全てのコマンドは引数
selfとdataを指定して auditing eventsmtplib.SMTP.sendを送出します。ここでdataはリモートホストに送信されるバイト数です。バージョン 3.3 で変更:
with構文のサポートが追加されました。バージョン 3.3 で変更: source_address argument was added.
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_SSLinstance behaves exactly the same as instances ofSMTP.SMTP_SSLshould be used for situations where SSL is required from the beginning of the connection and usingstarttls()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 theSMTPclass. context, also optional, can contain aSSLContextand allows configuring various aspects of the secure connection. Please read セキュリティで考慮すべき点 for best practices.バージョン 3.3 で変更: context が追加されました。
バージョン 3.3 で変更: The source_address argument was added.
バージョン 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 theSMTPclass. 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.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¶
エラーコード。
- smtp_error¶
The error message.
- exception smtplib.SMTPSenderRefused¶
送信者のアドレスが弾かれたときに送出される例外です。全ての
SMTPResponseException例外に、 SMTPサーバが弾いた 'sender' アドレスの文字列がセットされます。
- 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 認証が失敗しました。最もあり得るのは、サーバーがユーザ名/パスワードのペアを受け付なかった事です。
参考
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コマンドで身元を示します。デフォルトではhostname引数はローカルホストを指します。サーバーが返したメッセージは、オブジェクトの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/orhelo()メソッドを呼び出します。このメソッドは先に ESMTPEHLOを試します。SMTPHeloErrorサーバーが
HELOに正しく返答しませんでした。
- 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サーバがユーザ名/パスワードでの認証に失敗しました。
SMTPNotSupportedErrorAUTHコマンドはサーバにサポートされていません。SMTPException適当な認証方法が見付かりませんでした。
Each of the authentication methods supported by
smtplibare tried in turn if they are advertised as supported by the server. Seeauth()for a list of supported authentication methods. initial_response_ok is passed through toauth().オプションのキーワード引数 initial_response_ok は、それをサポートする認証方法に対して、チャレンジ/レスポンスを要求するのではなく、 "AUTH"コマンドとともに RFC 4954 で指定された"初期応答"を送信できるかどうかを指定します。
バージョン 3.5 で変更:
SMTPNotSupportedErrorが送出される場合があります。initial_response_ok 引数が追加されました。
- SMTP.auth(mechanism, authobject, *, initial_response_ok=True)¶
Issue an
SMTPAUTHcommand for the specified authentication mechanism, and handle the challenge response via authobject.mechanism specifies which authentication mechanism is to be used as argument to the
AUTHcommand; the valid values are those listed in theauthelement ofesmtp_features.authobject must be a callable object taking an optional single argument:
data = authobject(challenge=None)
If optional keyword argument initial_response_ok is true,
authobject()will be called first with no argument. It can return the RFC 4954 "initial response" ASCIIstrwhich will be encoded and sent with theAUTHcommand as below. If theauthobject()does not support an initial response (e.g. because it requires a challenge), it should returnNonewhen called withchallenge=None. If initial_response_ok is false, thenauthobject()will not be called first withNone.If the initial response check returns
None, or if initial_response_ok is false,authobject()will be called to process the server's challenge response; the challenge argument it is passed will be abytes. It should return ASCIIstrdata that will be base64 encoded and sent to the server.The
SMTPclass providesauthobjectsfor theCRAM-MD5,PLAIN, andLOGINmechanisms; they are namedSMTP.auth_cram_md5,SMTP.auth_plain, andSMTP.auth_loginrespectively. They all require that theuserandpasswordproperties of theSMTPinstance are set to appropriate values.User code does not normally need to call
authdirectly, but can instead call thelogin()method, which will try each of the above mechanisms in turn, in the order listed.authis exposed to facilitate the implementation of authentication methods not (or not yet) supported directly bysmtplib.Added in version 3.5.
- SMTP.starttls(*, context=None)¶
TLS (Transport Layer Security) モードで SMTP 接続します。続く全てのSMTP コマンドは暗号化されます。その後、もう一度
ehlo()を呼んでください。If keyfile and certfile are provided, they are used to create an
ssl.SSLContext.Optional context parameter is an
ssl.SSLContextobject; This is an alternative to using a keyfile and a certfile and if specified both keyfile and certfile should beNone.もしまだ
EHLOかHELOコマンドが実行されていない場合、このメソッドは ESMTPEHLOを先に試します。バージョン 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_hostnameand Server Name Indicator (seeHAS_SNI).バージョン 3.5 で変更: The error raised for lack of STARTTLS support is now the
SMTPNotSupportedErrorsubclass instead of the baseSMTPException.
- 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 inMAIL FROMcommands as mail_options. ESMTP options (such asDSNcommands) that should be used with allRCPTcommands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such asmail(),rcpt()anddata()to send the message.)注釈
配送エージェントは from_addr、to_addrs 引数を使い、メッセージのエンベロープを構成します。
sendmailはメッセージヘッダを修正しません。msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone
\rand\ncharacters are converted to\r\ncharacters. A byte string is not modified.まだセッションが無い場合は、
EHLOまたはHELOコマンドでセッションを作ります。ESMTPの場合はEHLOが先に試されます。また、サーバがESMTP対応ならば、メッセージサイズとそれぞれ指定されたオプションも渡します。(featureオプションがあればサーバの広告をセットします)EHLOが失敗した場合は、ESMTPオプションの無いHELOが試されます。このメソッドは最低でも1人の受信者にメールが受け取られたときは正常に戻ります。そうでない場合は例外を投げます。つまり、このメソッドが例外を送出しないときは誰かが送信したメールを受け取ったはずです。また、例外を送出しない場合は拒絶された受信者ごとに項目のある辞書を返します。各項目はサーバーが送ったSMTPエラーコードと付随するエラーメッセージのタプルを持ちます。
mail_options に
SMTPUTF8があり、サーバがサポートしている場合は、from_addr と to_addrs に非 ASCII 文字を含めることが出来ます。このメソッドは次の例外を送出することがあります:
SMTPRecipientsRefusedAll recipients were refused. Nobody got the mail.
SMTPHeloErrorサーバーが
HELOに正しく返答しませんでした。SMTPSenderRefusedサーバが from_addr を受理しませんでした。
SMTPDataErrorサーバが予期しないエラーコードを返しました (受信拒否以外)。
SMTPNotSupportedErrormail_options に
SMTPUTF8が与えられましたが、サーバがサポートしていません。
また、この他の注意として、例外が上がった後もコネクションは開いたままになっています。
バージョン 3.2 で変更: msg はバイト文字列でも構いません。
バージョン 3.5 で変更:
SMTPUTF8のサポートが追加されました。SMTPUTF8が与えられたが、サーバがサポートしていない場合はSMTPNotSupportedErrorが送出されます。
- SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())¶
This is a convenience method for calling
sendmail()with the message represented by anemail.message.Messageobject. The arguments have the same meaning as forsendmail(), except that msg is aMessageobject.If from_addr is
Noneor to_addrs isNone,send_messagefills those arguments with addresses extracted from the headers of msg as specified in RFC 5322: from_addr is set to the Sender field if it is present, and otherwise to the From field. to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. If exactly one set of Resent-* headers appear in the message, the regular headers are ignored and the Resent-* headers are used instead. If the message contains more than one set of Resent-* headers, aValueErroris raised, since there is no way to unambiguously detect the most recent set of Resent- headers.send_messageserializes msg usingBytesGeneratorwith\r\nas the linesep, and callssendmail()to transmit the resulting message. Regardless of the values of from_addr and to_addrs,send_messagedoes 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 advertiseSMTPUTF8support, anSMTPNotSupportedErroris raised. Otherwise theMessageis serialized with a clone of itspolicywith theutf8attribute set toTrue, andSMTPUTF8andBODY=8BITMIMEare 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 使用例¶
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):")
# Add the From: and To: headers at the start!
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: 使用例 を参照してください。