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?

#0103(2025/04/12)AWS Lambda(SAM) + API Gateway で Gmail通知

Posted at

AWS Lambda + SAM + Docker + API Gateway で Gmail通知

この記事では、AWSを利用して、外部からのHTTPリクエストを受け取り、その内容をGmailで送信するシステムの構築方法を解説します。

📌 構成と役割

構成図:

[ローカルPC(curl)]
     ↓
[API Gateway]
     ↓
[AWS Lambda(Python)]
     ↓
[Gmail送信(SMTP)]

各技術の役割:

  • SAM(Serverless Application Model)

    • LambdaやAPI Gatewayの構築・管理を簡単に行うCLIツール
  • Lambda

    • サーバーレス関数を実行するAWSサービス
  • Docker

    • Lambdaと同じ環境をローカルで再現してテストできる
  • API Gateway

    • Lambda関数をHTTP経由で呼び出すための入り口
  • Gmail (SMTP)

    • メール送信の仕組み

📌 構築&デプロイ手順

① AWS CLI, SAM CLI インストール

brew install awscli aws-sam-cli

② AWS CLI 設定

aws configure

③ SAMでプロジェクト作成

sam init
  • Package type: Zip
  • Runtime: Python3.11
  • Template: Hello World Example

④ Lambdaコードとtemplate.yamlを修正

app.py

import json, smtplib
from email.mime.text import MIMEText
import os

def lambda_handler(event, context):
    body = json.loads(event.get("body", "{}"))
    to = body.get("to", "youraddress@gmail.com")
    message_body = body.get("body", "メッセージがありません")

    smtp_server = "smtp.gmail.com"
    smtp_port = 587
    sender_email = os.environ["GMAIL_USER"]
    sender_pass = os.environ["GMAIL_PASS"]

    msg = MIMEText(message_body)
    msg["Subject"] = "Lambdaからの通知"
    msg["From"] = sender_email
    msg["To"] = to

    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.login(sender_email, sender_pass)
        server.sendmail(sender_email, to, msg.as_string())
        server.quit()
        return {"statusCode":200,"body":json.dumps({"result":"送信成功!"}, ensure_ascii=False)}
    except Exception as e:
        return {"statusCode":500,"body":json.dumps({"error":str(e)})}

template.yaml

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.11
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: POST
      Environment:
        Variables:
          GMAIL_USER: youraddress@gmail.com
          GMAIL_PASS: xxxxxxx

⑤ Gmailアプリパスワード取得

  • Googleアカウント → 2段階認証有効化
  • 「アプリパスワード」を生成し、template.yamlに設定

⑥ ビルド&デプロイ

sam build
sam deploy --guided

⑦ API動作テスト

curl -X POST https://YOUR_API_URL/Prod/hello \
  -H "Content-Type: application/json" \
  -d '{"to":"test@example.com", "body":"テストメールです!"}'
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?