Python-sending-email

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

Python-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/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"

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

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

ローカルマシンでSMTPサーバーを実行していない場合は、_smtplib_クライアントを使用してリモートSMTPサーバーと通信できます。 Webメールサービス(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 に設定する必要があります。 次に、 boundaries 内でテキストと添付セクションを指定できます。

境界は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"