Skip to content

Instantly share code, notes, and snippets.

@hdknr
Last active November 28, 2024 11:45
Show Gist options
  • Save hdknr/e0883d5d53e816dcfff37556c4c53c14 to your computer and use it in GitHub Desktop.
Save hdknr/e0883d5d53e816dcfff37556c4c53c14 to your computer and use it in GitHub Desktop.
Django Email

メール送信

Djangoでメールを送信する際に、都度サーバーを切り替える方法はいくつかあります。以下の手順で実装できます。

  1. メールサーバーの設定を動的に変更する: DjangoのEmailMessageクラスを使用して、メール送信時にサーバー設定を動的に変更できます。例えば、以下のようにconnectionパラメータを使用して異なるサーバーを指定します。

    from django.core.mail import EmailMessage, get_connection
    
    def send_email(subject, message, from_email, recipient_list, server_settings):
        connection = get_connection(
            host=server_settings['EMAIL_HOST'],
            port=server_settings['EMAIL_PORT'],
            username=server_settings['EMAIL_HOST_USER'],
            password=server_settings['EMAIL_HOST_PASSWORD'],
            use_tls=server_settings['EMAIL_USE_TLS'],
            use_ssl=server_settings['EMAIL_USE_SSL'],
        )
        email = EmailMessage(subject, message, from_email, recipient_list, connection=connection)
        email.send()
  2. サーバー設定のリストを用意する: 複数のサーバー設定をリストで管理し、メール送信時にランダムまたは順番に選択する方法です。

    import random
    
    servers = [
        {
            'EMAIL_HOST': 'smtp1.example.com',
            'EMAIL_PORT': 587,
            'EMAIL_HOST_USER': 'user1',
            'EMAIL_HOST_PASSWORD': 'password1',
            'EMAIL_USE_TLS': True,
            'EMAIL_USE_SSL': False,
        },
        {
            'EMAIL_HOST': 'smtp2.example.com',
            'EMAIL_PORT': 587,
            'EMAIL_HOST_USER': 'user2',
            'EMAIL_HOST_PASSWORD': 'password2',
            'EMAIL_USE_TLS': True,
            'EMAIL_USE_SSL': False,
        },
        # 他のサーバー設定を追加
    ]
    
    def send_email_with_random_server(subject, message, from_email, recipient_list):
        server_settings = random.choice(servers)
        send_email(subject, message, from_email, recipient_list, server_settings)
  3. サーバー設定を順番に使用する: itertools.cycleを使用して、サーバー設定を順番に使用する方法です。

    from itertools import cycle
    
    server_cycle = cycle(servers)
    
    def send_email_with_cycled_server(subject, message, from_email, recipient_list):
        server_settings = next(server_cycle)
        send_email(subject, message, from_email, recipient_list, server_settings)

これらの方法を使うことで、Djangoでメールを送信する際にサーバーを都度切り替えることができます。どの方法が最適かは、具体的な要件や環境に依存しますので、試してみてくださいね。😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment