1
0

ディレクトリ内にあるHTMLファイルを読み込んで、その内容をメール本文として送信する

Posted at

Python 2.7でディレクトリ内にあるHTMLファイルを読み込んで、その内容をメール本文として送信するには、以下のスクリプトを使用できます。この例では、HTMLファイルを読み込み、email.mime.text.MIMETextを使って'html'形式でメールを構築します。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# メールパラメータ設定
sender_email = "your_email@gmail.com"
receiver_email = "receiver_email@example.com"
password = "your_password"  # Gmailのパスワード
smtp_server = "smtp.gmail.com"
smtp_port = 587

# メールの件名とHTMLファイルのパス
subject = "HTMLファイルからのメール"
html_file_path = "path/to/your/file.html"

# HTMLファイルを読み込み
with open(html_file_path, 'r') as file:
    html_content = file.read()

# メールメッセージの作成
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# HTMLの本文を追加
message.attach(MIMEText(html_content, "html"))

# SMTPサーバーへ接続してメールを送信
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()  # セキュリティのためTLSを使用
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())
    print("メールが正常に送信されました。")
finally:
    server.quit()

このスクリプトを実行する前に、以下の変数を適切な値に変更してください:

  • sender_email: 送信者のメールアドレス
  • receiver_email: 受信者のメールアドレス
  • password: 送信者のメールアカウントのパスワード
  • html_file_path: 送信したいHTMLファイルのパス

また、Gmailを使ってメールを送信する場合は、Googleアカウントのセキュリティ設定に注意してください。"安全性の低いアプリのアクセス"を許可する設定や、2段階認証プロセスを使用している場合は、アプリパスワードを生成して使用する必要があります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0