Here are the examples of the python api django.core.mail.send_mail taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
229 Examples
3
Source : models.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
class User(AbstractUser):
3
Source : sendtestemail.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def handle(self, *args, **kwargs):
subject = 'Test email from %s on %s' % (socket.gethostname(), timezone.now())
send_mail(
subject=subject,
message="If you\'re reading this, it was successful.",
from_email=None,
recipient_list=kwargs['email'],
)
if kwargs['managers']:
mail_managers(subject, "This email was sent to the site managers.")
if kwargs['admins']:
mail_admins(subject, "This email was sent to the site admins.")
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from ajithpmohan
with BSD 3-Clause "New" or "Revised" License
from ajithpmohan
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
@property
3
Source : get_job.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def sendThreadEmail(thread):
send_mail(
getSubject(thread, now),
strip_tags(thread.threadMessage),
from_email,
[thread.email],
html_message=thread.threadMessage,
fail_silently=False,
)
#
#
# Logging Status Updates
#
#
def logStatus(thread):
3
Source : test_rest_email_backend.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def test_rest_email_backend_celery_config(self, mocked_send):
with self.settings(
CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES=None,
EMAIL_BACKEND='djcelery_email.backends.CeleryEmailBackend',
CELERY_EMAIL_BACKEND='signals.apps.email_integrations.custom_backends.rest_email_endpoint.RestEmailBackend'): # noqa
django_send_mail(subject='test', message='Hello!', from_email='[email protected]',
recipient_list=['[email protected]'])
mocked_send.assert_called_once()
3
Source : views.py
with MIT License
from arcturus5340
with MIT License
from arcturus5340
def send_message(subject, html_message, user, email=None):
from_email = settings.EMAIL_HOST_USER
try:
mail.send_mail(
subject=subject,
message='',
html_message=html_message,
from_email=from_email,
recipient_list=[email or user.email],
)
except smtplib.SMTPException as err:
return err.strerror
class UserViewSet(viewsets.ModelViewSet):
3
Source : common_tools.py
with MIT License
from Arianxx
with MIT License
from Arianxx
def _send_mail(subject, template, recipient_list, kwargs):
context = dict(kwargs)
message = render_to_string(template, context=context)
from_email = getattr(settings, 'EMAIL_FROM')
fail_silently = False
if template.endswith('.html'):
msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list)
msg.content_subtype = 'html'
msg.send()
else:
send_mail(subject, message, from_email=from_email, fail_silently=fail_silently, recipient_list=recipient_list)
def send_mail_thread(subject, template, recipient, **kwargs):
3
Source : feedback.py
with GNU General Public License v3.0
from arrobalytics
with GNU General Public License v3.0
from arrobalytics
def form_valid(self, form):
form_data = form.cleaned_data
message = f'How to reproduce?: {form_data["reproduce"]}\n' + \
f'Expectation: {form_data["expectation"]}\n' + \
f'Device: {form_data["device"]}\n' + \
f'From user: {self.request.user.username}\n' + \
f'User email: {self.request.user.email}'
if DJANGO_LEDGER_FEEDBACK_EMAIL_LIST:
send_mail(
subject=f'DJL Bug Report',
from_email=DJANGO_LEDGER_FEEDBACK_FROM_EMAIL,
recipient_list=DJANGO_LEDGER_FEEDBACK_EMAIL_LIST,
fail_silently=True,
message=message)
return super().form_valid(form)
class RequestNewFeatureView(LoginRequiredMixIn,
3
Source : feedback.py
with GNU General Public License v3.0
from arrobalytics
with GNU General Public License v3.0
from arrobalytics
def form_valid(self, form):
form_data = form.cleaned_data
message = f'Description: {form_data["feature_description"]}\n' + \
f'Solution: {form_data["solution"]}\n' + \
f'Alternatives: {form_data["alternatives"]}\n' + \
f'From user: {self.request.user.username}\n' + \
f'User email: {self.request.user.email}'
if DJANGO_LEDGER_FEEDBACK_EMAIL_LIST:
send_mail(
subject=f'DJL New Feature Request',
from_email=DJANGO_LEDGER_FEEDBACK_FROM_EMAIL,
recipient_list=DJANGO_LEDGER_FEEDBACK_EMAIL_LIST,
fail_silently=True,
message=message)
return super().form_valid(form)
3
Source : signals.py
with MIT License
from betagouv
with MIT License
from betagouv
def send_mail_aidant__organisations_changed(instance: Aidant, diff: dict, **_):
context = {"aidant": instance, **diff}
text_message = loader.render_to_string(
"signals/aidant__organisations_changed.txt", context
)
html_message = loader.render_to_string(
"signals/aidant__organisations_changed.html", context
)
send_mail(
from_email=settings.AIDANTS__ORGANISATIONS_CHANGED_EMAIL_FROM,
recipient_list=[instance.email],
subject=settings.AIDANTS__ORGANISATIONS_CHANGED_EMAIL_SUBJECT,
message=text_message,
html_message=html_message,
)
@receiver(post_migrate)
3
Source : tasks.py
with MIT License
from briancaffey
with MIT License
from briancaffey
def send_test_email_task(self):
send_mail(
"Email subject",
"Email message.",
"[email protected]",
["[email protected]"],
fail_silently=False,
)
@app.task(bind=True, base=BaseTask)
3
Source : models.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
class User(AbstractUser):
3
Source : helpers.py
with MIT License
from Code-Institute-Community
with MIT License
from Code-Institute-Community
def send_partnership_request_email(data):
try:
settings = PartnershipRequestEmailSiteSettings.objects.first()
if settings:
send_mail(
subject=settings.subject,
message=create_email_template(data),
html_message=create_html_email_template(data),
from_email=settings.from_email,
recipient_list=json.loads(settings.to_emails),
fail_silently=False,
)
except json.decoder.JSONDecodeError:
logger.exception("Error parsing to_emails. Wrong format.")
except SMTPException:
logger.exception("There was an issue sending the email.")
3
Source : workflows.py
with BSD 3-Clause "New" or "Revised" License
from codingjoe
with BSD 3-Clause "New" or "Revised" License
from codingjoe
def send_tracking_code(self, task):
send_mail(
subject="Your tracking code",
message=self.tracking_code,
from_email=None,
recipient_list=[self.email],
)
def end(self, task):
3
Source : views.py
with MIT License
from datatau-net
with MIT License
from datatau-net
def send_confirmation_email(user):
confirmation_email_text = f"""Hi {user.username},\n\nHere is the link to activate your DataTau account:\n\nhttps://datatau.net/accounts/login/activate/{user.id}/{user.api_key}\n\nWelcome to the coolest Data Science community!\n\nBR,\n\nDavid & Pedro"""
send_mail(
subject=f'Confirmation email from datatau.net',
message=confirmation_email_text,
from_email='[email protected]',
recipient_list=[user.email],
fail_silently=False
)
def check_signup(request):
3
Source : views.py
with MIT License
from datatau-net
with MIT License
from datatau-net
def send_confirmation_email(user):
confirmation_email_text = f"""Hi {user.username},\n\nHere is the link to activate your DataTau account:\n\nhttps://datatau.net/accounts/login/activate/{user.id}/{user.api_key}\n\nWelcome to the coolest Data Science community!\n\nBR,\n\nDavid & Pedro"""
send_mail(
subject=f'Confirmation email from datatau.net',
message=confirmation_email_text,
from_email='[email protected]',
recipient_list=[user.email],
fail_silently=False
)
def update_profile(request, user_id):
3
Source : mail.py
with MIT License
from dtcooper
with MIT License
from dtcooper
def send_mail(recipient, subject, body, request=None):
from_email = f'"{config.STATION_NAME} Admin" < no-reply@{settings.DOMAIN_NAME}>'
try:
django_send_mail(subject=subject, message=body, from_email=from_email, recipient_list=[recipient])
except Exception as e:
logger.exception(f'An error occurred while sending mail "{subject}" to {recipient}: {e}')
if request:
messages.error(
request,
"An error occurred while sending email. Message not sent. Try again.",
)
return False
return True
3
Source : tasks.py
with GNU General Public License v3.0
from dubs3c
with GNU General Public License v3.0
from dubs3c
def send_activation_code(self, user_id: int):
"""Task that sends an activation code to the users email"""
try:
token = ActivationTokens.objects.get(user__id=user_id)
msg_html = render_to_string(
"registration/activation.html", {"code": token.code}
)
send_mail(
"Bookie - Please activate your account",
"message",
"[email protected]",
[f"{token.user.email}"],
fail_silently=False,
html_message=msg_html,
)
except Exception as exc:
raise self.retry(exc=exc)
3
Source : views.py
with GNU Affero General Public License v3.0
from dzNLPCommunity
with GNU Affero General Public License v3.0
from dzNLPCommunity
def contact_view(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['Sujet']
from_email = form.cleaned_data['Votre_email']
message = form.cleaned_data['Votre_message']
try:
send_mail(subject, message, from_email, ['[email protected]'])
except BadHeaderError:
messages.error(request, 'Une erreur s\'est produite veuillez réessayer ultérieurement!')
messages.success(request, 'Votre email a été envoyé avec succès!')
return render(request, "contact.html", {'form': form})
def contact_success_view(request):
3
Source : tasks.py
with MIT License
from fengjinqi
with MIT License
from fengjinqi
def error_email(title=None, body=None, email=None):
email_title = title
email_body = body
send_mail(email_title, email_body, settings.EMAIL_NAME, [email])
conf = ConfigParser()
3
Source : email_handler.py
with GNU General Public License v3.0
from foo290
with GNU General Public License v3.0
from foo290
def __send_email(self, msg, useremail):
subject = self.settings.get('subject')
send_mail(
subject, strip_tags(msg),
from_email=self.settings.get('from_alias'),
recipient_list=[useremail], html_message=msg
)
# Public :
def send_verification_link(self, request, form):
3
Source : tasks.py
with Apache License 2.0
from genomicsengland
with Apache License 2.0
from genomicsengland
def send_email(email, subject, text, html=None):
"Send emails via Celery task"
subject = subject.strip() # remove new line characters
send_mail(
subject,
text,
settings.DEFAULT_FROM_EMAIL,
recipient_list=[email],
html_message=html,
)
@app.task
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_plaintext_send_mail(self):
"""
Test send_mail without the html_message
regression test for adding html_message parameter to send_mail()
"""
send_mail('Subject', 'Content', '[email protected]', ['[email protected]'])
message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject')
self.assertEqual(message.get_all('to'), ['[email protected]'])
self.assertFalse(message.is_multipart())
self.assertEqual(message.get_payload(), 'Content')
self.assertEqual(message.get_content_type(), 'text/plain')
def test_html_send_mail(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_html_send_mail(self):
"""Test html_message argument to send_mail"""
send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], html_message='HTML Content')
message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject')
self.assertEqual(message.get_all('to'), ['[email protected]'])
self.assertTrue(message.is_multipart())
self.assertEqual(len(message.get_payload()), 2)
self.assertEqual(message.get_payload(0).get_payload(), 'Content')
self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content')
self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
@override_settings(MANAGERS=[('nobody', '[email protected]')])
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_recipient_without_domain(self):
"""
Regression test for #15042
"""
self.assertTrue(send_mail("Subject", "Content", "tester", ["django"]))
message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject')
self.assertEqual(message.get('from'), "tester")
self.assertEqual(message.get('to'), "django")
def test_lazy_addresses(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_validate_multiline_headers(self):
# Ticket #18861 - Validate emails when using the locmem backend
with self.assertRaises(BadHeaderError):
send_mail('Subject\nMultiline', 'Content', '[email protected]', ['[email protected]'])
class FileBackendTests(BaseEmailBackendTests, SimpleTestCase):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_console_stream_kwarg(self):
"""
The console backend can be pointed at an arbitrary stream.
"""
s = StringIO()
connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s)
send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection)
message = force_bytes(s.getvalue().split('\n' + ('-' * 79) + '\n')[0])
self.assertMessageHasHeaders(message, {
('MIME-Version', '1.0'),
('Content-Type', 'text/plain; charset="utf-8"'),
('Content-Transfer-Encoding', '7bit'),
('Subject', 'Subject'),
('From', '[email protected]'),
('To', '[email protected]')})
self.assertIn(b'\nDate: ', message)
class FakeSMTPChannel(smtpd.SMTPChannel):
3
Source : test_fixtures.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_mail_message_uses_mocked_DNS_NAME(mailoutbox):
mail.send_mail("subject", "body", "[email protected]", ["[email protected]"])
m = mailoutbox[0]
message = m.message()
assert message["Message-ID"].endswith("@fake-tests.example.com>")
def test_mail_message_uses_django_mail_dnsname_fixture(django_testdir):
3
Source : models.py
with MIT License
from hvitis
with MIT License
from hvitis
def email_user(self, subject, message, from_email=None, **kwargs):
'''
Sends an email to this User.
'''
send_mail(subject, message, from_email, [self.email], **kwargs)
def first_login(self):
3
Source : test_fixtures_mail.py
with BSD 3-Clause "New" or "Revised" License
from idlesign
with BSD 3-Clause "New" or "Revised" License
from idlesign
def test_mail_outbox(mail_outbox):
send_mail(
'Subject here', 'Here is the message.',
'[email protected]', ['[email protected]'],
fail_silently=False,
)
assert len(mail_outbox) == 1
assert mail_outbox[0].subject == 'Subject here'
3
Source : models.py
with GNU General Public License v3.0
from Ilhasoft
with GNU General Public License v3.0
from Ilhasoft
def send_welcome_email(self):
if not settings.SEND_EMAILS:
return False # pragma: no cover
context = {"name": self.name, "base_url": settings.BASE_URL}
send_mail(
_("Welcome to Bothub"),
render_to_string("authentication/emails/welcome.txt", context),
None,
[self.email],
html_message=render_to_string(
"authentication/emails/welcome.html", context
),
)
def make_password_reset_token(self):
3
Source : models.py
with GNU General Public License v3.0
from Ilhasoft
with GNU General Public License v3.0
from Ilhasoft
def send_reset_password_email(self):
if not settings.SEND_EMAILS:
return False # pragma: no cover
token = self.make_password_reset_token()
reset_url = "{}reset-password/{}/{}/".format(
settings.BOTHUB_WEBAPP_BASE_URL, self.nickname, token
)
context = {"reset_url": reset_url, "base_url": settings.BASE_URL}
send_mail(
_("Reset your bothub password"),
render_to_string("authentication/emails/reset_password.txt", context),
None,
[self.email],
html_message=render_to_string(
"authentication/emails/reset_password.html", context
),
)
def check_password_reset_token(self, token):
3
Source : models.py
with MIT License
from iyanuashiri
with MIT License
from iyanuashiri
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Send an email to this user
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
return True
3
Source : operation_task.py
with Apache License 2.0
from JoyMobileDevelopmentTeam
with Apache License 2.0
from JoyMobileDevelopmentTeam
def send_warn_mail(task_name, receiver, report_id):
tips = task_name + ':监控到接口发生异常!查看报告地址:http://qa.15166.com/api/get_report/?id=' + str(report_id)
try:
email_title = "Joy_QA_Platform 定时任务监控接口"
email_body = tips
# 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list
send_status = send_mail(email_title, email_body, EMAIL_FROM, [receiver])
except Exception as e:
print(e)
def task2Dict(task):
3
Source : docusign.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def send_service_instructions_email(user: JustfixUser) -> None:
email = react_render_email(
SITE_CHOICES.JUSTFIX,
user.locale,
SERVICE_INSTRUCTIONS_URL,
is_html_email=True,
user=user,
)
send_mail(
subject=email.subject,
from_email=settings.COURT_DOCUMENTS_EMAIL,
recipient_list=[user.email],
message=email.body,
html_message=email.html_body,
)
def update_envelope_status(de: DocusignEnvelope, event: str) -> None:
3
Source : test_friendly_email_console_backend.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def test_no_extra_info(backend):
send_mail(**BASE_SEND_MAIL_KWARGS)
snapshot = backend.snapshot("no_extra_info.txt")
assert snapshot.expected == snapshot.actual
def test_html_alternative(backend):
3
Source : test_friendly_email_console_backend.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def test_html_alternative(backend):
send_mail(**BASE_SEND_MAIL_KWARGS, html_message=" < p>hi < /p>")
snapshot = backend.snapshot("html_alternative.txt")
assert snapshot.expected == snapshot.actual
def test_attachments(backend):
3
Source : email_dhcr.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def send_email_to_dhcr(subject: str, body: str):
send_mail(
subject,
body,
settings.DHCR_EMAIL_SENDER_ADDRESS,
settings.DHCR_EMAIL_RECIPIENT_ADDRESSES,
fail_silently=False,
)
3
Source : models.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
def get_profile(self):
3
Source : moderation.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def email(self, comment, content_object, request):
"""
Send email notification of a new comment to site staff when email
notifications have been requested.
"""
if not self.email_notification:
return
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
t = loader.get_template('comments/comment_notification_email.txt')
c = Context({ 'comment': comment,
'content_object': content_object })
subject = '[%s] New comment posted on "%s"' % (get_current_site(request).name,
content_object)
message = t.render(c)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
class Moderator(object):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_recipient_without_domain(self):
"""
Regression test for #15042
"""
self.assertTrue(send_mail("Subject", "Content", "tester", ["django"]))
message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject')
self.assertEqual(message.get('from'), "tester")
self.assertEqual(message.get('to'), "django")
def test_close_connection(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_console_stream_kwarg(self):
"""
Test that the console backend can be pointed at an arbitrary stream.
"""
s = StringIO()
connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s)
send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection)
message = force_bytes(s.getvalue().split('\n' + ('-' * 79) + '\n')[0])
self.assertMessageHasHeaders(message, set((
('MIME-Version', '1.0'),
('Content-Type', 'text/plain; charset="utf-8"'),
('Content-Transfer-Encoding', '7bit'),
('Subject', 'Subject'),
('From', '[email protected]'),
('To', '[email protected]'))))
self.assertIn(b'\nDate: ', message)
class FakeSMTPServer(smtpd.SMTPServer, threading.Thread):
3
Source : tasks.py
with MIT License
from mdcg
with MIT License
from mdcg
def send_confirmation_email(token, id, email):
logger.info("Creating the task..")
subject = "Obrigado por se cadastrar!"
from_email = settings.EMAIL_HOST_USER
message = (
f"http://localhost:8000/confirm/?confirmation_key={token}&id={id}"
)
to = email
send_mail(
subject,
message,
from_email,
[to],
fail_silently=False,
)
logger.info("Finishing task..")
3
Source : mailing.py
with GNU General Public License v3.0
from Mercado-Social-de-Madrid
with GNU General Public License v3.0
from Mercado-Social-de-Madrid
def send_template_email(title, destination, template_name, template_params):
msg_plain = render_to_string('email/%s.txt' % template_name, template_params)
msg_html = render_to_string('email/%s.html' % template_name, template_params)
send_mail(
title,
msg_plain,
settings.EMAIL_SEND_FROM,
[destination],
html_message=msg_html,
)
3
Source : views.py
with GNU General Public License v2.0
from midianinja
with GNU General Public License v2.0
from midianinja
def envia_email_confirmacao(self, user):
host = os.environ['BACKEND_HOST']
link = 'http://{HOST}/api/account/users/confirm/{ID}/{TOKEN}'
link = link.format(HOST=host, ID=user.id, TOKEN=Token.objects.get_or_create(user=user)[0].pk)
msg = 'Clique em {LINK} para confirmar seu email'.format(LINK=link)
return send_mail(
'Confirmação de email',
msg,
'[email protected]',
[user.email],
fail_silently=False,
)
@csrf_exempt
3
Source : views.py
with GNU General Public License v2.0
from midianinja
with GNU General Public License v2.0
from midianinja
def email_verification(request, user_id, token):
user = User.objects.get(id=user_id)
if user.is_active is False and token == Token.objects.get(user=user).key:
user.is_active = True
user.save()
send_mail(
'Confirmação de email',
'Seu email {EMAIL} foi verificado com sucesso'.format(EMAIL=user.email),
'[email protected]',
[user.email],
fail_silently=False,
)
def list_skills(request):
3
Source : tasks.py
with Apache License 2.0
from objectsyndicate
with Apache License 2.0
from objectsyndicate
def send_email(self, subject, body, to, user):
settings = AccountSettings.objects.get(user=user)
settings.email_daily = settings.email_daily - 1
settings.save()
notice = Notice()
notice.taskid = self.request.id
notice.owner = User.objects.get(id=user)
notice.type = "E"
notice.save()
mail = send_mail(
subject,
body + " if you would like to unsubscribe from notifications modify your Crop🌱Watch settings ID:" + str(
notice.id),
DEFAULT_FROM_EMAIL,
[to],
fail_silently=False,
)
return mail
3
Source : tasks.py
with GNU General Public License v3.0
from observatorycontrolsystem
with GNU General Public License v3.0
from observatorycontrolsystem
def send_mail(*args, **kwargs):
# Add logging for emails - args[0] is subject and args[3] is recipients
usernames = set()
for email_address in args[3]:
usernames = usernames.union(
set(User.objects.filter(email=email_address).values_list('username', flat=True))
)
logger.info(f"Sending email to {','.join(usernames)} with subject {args[0]}")
django_send_mail(*args, **kwargs)
@dramatiq.actor()
3
Source : verify_code.py
with GNU Lesser General Public License v3.0
from open-cmdb
with GNU Lesser General Public License v3.0
from open-cmdb
def send_verifycode(self, to):
code = self.generation_verifycode()
try:
send_mail("CMDB 重置密码",
"Hi,您的验证码为:\n\t{}".format(code),
settings.SEND_EMAIL,
[to],
fail_silently=False)
return code
except Exception as exc:
raise Exception("Email send fail!")
3
Source : tasks.py
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
def order_created(order_id):
"""
Task to send an e-mail notification when an order is
successfully created.
"""
order = Order.objects.get(id=order_id)
subject = 'Order nr. {}'.format(order.id)
message = 'Dear {},\n\nYou have successfully placed an order.\
Your order id is {}.'.format(order.first_name,
order.id)
mail_sent = send_mail(subject,
message,
'[email protected]',
[order.email])
return mail_sent
See More Examples