ここまでで紹介した レポート生成 → PDF化 → メール送信 → クラウド共有 を一連の流れとして自動化すれば、完全な「レポート配布パイプライン」が構築できます。これにより、データ更新から配布までをワンクリックで実行可能になります。
サンプルコード(統合パイプライン)
import json
from docx import Document
from docx2pdf import convert
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
# --- Step 1: レポート生成 (Word) ---
def generate_report():
doc = Document()
doc.add_heading("分析レポート", level=1)
doc.add_paragraph("このレポートは自動生成されました。")
doc.add_heading("第1章: 集計結果", level=2)
categories = {"small": 12, "medium": 8, "large": 5}
for k, v in categories.items():
doc.add_paragraph(f"{k}: {v}件")
doc.save("report.docx")
print("Wordレポートを生成しました。")
# --- Step 2: PDF化 ---
def convert_to_pdf():
convert("report.docx", "report.pdf")
print("PDFに変換しました。")
# --- Step 3: メール送信 ---
def send_email():
sender = "your_email@example.com"
receiver = "receiver@example.com"
subject = "自動生成レポート"
body = "添付のPDFレポートをご確認ください。"
msg = MIMEMultipart()
msg["From"] = sender
msg["To"] = receiver
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))
with open("report.pdf", "rb") as f:
part = MIMEApplication(f.read(), Name="report.pdf")
part['Content-Disposition'] = 'attachment; filename="report.pdf"'
msg.attach(part)
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login("your_email@example.com", "your_password")
server.send_message(msg)
print("メール送信しました。")
# --- Step 4: クラウド共有 (Google Drive) ---
def upload_to_drive():
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
file = drive.CreateFile({'title': 'report.pdf'})
file.SetContentFile('report.pdf')
file.Upload()
file.InsertPermission({'type': 'anyone', 'value': 'anyone', 'role': 'reader'})
print("Google Drive共有リンク:", file['alternateLink'])
# --- パイプライン実行 ---
generate_report()
convert_to_pdf()
send_email()
upload_to_drive()
Python解説ポイント
- Step 1 → Word レポートを自動生成。
- Step 2 →
docx2pdfで PDF に変換。 - Step 3 → SMTP を使って PDF をメール送信。
- Step 4 → Google Drive API でクラウド共有リンクを生成。
- 一括実行 → 関数を順番に呼び出すことで、完全自動化パイプラインが完成。
応用の場面
- 定期レポート配布 → 毎週の分析結果を自動で PDF化し、メール+クラウド共有。
- チーム共有 → 社内で自動的にレポートを配布。
- 顧客向けレポート → 外部顧客に定期的に PDF を送信し、クラウドリンクも提供。
まとめ
- レポート生成から配布までを 一括自動化することで、業務効率が大幅に向上。
- Word → PDF → メール送信 → クラウド共有 の流れをスクリプト化すれば、完全な配布パイプラインが構築できる。
- この仕組みを定期実行すれば、完全自動レポート配布システムが完成。


