Skip to content

Instantly share code, notes, and snippets.

@lorne-luo
Last active October 2, 2019 02:54
Show Gist options
  • Select an option

  • Save lorne-luo/15b60e217bbcdcb57363d4552a81b1a2 to your computer and use it in GitHub Desktop.

Select an option

Save lorne-luo/15b60e217bbcdcb57363d4552a81b1a2 to your computer and use it in GitHub Desktop.
reuse connection to send multiple emails in django
from django.core import mail
connection = mail.get_connection()
connection.open()
email1 = mail.EmailMessage(
'That’s your subject',
'That’s your message body',
'from@yourdjangoapp.com',
['to@yourbestuser1.com'],
connection=connection,
)
email1.send()
email2 = mail.EmailMessage(
'That’s your subject #2',
'That’s your message body #2',
'from@yourdjangoapp.com',
['to@yourbestuser2.com'],
)
email3 = mail.EmailMessage(
'That’s your subject #3',
'That’s your message body #3',
'from@yourdjangoapp.com',
['to@yourbestuser3.com'],
)
connection.send_messages([email2, email3])
connection.close()
message1 = ('That’s your subject #1',
'That’s your message body #1',
'from@yourdjangoapp.com',
['to@yourbestuser1.com', 'to@yourbestuser2.com'])
message2 = ('That’s your subject #2',
'That’s your message body #2',
'from@yourdjangoapp.com',
['to@yourbestuser2.com'])
message3 = ('That’s your subject #3',
'That’s your message body #3',
'from@yourdjangoapp.com',
['to@yourbestuser3.com'])
send_mass_mail((message1, message2, message3), fail_silently=False)
from django.core import mail
from django.test import TestCase
class EmailTest(TestCase):
def test_send_email(self):
mail.send_mail(
'That’s your subject', 'That’s your message body',
'from@yourdjangoapp.com', ['to@yourbestuser.com'],
fail_silently=False,
)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'That’s your subject')
self.assertEqual(mail.outbox[0].body, 'That’s your message body')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment