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?

FastAPI-Mail の使い方

Posted at

pip を使うので、仮想環境を使います。
Ubuntu で Python の仮想環境を使う

仮想環境になっていることの確認

$ which python
/home/uchida/myenv/bin/python

インストール

pip install fastapi_mail

プログラム

main.py
# ------------------------------------------------------------------
#	main.py
#
#						Oct/30/2025
# ------------------------------------------------------------------
from fastapi import FastAPI, HTTPException
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType
from pydantic import BaseModel, EmailStr
from typing import List
import os
from dotenv import load_dotenv

# ------------------------------------------------------------------
# .envファイルから環境変数を読み込み
load_dotenv()

app = FastAPI()

# hi-hoメール設定
conf = ConnectionConfig(
    MAIL_USERNAME=os.getenv("MAIL_USERNAME"),  # hi-hoのメールアドレス
    MAIL_PASSWORD=os.getenv("MAIL_PASSWORD"),  # hi-hoのメールパスワード
    MAIL_FROM=os.getenv("MAIL_FROM"),          # 送信元アドレス
    MAIL_PORT=587,                              # SMTP over TLS
    MAIL_SERVER=os.getenv("MAIL_SERVER"),
    MAIL_STARTTLS=True,
    MAIL_SSL_TLS=False,
    USE_CREDENTIALS=True,
    VALIDATE_CERTS=True
)

# ------------------------------------------------------------------
# リクエストボディのモデル
class EmailSchema(BaseModel):
    email: List[EmailStr]
    subject: str
    body: str

# ------------------------------------------------------------------
# シンプルなテキストメール送信
@app.post("/send-simple-email")
async def send_simple_email(email_data: EmailSchema):
    try:
        message = MessageSchema(
            subject=email_data.subject,
            recipients=email_data.email,
            body=email_data.body,
            subtype=MessageType.plain
        )
        
        fm = FastMail(conf)
        await fm.send_message(message)
        
        return {"message": "メールを送信しました"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"エラー: {str(e)}")


# ------------------------------------------------------------------
# 設定確認用エンドポイント(デバッグ用)
@app.get("/check-config")
async def check_config():
    return {
        "mail_server": conf.MAIL_SERVER,
        "mail_port": conf.MAIL_PORT,
        "mail_username": conf.MAIL_USERNAME,
        "mail_from": conf.MAIL_FROM,
        "credentials_set": bool(conf.MAIL_PASSWORD),
        "starttls": conf.MAIL_STARTTLS
    }

# ------------------------------------------------------------------
# ヘルスチェック
@app.get("/")
async def root():
    return {
        "status": "ok",
        "message": "FastAPI Mail Server (hi-ho対応)",
        "endpoints": [
            "/send-simple-email",
            "/check-config"
        ]
    }

# ------------------------------------------------------------------
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
# ------------------------------------------------------------------
.env
MAIL_USERNAME=hello@hi-ho.ne.jp
MAIL_PASSWORD=secretXXX
MAIL_FROM=hello@hi-ho.ne.jp
MAIL_SERVER=hi-ho.mose-mail.jp

サーバーの起動

uvicorn main:app --reload

テストスクリプト

curl -X POST "http://localhost:8000/send-simple-email" \
  -H "Content-Type: application/json" \
  -d '{
    "email": ["testuser@yahoo.co.jp"],
    "subject": "テストメール Oct/30/2025 PM 18:13",
    "body": "これはテストメールです。 PM 18:13"
  }'

参考ページ

Sending email with FastAPI-Mail

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?