Python3-python-sending-email

提供:Dev Guides
移動先:案内検索

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

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

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

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

import smtplib

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

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

  • host -これは、SMTPサーバーを実行しているホストです。 ホストのIPアドレスまたはfinddevguides.comのようなドメイン名を指定できます。 これはオプションの引数です。
  • port -_host_引数を指定する場合、SMTPサーバーがリッスンしているポートを指定する必要があります。 通常、このポートは25です。
  • local_hostname -SMTPサーバーがローカルマシンで実行されている場合、_localhost_オプションのみを指定できます。

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

  • sender-送信者のアドレスを含む文字列。
  • receivers-文字列のリスト、各受信者に1つ。
  • message-さまざまなRFCで指定された形式の文字列としてのメッセージ。

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

#!/usr/bin/python3

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"

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

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

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

mail = smtplib.SMTP('smtp.gmail.com', 587)

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

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

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

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

#!/usr/bin/python3

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 に設定する必要があります。 次に、テキストと添付セクションを boundaries 内で指定できます。

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

添付ファイルは、* pack( "m")*関数でエンコードしてから、送信前にBase 64エンコードにする必要があります。

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

#!/usr/bin/python3

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")