前提条件
- smtplibモジュール インスト
- Googleアカウントの2段階認証を有効にし、アカウントからアプリパスワード発行
- 送りたいPDFを、pythonコードがある同じディレクトリに置く
インストモジュール
pip install secure-smtplib
ディレクトリ構造
/プロジェクトフォルダ/
├── send_email.py
└── hogehoge 履歴書.pdf
└── hogehoge 職務経歴書.pdf
アプリパスワード発行手順
- このリンクにアクセス
アプリ名を入力
- 「生成」クリック
- アプリパスワード をコピーし、ここに貼り付け
アプリパスワード貼り付け場所
app_password = "✳️✳️✳️✳️✳️✳️"
メール送信ループしてないか確認
server.sendmail(sender_email, recipient_email, msg.as_string())
print("送信結果:", response)
実行結果
コード全文
qiita.rb
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header
import os
def send_email_with_pdfs(sender_email, recipient_email, subject, body, pdf_files, app_password):
# メールの設定
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = subject
# メール本文の追加
msg.attach(MIMEText(body, 'plain'))
# 添付するPDFファイルの追加
for pdf_file in pdf_files:
try:
if os.path.exists(pdf_file):
with open(pdf_file, 'rb') as file:
part = MIMEBase('application', 'octet-stream')
part.set_payload(file.read())
encoders.encode_base64(part)
# ファイル名をエンコードして日本語(漢字)対応
part.add_header('Content-Disposition',
'attachment',
filename=(Header(os.path.basename(pdf_file), 'utf-8').encode()))
msg.attach(part)
else:
print(f"File not found: {pdf_file}")
except Exception as e:
print(f"Error attaching {pdf_file}: {e}")
# SMTPサーバーを使ってメール送信
try:
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls() # セキュア接続を開始
server.login(sender_email, app_password) # アプリパスワードを使用
server.sendmail(sender_email, recipient_email, msg.as_string())
print('成功!')
except Exception as e:
print(f"メール送れんかったよ: {e}")
# 使用例
sender_email = "hageo@gmail.com"
recipient_email = "hageo@gmail.com"
subject = "書類のご送付"
body = "メール、ありがとうございます。書類を送ります。"
pdf_files = ["履歴書 hogehoge.pdf", "ほげお 職務経歴書.pdf"]
app_password = "adabura katabura hechhara" # ここにアプリパスワードを入力
send_email_with_pdfs(sender_email, recipient_email, subject, body, pdf_files, app_password)