工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python - SMTP を使用して電子メールを送信する

前のページ次のページ

Simple Mail Transfer Protocol (SMTP) は、電子メールの送信とメール サーバー間の電子メールのルーティングを処理するプロトコルです。

Python は smtplib を提供します このモジュールは、SMTP または ESMTP リスナー デーモンを備えた任意のインターネット マシンにメールを送信するために使用できる SMTP クライアント セッション オブジェクトを定義します。

これは、後で電子メールを送信するために使用できる、1 つの SMTP オブジェクトを作成するための簡単な構文です −

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

ここにパラメータの詳細があります −

SMTP オブジェクトには、sendmail というインスタンス メソッドがあります。 、通常、メッセージを送信する作業を行うために使用されます。 3 つのパラメータを取ります −

ここでは、Python スクリプトを使用して 1 つの電子メールを送信する簡単な方法を示します。一度試してみてください−

#!/usr/bin/python

import smtplib

sender = '[email protected]'
receivers = ['[email protected]']

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

ここでは、基本的な電子メールをメッセージに配置し、三重引用符を使用して、ヘッダーを正しくフォーマットするように注意しています。電子メールには 差出人 が必要です 、宛先件名 空行で電子メールの本文と区切られたヘッダー。

smtpObj を使用してメールを送信するには ローカル マシン上の SMTP サーバーに接続し、sendmail を使用します。 メッセージ、差出人アドレス、および宛先アドレスをパラメーターとしてメソッドと共に使用します (差出人アドレスと宛先アドレスは電子メール自体の中にありますが、これらは常にメールのルーティングに使用されるわけではありません)。

ローカル マシンで SMTP サーバーを実行していない場合は、smtplib を使用できます。 リモート SMTP サーバーと通信するためのクライアント。ウェブメール サービス (Hotmail や Yahoo! メールなど) を使用していない限り、次のように、電子メール プロバイダーから送信メール サーバーの詳細が提供されている必要があります。

smtplib.SMTP('mail.your-domain.com', 25)

Python を使用して HTML メールを送信する

Python を使用してテキスト メッセージを送信すると、すべてのコンテンツが単純なテキストとして扱われます。テキスト メッセージに HTML タグを含めても、単純なテキストとして表示され、HTML タグは HTML 構文に従ってフォーマットされません。ただし、Python には、HTML メッセージを実際の HTML メッセージとして送信するオプションがあります。

電子メール メッセージを送信するときに、Mime バージョン、コンテンツ タイプ、および文字セットを指定して、HTML 電子メールを送信できます。

以下は、HTML コンテンツを電子メールとして送信する例です。一度試してみてください−

#!/usr/bin/python

import smtplib

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

添付ファイルを電子メールとして送信

混合コンテンツの電子メールを送信するには、Content-type を設定する必要があります multipart/mixed へのヘッダー .次に、境界内でテキストと添付セクションを指定できます .

境界は 2 つのハイフンで始まり、その後に一意の番号が続きます。この番号は電子メールのメッセージ部分には表示されません。電子メールの最終セクションを示す最後の境界も、2 つのハイフンで終了する必要があります。

添付ファイルは pack("m") でエンコードする必要があります 送信前に base64 エンコーディングを持つ関数。

以下は、ファイル /tmp/test.txt を送信する例です。 添付ファイルとして。一度試してみてください−

#!/usr/bin/python

import smtplib
import base64

filename = "/tmp/test.txt"

# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = '[email protected]'
reciever = '[email protected]'

marker = "AUNIQUEMARKER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"

Python

  1. Python データ型
  2. Python 演算子
  3. Python pass ステートメント
  4. Python 関数の引数
  5. Python 辞書
  6. try、except、finally ステートメントを使用した Python 例外処理
  7. Raspberry piを使用したTMP006温度センサーPythonライブラリ、
  8. PythonとRaspberryPiの温度センサー
  9. Python Average:Python でリストの AVERAGE を見つける方法
  10. 3 つ目の変数を使用せずに 2 つの Python 変数を交換する
  11. Java - 電子メールの送信