ChatGPTにメール送信プログラムを作ってもらった_02(SendGrid)

ChatGPTにメール送信プログラム、その2、SendGridの場合です。

指示文(プロンプト):

Pythonでメールを送信するプログラムを作成して提示してください。SendGrid を利用したいです。アカウントは取得済みです。

回答:

以下はPythonでSendGridを使用してメールを送信する例です。 SendGrid APIキーを取得してください。 SendGrid APIキーが必要です。


import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

def send_email(from_email, to_email, subject, body):
    message = Mail(
        from_email=from_email,
        to_emails=to_email,
        subject=subject,
        html_content=body)

    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)

# 実行例
send_email('from@example.com', 'to@example.com', 'テストメール', 'これはテストメールです。')
    
    

send_email関数を呼び出すことで、指定した送信元アドレス、受信先アドレス、件名、本文を含むメールを送信できます。SENDGRID_API_KEY環境変数をセットして、APIキーを設定してください。

結果:

成功しました。テスト用に個人のyahooメルアドにテストメールを飛ばしています。