Python django.core.mail.get_connection() Examples
The following are 30
code examples of django.core.mail.get_connection().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.core.mail
, or try the search function
.
Example #1
Source File: test_backend.py From postmarker with MIT License | 6 votes |
def test_context_manager(postmark_request): with mail.get_connection() as connection: send_with_connection(connection) assert postmark_request.call_args[1]["json"] == ( { "ReplyTo": None, "Subject": "Subject", "To": "receiver@example.com", "Bcc": None, "Headers": [], "Cc": None, "Attachments": [], "TextBody": "Body", "HtmlBody": None, "Tag": None, "Metadata": None, "TrackOpens": True, "From": "sender@example.com", }, )
Example #2
Source File: api.py From colossus with MIT License | 6 votes |
def send_campaign(campaign): campaign.status = CampaignStatus.DELIVERING campaign.save(update_fields=['status']) site = get_current_site(request=None) # get site based on SITE_ID if campaign.track_clicks: campaign.email.enable_click_tracking() if campaign.track_opens: campaign.email.enable_open_tracking() with get_connection() as connection: for subscriber in campaign.get_recipients(): if not subscriber.activities.filter(activity_type=ActivityTypes.SENT, email=campaign.email).exists(): sent = send_campaign_email_subscriber(campaign.email, subscriber, site, connection) if sent: subscriber.create_activity(ActivityTypes.SENT, email=campaign.email) subscriber.update_open_and_click_rate() subscriber.last_sent = timezone.now() subscriber.save(update_fields=['last_sent']) campaign.mailing_list.update_open_and_click_rate() campaign.status = CampaignStatus.SENT campaign.save(update_fields=['status'])
Example #3
Source File: admin_functions.py From Ouroboros with GNU General Public License v3.0 | 6 votes |
def send_mass_html_mail( datatuple, fail_silently=False, user=None, password=None, connection=None ): """ Given a datatuple of (subject, text_content, html_content, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. (from <a href="https://stackoverflow.com/a/10215091">this StackOverflow answer</a> """ connection = connection or get_connection( username=user, password=password, fail_silently=fail_silently ) messages = [] for subject, text, html, from_email, recipient in datatuple: message = EmailMultiAlternatives(subject, text, from_email, recipient) message.attach_alternative(html, "text/html") messages.append(message) return connection.send_messages(messages)
Example #4
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_backend_arg(self): """Test backend argument of mail.get_connection()""" self.assertIsInstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend) self.assertIsInstance( mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend ) self.assertIsInstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend) self.assertIsInstance( mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend ) with tempfile.TemporaryDirectory() as tmp_dir: self.assertIsInstance( mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend ) self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
Example #5
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def mass_mail_sending_view(request): m1 = mail.EmailMessage( 'First Test message', 'This is the first test email', 'from@example.com', ['first@example.com', 'second@example.com']) m2 = mail.EmailMessage( 'Second Test message', 'This is the second test email', 'from@example.com', ['second@example.com', 'third@example.com']) c = mail.get_connection() c.send_messages([m1, m2]) return HttpResponse("Mail sent")
Example #6
Source File: check-slaves.py From desec-stack with MIT License | 6 votes |
def report(self, outdated_slaves, output, timeouts): if not outdated_slaves and not timeouts: return subject = f'{timeouts and "CRITICAL ALERT" or "ALERT"} {len(outdated_slaves)} slaves out of sync' message = '' if timeouts: message += f'The following servers had timeouts:\n\n{timeouts}\n\n' if outdated_slaves: message += f'The following {len(outdated_slaves)} slaves are out of sync:\n' for outdated_slave in outdated_slaves: message += f'* {outdated_slave}\n' message += '\n' message += f'Current slave IPs: {self.servers}\n' message += '\n'.join(output) mail_admins(subject, message, connection=get_connection('django.core.mail.backends.smtp.EmailBackend'))
Example #7
Source File: checks.py From zing with GNU General Public License v3.0 | 6 votes |
def check_email_server_is_alive(app_configs=None, **kwargs): from django.conf import settings errors = [] if settings.ZING_SIGNUP_ENABLED or settings.ZING_CONTACT_EMAIL.strip(): from django.core.mail import get_connection connection = get_connection() try: connection.open() except Exception: errors.append( checks.Warning( _("Email server is not available."), hint=_( "Review your email settings and make sure your email " "server is working." ), id="pootle.W004", ) ) else: connection.close() return errors
Example #8
Source File: utils.py From pasportaservo with GNU Affero General Public License v3.0 | 6 votes |
def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None, connection=None): """ Given a datatuple of (subject, text_content, html_content, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. """ connection = connection or get_connection( username=user, password=password, fail_silently=fail_silently) messages = [] default_from = settings.DEFAULT_FROM_EMAIL for subject, text, html, from_email, recipients in datatuple: message = EmailMultiAlternatives( subject, text, default_from, recipients, headers={'Reply-To': 'Pasporta Servo <saluton@pasportaservo.org>'}) message.attach_alternative(html, 'text/html') messages.append(message) return connection.send_messages(messages) or 0
Example #9
Source File: bulk_email.py From open-humans with MIT License | 6 votes |
def send_mass_html_mail(datatuple, fail_silently=False, connection=None): """ Given a datatuple of (subject, text_content, html_content, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. """ connection = get_connection(fail_silently=fail_silently) messages = [] for subject, text, html, from_email, recipient in datatuple: message = EmailMultiAlternatives(subject, text, from_email, recipient) message.attach_alternative(html, "text/html") messages.append(message) return connection.send_messages(messages)
Example #10
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_use_as_contextmanager(self): """ The connection can be used as a contextmanager. """ opened = [False] closed = [False] conn = mail.get_connection(username='', password='') def open(): opened[0] = True conn.open = open def close(): closed[0] = True conn.close = close with conn as same_conn: self.assertTrue(opened[0]) self.assertIs(same_conn, conn) self.assertFalse(closed[0]) self.assertTrue(closed[0])
Example #11
Source File: mailtrap.py From django-smsish with MIT License | 6 votes |
def transform_sms_to_email_message(sms_message): backend = getattr(settings, "SMSISH_MAILTRAP_SMS_BACKEND_EMAIL_BACKEND", DEFAULT_SMS_OVER_EMAIL_BACKEND) conn = get_connection(backend=backend) email = EmailMessage( subject="SMS over Email", body=sms_message.body, from_email=emailify_phone_number(sms_message.from_email), to=[emailify_phone_number(r) for r in sms_message.to], bcc=[emailify_phone_number(r) for r in sms_message.bcc] if sms_message.bcc else None, connection=conn, attachments=None, headers=None, cc=[emailify_phone_number(r) for r in sms_message.cc] if sms_message.cc else None, reply_to=[emailify_phone_number(sms_message.reply_to) for r in sms_message.reply_to] if sms_message.reply_to else None, ) email.attach("metadata.txt", "Content-Length: {}".format(len(sms_message.body)), "text/plain") return email
Example #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_message_cc_header(self): """ Regression test for #7722 """ email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com']) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', '7bit'), ('Subject', 'Subject'), ('From', 'from@example.com'), ('To', 'to@example.com'), ('Cc', 'cc@example.com')}) self.assertIn('\nDate: ', message.as_string())
Example #13
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_custom_backend(self): """Test custom backend defined in this suite.""" conn = mail.get_connection('mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, 'test_outbox')) email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1)
Example #14
Source File: test_backend.py From postmarker with MIT License | 5 votes |
def test_silent_exception(self): with mail.get_connection(fail_silently=True) as connection: send_with_connection(connection)
Example #15
Source File: suspend_users.py From open-humans with MIT License | 5 votes |
def email_notification(self, users): subject = "Open Humans: Account suspension notification" messages = [] for user in users: body_text = self._body_text(user.username) message = EmailMultiAlternatives(subject, body_text, None, [user.email]) messages.append(message) connection = get_connection() connection.send_messages(messages)
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_connection_timeout_default(self): """The connection's timeout value is None by default.""" connection = mail.get_connection('django.core.mail.backends.smtp.EmailBackend') self.assertIsNone(connection.timeout)
Example #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_email_msg_uses_crlf(self): """#23063 -- RFC-compliant messages are sent over SMTP.""" send = SMTP.send try: smtp_messages = [] def mock_send(self, s): smtp_messages.append(s) return send(self, s) SMTP.send = mock_send email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) mail.get_connection().send_messages([email]) # Find the actual message msg = None for i, m in enumerate(smtp_messages): if m[:4] == 'data': msg = smtp_messages[i + 1] break self.assertTrue(msg) msg = msg.decode() # The message only contains CRLF and not combinations of CRLF, LF, and CR. msg = msg.replace('\r\n', '') self.assertNotIn('\r', msg) self.assertNotIn('\n', msg) finally: SMTP.send = send
Example #18
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo='bar') self.assertTrue(c.fail_silently)
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_send(self): email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "from@example.com") self.assertEqual(message.get_all("to"), ["to@example.com"])
Example #20
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_send_unicode(self): email = EmailMessage('Chère maman', 'Je t\'aime très fort', 'from@example.com', ['to@example.com']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], '=?utf-8?q?Ch=C3=A8re_maman?=') self.assertEqual(message.get_payload(decode=True).decode(), 'Je t\'aime très fort')
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_file_sessions(self): """Make sure opening a connection creates a new file""" msg = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), 'rb') as fp: message = message_from_binary_file(fp) self.assertEqual(message.get_content_type(), 'text/plain') self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'from@example.com') self.assertEqual(message.get('to'), 'to@example.com') connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) connection.close()
Example #22
Source File: test_utilities.py From edx-enterprise with GNU Affero General Public License v3.0 | 5 votes |
def test_send_email_notification_message( self, user, enrolled_in, enterprise_customer_name, expected_fields, ): """ Test that we can successfully render and send an email message. """ enrolled_in['start'] = datetime.datetime.strptime(enrolled_in['start'], '%Y-%m-%d') enterprise_customer = mock.MagicMock(spec=[], site=None) enterprise_customer.name = enterprise_customer_name if user is None: with raises(TypeError): utils.send_email_notification_message( user, enrolled_in, enterprise_customer ) else: conn = mail.get_connection() user_cls = user.pop('class') user = user_cls(**user) utils.send_email_notification_message( user, enrolled_in, enterprise_customer, email_connection=conn, ) assert len(mail.outbox) == 1 for field, val in expected_fields.items(): assert getattr(mail.outbox[0], field) == val assert mail.outbox[0].connection is conn
Example #23
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo='bar') self.assertTrue(c.fail_silently)
Example #24
Source File: admin.py From registration with MIT License | 5 votes |
def send(self, request, queryset): msgs = [] sent = 0 errors = 0 for reimb in queryset: try: reimb.send(request.user) msgs.append(emails.create_reimbursement_email(reimb, request)) sent += 1 except ValidationError as e: errors += 1 logging.error(e.message) if msgs: connection = mail.get_connection() connection.send_messages(msgs) if sent > 0 and errors > 0: self.message_user(request, ( "%s reimbursements sent, %s reimbursements not sent. Did you " "check that they were invited before and with money assigned?" % (sent, errors)), level=messages.WARNING) elif sent > 0: self.message_user(request, '%s reimbursement sent' % sent, level=messages.SUCCESS) else: self.message_user(request, 'Reimbursement couldn\'t be sent! Did you check ' 'that app was invited before and with money ' 'assigned?', level=messages.ERROR)
Example #25
Source File: expire_applications.py From registration with MIT License | 5 votes |
def handle(self, *args, **options): fourdaysago = timezone.now() - timedelta(days=4) self.stdout.write('Checking reminders...') reminders = models.Application.objects.filter( status_update_date__lte=fourdaysago, status=models.APP_INVITED) self.stdout.write('Checking reminders...%s found' % reminders.count()) self.stdout.write('Sending reminders...') msgs = [] for app in reminders: app.last_reminder() msgs.append(emails.create_lastreminder_email(app)) connection = mail.get_connection() connection.send_messages(msgs) self.stdout.write(self.style.SUCCESS( 'Sending reminders... Successfully sent %s reminders' % len(msgs))) onedayago = timezone.now() - timedelta(days=1) self.stdout.write('Checking expired...') expired = models.Application.objects.filter( status_update_date__lte=onedayago, status=models.APP_LAST_REMIDER) self.stdout.write('Checking expired...%s found' % expired.count()) self.stdout.write('Setting expired...') count = len([app.expire() for app in expired]) self.stdout.write(self.style.SUCCESS( 'Setting expired... Successfully expired %s applications' % count))
Example #26
Source File: emails.py From registration with MIT License | 5 votes |
def send_batch_emails(emails): connection = mail.get_connection() connection.send_messages(emails)
Example #27
Source File: models.py From PonyConf with Apache License 2.0 | 5 votes |
def send_notification(self, sender, dests, reply_to=None, message_id=None, reference=None, footer=None, subject=None): messages = [] for dest, dest_name, dest_email in dests: dest_type = ContentType.objects.get_for_model(dest) dest, _ = MessageAuthor.objects.get_or_create(author_type=dest_type, author_id=dest.pk) token = self.token + dest.token + hexdigest_sha256(settings.SECRET_KEY, self.token, dest.token)[:16] if reply_to: reply_to_name, reply_to_email = reply_to reply_to_list = ['%s <%s>' % (reply_to_name, reply_to_email.format(token=token))] else: reply_to_list = [] headers = dict() if message_id: headers.update({ 'Message-ID': message_id.format(id=self.token), }) if message_id and reference: headers.update({ 'References': message_id.format(id=reference), }) body = self.content if footer is not None: body += footer messages.append(EmailMessage( subject=subject or self.subject, body=body, from_email='%s <%s>' % sender, to=['%s <%s>' % (dest_name, dest_email)], reply_to=reply_to_list, headers=headers, )) connection = get_connection() connection.send_messages(messages)
Example #28
Source File: log.py From python2017 with MIT License | 5 votes |
def connection(self): return get_connection(backend=self.email_backend, fail_silently=True)
Example #29
Source File: digest.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def send_digest_emails(digest_frequency): """Send daily digests to users subscribed to digests with frequency digest_frequency. :return tuple containing number of emails successfully sent and number that failed to send """ if digest_frequency == DigestFrequency.never: raise ValueError(_('Cannot send digest emails for frequency "never"')) timestamp = timezone.now() subscribers = [ u.user for u in UserSettings.objects.filter(digest_frequency=digest_frequency.key).select_related('user') ] emails = [(u, create_digest_email(u, digest_frequency, timestamp)) for u in subscribers] succeeded = 0 skipped = 0 failed = 0 with get_connection(fail_silently=False): for user, email in emails: if email: try: email.send() DigestStatus.objects.update_or_create(user=user, defaults={ 'last_success': timestamp, 'last_attempt': timestamp }) logger.debug('Sent digest email to %s', user) succeeded += 1 except Exception as ex: logger.error('Error sending digest to %s', user, exc_info=ex) DigestStatus.objects.update_or_create(user=user, defaults={ 'last_attempt': timestamp }) failed += 1 else: logger.debug('User %s has no new updates for digest', user) skipped += 1 return succeeded, skipped, failed
Example #30
Source File: log.py From openhgsenti with Apache License 2.0 | 5 votes |
def connection(self): return get_connection(backend=self.email_backend, fail_silently=True)