本文整理汇总了Python中django.core.mail.get_connection方法的典型用法代码示例。如果您正苦于以下问题:Python mail.get_connection方法的具体用法?Python mail.get_connection怎么用?Python mail.get_connection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.mail
的用法示例。
在下文中一共展示了mail.get_connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: report
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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'))
示例2: send_mass_html_mail
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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
示例3: check_email_server_is_alive
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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
示例4: send_mass_html_mail
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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)
示例5: transform_sms_to_email_message
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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
示例6: send_mass_html_mail
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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)
示例7: send_campaign
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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'])
示例8: test_context_manager
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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",
},
)
示例9: test_backend_arg
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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)
示例10: test_message_cc_header
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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())
示例11: test_use_as_contextmanager
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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])
示例12: mass_mail_sending_view
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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")
示例13: send_digest_emails
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
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
示例14: bulk_email_view
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
def bulk_email_view(self, request, object_id):
season = get_object_or_404(Season, pk=object_id)
if not request.user.has_perm('tournament.bulk_email', season.league):
raise PermissionDenied
if request.method == 'POST':
form = forms.BulkEmailForm(season.seasonplayer_set.count(), request.POST)
if form.is_valid() and form.cleaned_data['confirm_send']:
season_players = season.seasonplayer_set.all()
email_addresses = {sp.player.email for sp in season_players if
sp.player.email != ''}
email_messages = []
for addr in email_addresses:
message = EmailMultiAlternatives(
form.cleaned_data['subject'],
form.cleaned_data['text_content'],
settings.DEFAULT_FROM_EMAIL,
[addr]
)
message.attach_alternative(form.cleaned_data['html_content'], 'text/html')
email_messages.append(message)
conn = mail.get_connection()
conn.open()
conn.send_messages(email_messages)
conn.close()
self.message_user(request, 'Emails sent to %d players.' % len(season_players),
messages.INFO)
return redirect('admin:tournament_season_changelist')
else:
form = forms.BulkEmailForm(season.seasonplayer_set.count())
context = {
'has_permission': True,
'opts': self.model._meta,
'site_url': '/',
'original': season,
'title': 'Bulk email',
'form': form
}
return render(request, 'tournament/admin/bulk_email.html', context)
示例15: connection
# 需要导入模块: from django.core import mail [as 别名]
# 或者: from django.core.mail import get_connection [as 别名]
def connection(self):
return get_connection(backend=self.email_backend, fail_silently=True)