Python django.core.mail.EmailMessage() Examples

The following are 30 code examples of django.core.mail.EmailMessage(). 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: email.py    From BikeMaps with MIT License 7 votes vote down vote up
def sender(request, subject, template_name, context, to):
    site = get_current_site(request)
    context.update({'site_name': site.name,
                    'domain': site.domain,
                    'protocol': 'https' if request.is_secure() else 'http'})
    message = render_to_string(template_name, context)
    from_email = "%(site_name)s <%(name)s@%(domain)s>" % {'name': "noreply",
                                                          'domain': site.domain,
                                                          'site_name': site.name}

    if len(to) > 1:
        kwargs = {'bcc': to, }
    else:
        kwargs = {'to': to, }

    email = EmailMessage(subject, message, from_email, **kwargs)

    try:
        email.send()
    except SMTPException as err:
        logger.error(err) 
Example #2
Source File: test_mail.py    From django-sendgrid-v5 with MIT License 6 votes vote down vote up
def test_asm(self):
        msg = EmailMessage(
            subject="Hello, World!",
            body="Hello, World!",
            from_email="Sam Smith <sam.smith@example.com>",
            to=["John Doe <john.doe@example.com>", "jane.doe@example.com"],
        )
        msg.asm = {"group_id": 1}
        result = self.backend._build_sg_mail(msg)

        self.assertIn("asm", result)
        self.assertIn("group_id", result["asm"])

        del msg.asm["group_id"]
        with self.assertRaises(KeyError):
            self.backend._build_sg_mail(msg)

        msg.asm = {"group_id": 1, "groups_to_display": [2, 3, 4], "bad_key": None}
        result = self.backend._build_sg_mail(msg)

        self.assertIn("asm", result)
        self.assertIn("group_id", result["asm"])
        self.assertIn("groups_to_display", result["asm"]) 
Example #3
Source File: payments.py    From wagtailinvoices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_receipts(invoice, email, amount):
    name = invoice.client_full_name
    id = invoice.id

    # Administrator successful payment receipt
    admin_receipt_message = render_to_string(
        'emails/admin_receipt.txt', {
            'email': email,
            'name': name,
            'amount': amount,
            'id': id,
        })
    admin_receipt = EmailMessage(
        name +
        " has successfully paid",
        admin_receipt_message,
        email,
        [email])
    admin_receipt.content_subtype = 'html'
    admin_receipt.send() 
Example #4
Source File: functions.py    From openstax-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
def send_redirect_report(bad_redirects):
    msg = 'The Openstax Redirect Report has been run'
    msg += '\n\nShort Code,Redirect URL'
    msg += '\n' + str(bad_redirects)

    subject = 'OpenStax Redirect Report'
    from_address = 'noreply@openstax.org'
    to_address = ['cmsupport@openstax.org', ]

    try:
        email = EmailMessage(subject,
                             msg,
                             from_address,
                             to_address)
        email.send()

    except Exception as e:
        logger.error("EMAIL FAILED TO SEND: subject:{}".format(subject)) 
Example #5
Source File: views.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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: action_item_spam.py    From osler with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
		providerEmails = []
		#all action items that are past due and incomplete
		actionItemList = models.ActionItem.objects.filter(due_date__lte=django.utils.timezone.now().date()).filter(completion_date=None)
		for actionItem in actionItemList:
			try:
				for coordinator in actionItem.patient.case_managers.all():
					email = coordinator.associated_user.email
					if email not in providerEmails:
						providerEmails = providerEmails + [email]
			except AttributeError:
				pass
		message = '''Hello Case Manager! You have an action item due. Please do it otherwise you will
		 continue to be spammed. Thanks! If you are recieving this message but you really don't have
		 an action item due, please contact your current Tech Tsar to relieve you of your misery.'''
		email = EmailMessage('SNHC: Action Item Due', message, to=providerEmails)
		email.send() 
Example #7
Source File: notify_changed_employments.py    From timed-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        email = options["email"]
        last_days = options["last_days"]

        # today is excluded
        end = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        start = end - timedelta(days=last_days)

        employments = Employment.objects.filter(updated__range=[start, end])
        if employments.exists():
            from_email = settings.DEFAULT_FROM_EMAIL
            subject = "[Timed] Employments changed in last {0} days".format(last_days)
            body = template.render({"employments": employments})
            message = EmailMessage(
                subject=subject,
                body=body,
                from_email=from_email,
                to=[email],
                headers=settings.EMAIL_EXTRA_HEADERS,
            )
            message.send() 
Example #8
Source File: about.py    From BikeMaps with MIT License 6 votes vote down vote up
def contact(request):
	emailForm = EmailForm(request.POST)

	if emailForm.is_valid():
		subject = '[BikeMaps] '+ emailForm.cleaned_data['subject']
		message = emailForm.cleaned_data['message']
		sender = emailForm.cleaned_data['sender']
		cc_myself = emailForm.cleaned_data['cc_myself']

		recipients = ['admin@bikemaps.org','tech-support@bikemaps.org']
		cc = [sender] if cc_myself else []

		email = EmailMessage(subject, message, 'admin@bikemaps.org', recipients, headers = {'Reply-To': sender}, cc = cc)

		try:
			email.send()
			messages.success(request, '<strong>' + _('Thank you!') + '</strong><br>' + _('We\'ll do our best to get back to you soon.'))
			emailForm = EmailForm() # Clear the form
		except BadHeaderError:
			messages.error(request, '<strong>'+ _('Invalid Header.') + '</strong>' + _('Illegal characters found.'))

	return render(request, 'mapApp/about.html', {"emailForm": emailForm}) 
Example #9
Source File: tests.py    From cornerwise with MIT License 6 votes vote down vote up
def test_send_comment(self):
        data = {
            "send_to": "cornerwise",
            "subject": "Hello",
            "comment": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        }
        response = self.client.post(reverse("contact-us"), data)

        self.assertEqual(response.status_code, 200)

        comment = models.UserComment.objects.order_by("-created")[0]
        self.assertEqual(comment.subject, data["subject"])
        self.assertEqual(comment.comment, data["comment"])

        self.assertEqual(len(mail.outbox), 1)
        message: mail.EmailMessage = mail.outbox[0]

        self.assertIn(self.admin.email, message.recipients())

        html = message.substitutions["-message_html-"]
        self.assertIn("Hello", html) 
Example #10
Source File: tasks.py    From hypha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_mail_task(**kwargs):
    response = {'status': '', 'id': None}
    email = EmailMessage(**kwargs)
    try:
        email.send()
    except Exception as e:
        response['status'] = 'Error: ' + str(e)
    else:
        try:
            return {
                'status': email.anymail_status.status.pop(),
                'id': email.anymail_status.message_id,
            }
        except AttributeError:
            response['status'] = 'sent'

    return response 
Example #11
Source File: amnotify.py    From modoboa-amavis with MIT License 6 votes vote down vote up
def _build_message(self, rcpt, total, reqs):
        """Build new EmailMessage instance."""
        if self.options["verbose"]:
            print("Sending notification to %s" % rcpt)
        context = {
            "total": total,
            "requests": reqs,
            "baseurl": self.baseurl,
            "listingurl": self.listingurl
        }
        content = render_to_string(
            "modoboa_amavis/notifications/pending_requests.html",
            context
        )
        msg = mail.EmailMessage(
            _("[modoboa] Pending release requests"),
            content,
            self.sender,
            [rcpt]
        )
        return msg 
Example #12
Source File: utils.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def send_email_messages(self, recipient, messages, site=None):  # pylint:disable=arguments-differ
        """
        Plain email sending to the specified recipient
        """
        from_email = settings.OSCAR_FROM_EMAIL
        if site:
            from_email = site.siteconfiguration.get_from_email()

        # Determine whether we are sending a HTML version too
        if messages['html']:
            email = EmailMultiAlternatives(messages['subject'],
                                           messages['body'],
                                           from_email=from_email,
                                           to=[recipient])
            email.attach_alternative(messages['html'], "text/html")
        else:
            email = EmailMessage(messages['subject'],
                                 messages['body'],
                                 from_email=from_email,
                                 to=[recipient])
        self.logger.info("Sending email to %s", recipient)
        email.send()

        return email 
Example #13
Source File: signals.py    From django-simplestore with MIT License 6 votes vote down vote up
def send_order_email_confirmation(sender, instance, **kwargs):
    """
    Send email to customer with order details.
    """
    order = instance
    message = get_template("emails/order_conf.html").render(Context({
        'order': order.get_serialized_data()
    }))
    mail = EmailMessage(
        subject="Order confirmation",
        body=message,
        from_email=EMAIL_ADMIN,
        to=[order.email],
        reply_to=[EMAIL_ADMIN],
    )
    mail.content_subtype = "html"
    return mail.send() 
Example #14
Source File: test_backend.py    From postmarker with MIT License 5 votes vote down vote up
def send_with_connection(connection):
    mail.EmailMessage("Subject", "Body", "sender@example.com", ["receiver@example.com"], connection=connection).send() 
Example #15
Source File: test_backend.py    From postmarker with MIT License 5 votes vote down vote up
def test_reply_to_cc_bcc(postmark_request, kwarg, key):
    message = mail.EmailMessage(
        "Subject",
        "Body",
        "sender@example.com",
        ["receiver@example.com"],
        **{kwarg: ["r1@example.com", "r2@example.com"]}
    )
    message.send()
    assert postmark_request.call_args[1]["json"][0][key] == "r1@example.com, r2@example.com" 
Example #16
Source File: test_mail.py    From sendgrid-django with MIT License 5 votes vote down vote up
def test_build_sg_email_w_extra_headers(self):
        msg = EmailMessage()
        msg.extra_headers = {'EXTRA_HEADER': 'VALUE'}
        with self.settings(SENDGRID_API_KEY='test_key'):
            mail = SendGridBackend()._build_sg_mail(msg)
            self.assertEqual(
                mail,
                {'content': [{'type': 'text/plain', 'value': ''}],
                 'from': {'email': 'webmaster@localhost'},
                 'headers': {'EXTRA_HEADER': 'VALUE'},
                 'personalizations': [{'subject': ''}],
                 'subject': ''}
            ) 
Example #17
Source File: tasks.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_news_mails(first_language, append_english, subject, text, text_en, unsubsribe_url):
    prev_language = translation.get_language()

    count = 0
    for person in Person.objects.all():
        # build mail text
        mail_text = ""
        tmp_unsubscribe_url = unsubsribe_url + str(person.token)

        if append_english:
            mail_text += render_to_string("news/mail/english.txt")

        mail_text += _mail_text_language(first_language, text, tmp_unsubscribe_url)

        if append_english:
            mail_text += _mail_text_language("en", text_en, tmp_unsubscribe_url)

        mail_text = mail_text.lstrip().rstrip()

        tracking_header = new_tracking_news(person)

        # send mail
        try:
            mail = EmailMessage(subject,
                                mail_text,
                                settings.EMAIL_SENDER_ADDRESS,
                                [person.email, ],
                                headers=tracking_header)
            mail.send(fail_silently=False)
        except smtplib.SMTPRecipientsRefused:
            pass

        count += 1

        # wait a bit after a batch of mails
        if count >= settings.MAIL_BATCH_SIZE:
            count = 0
            time.sleep(settings.MAIL_BATCH_GAP)

    translation.activate(prev_language) 
Example #18
Source File: models.py    From wagtail-torchbox with MIT License 5 votes vote down vote up
def send_email_response(self, to_address):
        email_message = EmailMessage(
            subject=self.email_subject,
            body=self.email_body,
            from_email=self.email_from_address,
            to=[to_address],
        )
        email_message.attach(
            self.email_attachment.file.name.split('/')[-1],
            self.email_attachment.file.read()
        )
        email_message.send() 
Example #19
Source File: test_mail.py    From sendgrid-django with MIT License 5 votes vote down vote up
def test_build_sg_email_w_substitutions(self):
        msg = EmailMessage()
        msg.substitutions = {}
        with self.settings(SENDGRID_API_KEY='test_key'):
            mail = SendGridBackend()._build_sg_mail(msg)
            self.assertEqual(
                mail,
                {'content': [{'type': 'text/plain', 'value': ''}],
                 'from': {'email': 'webmaster@localhost'},
                 'personalizations': [{'subject': ''}],
                 'subject': ''}
            ) 
Example #20
Source File: views.py    From texta with GNU General Public License v3.0 5 votes vote down vote up
def _send_confirmation_email(user, email):
    if (REQUIRE_EMAIL_CONFIRMATION):
        token = _generate_random_token()
        email = EmailMessage('Email Confirmation',
                             'Please confirm your email by clicking this link:' + URL_PREFIX + '/confirm/' + token,
                             to=[email])

        try:
            user.profile
        except:
            Profile.objects.create(user=user).save()

        user.profile.email_confirmation_token = token
        user.save()
        email.send() 
Example #21
Source File: classroom.py    From elearning with MIT License 5 votes vote down vote up
def contact_us_view(request):
    form_class = ContactForm

    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = request.POST.get('contact_name', '')
            contact_email = request.POST.get('contact_email', '')
            form_content = request.POST.get('form_content', '')
            template = loader.get_template('students/contact/contact_template.txt')
            context = {
                'contact_name': contact_name,
                'contact_email': contact_email,
                'form_content': form_content
            }
            content = template.render(context)

            email = EmailMessage(
                _('Nouveau message de myealearning'),
                content,
                _('myealearning'),
                [config('ADMIN_EMAIL')],
                headers = { 'Reply-To': contact_email }
            )
            email.send()
            messages.success(request, _('Thank you ! We will check in as soon as possible ;-)'))
            return redirect('contact_us')
        else:
            messages.info(request, _('Oops ! Message not send...'))
    return render(request, 'students/contact/contact_form.html', { 'form': form_class }) 
Example #22
Source File: views.py    From doccano with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)

        # here we make sure that a post request won't trigger a subscription in case allow_signup is False
        if not bool(settings.ALLOW_SIGNUP):
            return redirect('signup')

        if not hasattr(settings, "EMAIL_BACKEND") and not hasattr(settings, "EMAIL_HOST"):
            return render(request, 'email_not_set.html')

        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'scheme': request.scheme,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.send()
            return render(request, 'validate_mail_address_complete.html')
        else:
            return render(request, self.template_name, {'form': form, 'allow_signup': bool(settings.ALLOW_SIGNUP)}) 
Example #23
Source File: export_users_csv.py    From logtacts with MIT License 5 votes vote down vote up
def handle(self, *args, **kwargs):
        date_string = timezone.now().strftime("%Y_%m_%d")
        with open("co_users_{}.csv".format(date_string), 'w') as csvfile:
            writer = csv.writer(csvfile)
            for user in User.objects.all():
                writer.writerow([user.email, user.username, user.first_name, user.last_name])
        with open("co_users_{}.csv".format(date_string), 'r') as csvfile:
            message = EmailMessage(
                'CO Users',
                'See attached',
                'site@contactotter.com',
                ['philip@inkpebble.com'],
            )
            message.attach("co_users_{}.csv".format(date_string), csvfile.read(), 'text/csv')
            message.send() 
Example #24
Source File: emails.py    From registration with MIT License 5 votes vote down vote up
def render_mail(template_prefix, recipient_email, substitutions,
                from_email=FROM_EMAIL, action_required=False):
    """
    Renders an e-mail to `email`.  `template_prefix` identifies the
    e-mail that is to be sent, e.g. "account/email/email_confirmation"
    """
    substitutions.update(utils.get_substitutions_templates())
    subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                               context=substitutions)
    # remove superfluous line breaks
    subject = " ".join(subject.splitlines()).strip()
    prefix = '[' + settings.HACKATHON_NAME + ']'
    if action_required:
        prefix = '[ACTION REQUIRED]'
    subject = prefix + ' ' + subject
    substitutions.update({'subject': subject})

    bodies = {}
    for ext in ['html', 'txt']:
        try:
            template_name = '{0}_message.{1}'.format(template_prefix, ext)
            bodies[ext] = render_to_string(template_name,
                                           substitutions).strip()
        except TemplateDoesNotExist:
            if ext == 'txt' and not bodies:
                # We need at least one body
                raise
    if 'txt' in bodies:
        msg = EmailMultiAlternatives(subject,
                                     bodies['txt'],
                                     from_email,
                                     [recipient_email])
        if 'html' in bodies:
            msg.attach_alternative(bodies['html'], 'text/html')
    else:
        msg = EmailMessage(subject,
                           bodies['html'],
                           from_email,
                           [recipient_email])
        msg.content_subtype = 'html'  # Main content is now text/html
    return msg 
Example #25
Source File: checks.py    From django-watchman with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_email():
    headers = {"X-DJANGO-WATCHMAN": True}
    headers.update(watchman_settings.WATCHMAN_EMAIL_HEADERS)
    email = EmailMessage(
        "django-watchman email check",
        "This is an automated test of the email system.",
        watchman_settings.WATCHMAN_EMAIL_SENDER,
        watchman_settings.WATCHMAN_EMAIL_RECIPIENTS,
        headers=headers,
    )
    email.send()
    return {"ok": True} 
Example #26
Source File: models.py    From PonyConf with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: adapters.py    From django-invitations with GNU General Public License v3.0 5 votes vote down vote up
def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject,
                                         bodies['txt'],
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject,
                               bodies['html'],
                               settings.DEFAULT_FROM_EMAIL,
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg 
Example #28
Source File: views.py    From cruzz with MIT License 5 votes vote down vote up
def post(self, request):
        user = request.data.get('user', {})

        # The create serializer, validate serializer, save serializer pattern
        # below is common.
        serializer = self.serializer_class(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        user = User.objects.get(email=serializer.data['email'])

        current_site = get_current_site(request)
        print(current_site)
        mail_subject = 'Activate your Vconnect account.'
        message = render_to_string('acc_active_email.html', {
            'user': user,
            'domain': current_site,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
            'token': account_activation_token.make_token(user),
        })
        print(message)
        to_email = serializer.data['email']
        email = EmailMessage(
            mail_subject, message, to=[to_email]
        )
        print(email, to_email)

        email.send()

        serializer.data['is_active'] = False
        return Response(serializer.data, status=status.HTTP_201_CREATED) 
Example #29
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def mail_sending_view(request):
    mail.EmailMessage(
        "Test message",
        "This is a test email",
        "from@example.com",
        ['first@example.com', 'second@example.com']).send()
    return HttpResponse("Mail sent") 
Example #30
Source File: test_mail.py    From sendgrid-django with MIT License 5 votes vote down vote up
def test_build_empty_sg_mail(self):
        msg = EmailMessage()
        with self.settings(SENDGRID_API_KEY='test_key'):
            mail = SendGridBackend()._build_sg_mail(msg)
            self.assertEqual(
                mail,
                {'from': {'email': 'webmaster@localhost'},
                 'subject': '',
                 'content': [{'type': 'text/plain', 'value': ''}],
                 'personalizations': [{'subject': ''}]}
            )