0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メールPDF、自動送信(1つのメアドのみ) ※セキュリティ弱

Posted at

前提条件

  • smtplibモジュール インスト
  • Googleアカウントの2段階認証を有効にし、アカウントからアプリパスワード発行
  • 送りたいPDFを、pythonコードがある同じディレクトリに置く
インストモジュール
pip install secure-smtplib   

ディレクトリ構造
/プロジェクトフォルダ/
  ├── send_email.py    
  └── hogehoge 履歴書.pdf     
  └── hogehoge 職務経歴書.pdf    

アプリパスワード発行手順

  • このリンクにアクセス

アプリ名を入力

スクリーンショット 2025-02-19 18.26.37.png

  • 「生成」クリック
  • アプリパスワード をコピーし、ここに貼り付け
アプリパスワード貼り付け場所
app_password = "✳️✳️✳️✳️✳️✳️"   
メール送信ループしてないか確認
server.sendmail(sender_email, recipient_email, msg.as_string())
print("送信結果:", response)

実行結果

スクリーンショット 2025-02-19 19.09.17.png


コード全文

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?