Python django.core.mail.send_mail() Examples

The following are 30 code examples of django.core.mail.send_mail(). 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: forms.py    From open-humans with MIT License 6 votes vote down vote up
def send_mail(self, project_member_id, project):
        params = {
            "message": self.cleaned_data["message"],
            "project_member_id": project_member_id,
            "project": project,
        }

        plain = render_to_string("email/activity-message.txt", params)
        html = render_to_string("email/activity-message.html", params)

        send_mail(
            "Open Humans: message from project member {}".format(project_member_id),
            plain,
            "no-reply@example.com",
            [project.contact_email],
            html_message=html,
        ) 
Example #2
Source File: tasks.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_register_active_email(to_email, username, token):
    """发送激活邮件"""
    # 组织邮件内容
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = """
                        <h1>%s, 欢迎您成为天天生鲜注册会员</h1>
                        请点击以下链接激活您的账户(7个小时内有效)<br/>
                        <a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
                    """ % (username, token, token)

    # 发送激活邮件
    # send_mail(subject=邮件标题, message=邮件正文,from_email=发件人, recipient_list=收件人列表)
    send_mail(subject, message, sender, receiver, html_message=html_message) 
Example #3
Source File: tasks.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_register_active_email(to_email, username, token):
    """发送激活邮件"""
    # 组织邮件内容
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = """
                            <h1>%s, 欢迎您成为天天生鲜注册会员</h1>
                            请点击以下链接激活您的账户<br/>
                            <a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
                        """ % (username, token, token)

    # 发送激活邮件
    # send_mail(subject=邮件标题, message=邮件正文,from_email=发件人, recipient_list=收件人列表)
    send_mail(subject, message, sender, receiver, html_message=html_message) 
Example #4
Source File: emailer.py    From junction with MIT License 6 votes vote down vote up
def send_email(to, context, template_dir):
    """Render given templates and send email to `to`.

    :param to: User object to send email to..
    :param context: dict containing which needs to be passed to django template
    :param template_dir: We expect files message.txt, subject.txt,
    message.html etc in this folder.
    :returns: None
    :rtype: None

    """

    def to_str(template_name):
        return render_to_string(path.join(template_dir, template_name), context).strip()

    subject = to_str("subject.txt")
    text_message = to_str("message.txt")
    html_message = to_str("message.html")
    from_email = settings.DEFAULT_FROM_EMAIL
    recipient_list = [_format_email(to)]

    return send_mail(
        subject, text_message, from_email, recipient_list, html_message=html_message
    ) 
Example #5
Source File: collect.py    From acacia_main with MIT License 6 votes vote down vote up
def send_downgrade_email(customer):
    from django.core.mail import send_mail
    from django.template.loader import render_to_string

    email_content = render_to_string(
        "billing/email_downgrade.txt",
        context={"username":customer.user.username}
    )

    result = send_mail(
        'Acacia Account Downgraded',
        email_content,
        'noreply@tradeacacia.com',
        [customer.user.email],
        fail_silently=True
    )
    return result == 1 
Example #6
Source File: models.py    From Try-Django-1.11 with MIT License 6 votes vote down vote up
def send_activation_email(self):
        if not self.activated:
            self.activation_key = code_generator()# 'somekey' #gen key
            self.save()
            #path_ = reverse()
            path_ = reverse('activate', kwargs={"code": self.activation_key})
            full_path = "https://muypicky.com" + path_
            subject = 'Activate Account'
            from_email = settings.DEFAULT_FROM_EMAIL
            message = f'Activate your account here: {full_path}'
            recipient_list = [self.user.email]
            html_message = f'<p>Activate your account here: {full_path}</p>'
            print(html_message)
            sent_mail = send_mail(
                            subject, 
                            message, 
                            from_email, 
                            recipient_list, 
                            fail_silently=False, 
                            html_message=html_message)
            sent_mail = False
            return sent_mail 
Example #7
Source File: views.py    From website with MIT License 6 votes vote down vote up
def post(self, request):
        form = RegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username','')
            email = form.cleaned_data.get('email', '')
            password = form.cleaned_data.get('password', '')
            users = User()
            users.username = username
            users.password =make_password(password)
            users.email = email
            users.is_active = False
            users.save()
            token = token_confirm.generate_validate_token(username)
            # message = "\n".join([u'{0},欢迎加入我的博客'.format(username), u'请访问该链接,完成用户验证,该链接1个小时内有效',
            #                      '/'.join([settings.DOMAIN, 'activate', token])])
            #send_mail(u'注册用户验证信息', message, settings.EMAIL_HOST_USER, [email], fail_silently=False)
            send_register_email.delay(email=email,username=username,token=token,send_type="register")
            return JsonResponse({'valid':True,'status':200, 'message': u"请登录到注册邮箱中验证用户,有效期为1个小时"})
        return JsonResponse({'status':400,'data':form.errors,'valid':False}) 
Example #8
Source File: tasks.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def send_mail_async(*args, **kwargs):
    """ Using celery to send email async

    You can use it as django send_mail function

    Example:
    send_mail_sync.delay(subject, message, from_mail, recipient_list, fail_silently=False, html_message=None)

    Also you can ignore the from_mail, unlike django send_mail, from_email is not a require args:

    Example:
    send_mail_sync.delay(subject, message, recipient_list, fail_silently=False, html_message=None)
    """
    if len(args) == 3:
        args = list(args)
        args[0] = settings.EMAIL_SUBJECT_PREFIX + args[0]
        args.insert(2, settings.EMAIL_HOST_USER)
        args = tuple(args)

    try:
        send_mail(*args, **kwargs)
    except Exception as e:
        logger.error("Sending mail error: {}".format(e)) 
Example #9
Source File: forms.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def send_mail(self,
                  subject_template_name, email_template_name, context, *args,
                  html_email_template_name=None, **kwargs):
        user_is_active = context['user'].is_active
        html_email_template_name = html_email_template_name[user_is_active]
        email_template_name = email_template_name[user_is_active]
        if not user_is_active:
            case_id = str(uuid4()).upper()
            auth_log.warning(
                (self.admin_inactive_user_notification + ", but the account is deactivated [{cid}].")
                .format(u=context['user'], cid=case_id)
            )
            context['restore_request_id'] = case_id

        args = [subject_template_name, email_template_name, context, *args]
        kwargs.update(html_email_template_name=html_email_template_name)
        context.update({'ENV': settings.ENVIRONMENT, 'subject_prefix': settings.EMAIL_SUBJECT_PREFIX_FULL})
        super().send_mail(*args, **kwargs) 
Example #10
Source File: forms.py    From open-humans with MIT License 6 votes vote down vote up
def send_mail(self, sender, receiver):
        params = {
            "message": self.cleaned_data["message"],
            "sender": sender,
            "receiver": receiver,
        }

        plain = render_to_string("email/user-message.txt", params)
        html = render_to_string("email/user-message.html", params)

        send_mail(
            "Open Humans: message from {} ({})".format(
                sender.member.name, sender.username
            ),
            plain,
            sender.member.primary_email.email,
            [receiver.member.primary_email.email],
            html_message=html,
        ) 
Example #11
Source File: tasks.py    From django_blog with MIT License 6 votes vote down vote up
def email_handler(args):
    app_model = settings.AUTH_USER_MODEL.split('.')
    user_model = apps.get_model(*app_model)
    recipient = user_model.objects.filter(id__in=args)
    d = {}
    for user in recipient:
        try:
            if not (hasattr(user, 'onlinestatus') and user.onlinestatus.is_online()):
                context = {'receiver': user.username,
                           'unsend_count': user.notifications.filter(unread=True, emailed=False).count(),
                           'notice_list': user.notifications.filter(unread=True, emailed=False),
                           'unread_link': 'http://www.aaron-zhao.com/notifications/unread/'}
                msg_plain = render_to_string("notifications/email/email.txt", context=context)
                result = send_mail("来自[AA的博客] 您有未读的评论通知",
                                   msg_plain,
                                   'support@aaron-zhao.com',
                                   recipient_list=[user.email])
                user.notifications.unsent().update(emailed=True)
                if result == 1:
                    d[user.username] = 1
        except Exception as e:
            print("Error in easy_comment.handlers.py.email_handler: %s" % e)
    return d 
Example #12
Source File: views.py    From peering-manager with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        autonomous_system = get_object_or_404(AutonomousSystem, asn=kwargs["asn"])

        if not autonomous_system.can_receive_email:
            redirect(autonomous_system.get_absolute_url())

        form = AutonomousSystemEmailForm(request.POST)
        form.fields[
            "recipient"
        ].choices = autonomous_system.get_contact_email_addresses()

        if form.is_valid():
            sent = send_mail(
                form.cleaned_data["subject"],
                form.cleaned_data["body"],
                settings.SERVER_EMAIL,
                [form.cleaned_data["recipient"]],
            )
            if sent == 1:
                messages.success(request, "Email sent.")
            else:
                messages.error(request, "Unable to send the email.")

        return redirect(autonomous_system.get_absolute_url()) 
Example #13
Source File: test_backend.py    From postmarker with MIT License 6 votes vote down vote up
def test_send_mail(postmark_request, settings):
    send_mail(**SEND_KWARGS)
    assert postmark_request.call_args[1]["json"] == (
        {
            "ReplyTo": None,
            "Subject": "Subject here",
            "To": "receiver@example.com",
            "Bcc": None,
            "Headers": [],
            "Cc": None,
            "Attachments": [],
            "TextBody": "Here is the message.",
            "HtmlBody": None,
            "Tag": None,
            "Metadata": None,
            "TrackOpens": False,
            "From": "sender@example.com",
        },
    )
    assert postmark_request.call_args[1]["headers"]["X-Postmark-Server-Token"] == settings.POSTMARK["TOKEN"] 
Example #14
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send(self):
        result = None
        self.recipient = self.recipient.strip()

        try:
            validate_phone_number(self.recipient)
            result = self.send_sms()
        except ValidationError:
            pass

        try:
            validate_email(self.recipient)
            result = self.send_mail()
        except ValidationError:
            pass

        self.save()
        return result 
Example #15
Source File: send_mail.py    From djangochannel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_email(email, code):
    """Отправка кода на email"""
    subject = 'Код подтверждения'
    message = 'Введите этот код для подтверждения смены email: {}'.format(code)
    try:
        send_mail(subject, message, 'robot@djangochannel.com', [email])
        return True
    except BadHeaderError:
        return False 
Example #16
Source File: controllers.py    From GraphSpace with GNU General Public License v2.0 5 votes vote down vote up
def send_password_reset_email(request, password_reset_code):
	# Construct email message
	mail_title = 'Password Reset Information for GraphSpace!'
	message = 'Please go to the following url to reset your password: ' + settings.URL_PATH + 'reset_password/?code=' + password_reset_code.code
	email_from = "GraphSpace Admin"

	return send_mail(mail_title, message, email_from, [password_reset_code.email], fail_silently=False) 
Example #17
Source File: send_mail.py    From djangochannel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_mail_forum(instance):
    """Отправка email о новых темах"""
    subject = 'Новая темя на форуме'
    message = 'Пользователем {}, была создана новая тема "{}" в разделе "{}"'.format(
        instance.user,
        instance.title,
        instance.section)
    try:
        send_mail(subject, message, 'robot@djangochannel.com', ["socanime@gmail.com"])
        return True
    except BadHeaderError:
        return False 
Example #18
Source File: send_mail.py    From djangochannel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_mail_contact(instance):
    """Отправка email контакной формы"""
    subject = 'Новое сообщение обратной связи'
    message = 'Пользователем {}, была создана новая тема "{}"'.format(
        instance.email,
        instance.title)
    try:
        send_mail(subject, message, 'robot@djangochannel.com', ["socanime@gmail.com"])
        return True
    except BadHeaderError:
        return False 
Example #19
Source File: send_mail.py    From djangochannel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_mail_new_mess(user, email):
    """Отправка email о новом личном сообщении"""
    subject = 'Новое личное сообщение'
    message = 'Здравствуйте, пользователь {}, отправил Вам личное сообщение на сайте djangochannel.com\n ' \
              'Посмотреть его Вы можете у себя в личном кабинете.'.format(user)
    try:
        send_mail(subject, message, 'robot@djangochannel.com', [email])
        return True
    except BadHeaderError:
        return False 
Example #20
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def invite_attendee(email, event, sender):
    context = {
        "sender": sender.profile,
        "team": event.team,
        "event": event,
        "site": Site.objects.get(id=1),
    }
    recipient = None
    if type(email) == User:
        recipient = email
        email = recipient.email

    email_subject = "Invitation to attend: %s" % event.name
    email_body_text = render_to_string(
        "get_together/emails/events/attendee_invite.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/events/attendee_invite.html", context
    )
    email_recipients = [email]
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    success = send_mail(
        from_email=email_from,
        html_message=email_body_html,
        message=email_body_text,
        recipient_list=email_recipients,
        subject=email_subject,
        fail_silently=True,
    )
    EmailRecord.objects.create(
        sender=sender,
        recipient=recipient,
        email=email,
        subject=email_subject,
        body=email_body_text,
        ok=success,
    ) 
Example #21
Source File: services.py    From abidria-api with MIT License 5 votes vote down vote up
def send_ask_confirmation_mail(self, confirmation_token, email, username):
        confirmation_url = "{}?token={}".format(self.request.build_absolute_uri(reverse('email-confirmation')),
                                                confirmation_token)

        context_params = {'username': username, 'confirmation_url': confirmation_url}
        plain_text_message = get_template('ask_confirmation_email.txt').render(context_params)
        html_message = get_template('ask_confirmation_email.html').render(context_params)

        subject, origin_email, target_email = 'Abidria account confirmation', settings.EMAIL_HOST_USER, email

        mail.send_mail(subject,
                       plain_text_message,
                       origin_email, [target_email, ],
                       html_message=html_message,
                       fail_silently=False) 
Example #22
Source File: task.py    From django-shop-tutorial with MIT License 5 votes vote down vote up
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 number {}'.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,
                          'django-shop-tutorial@myshop.com',
                          [order.email])
    return mail_sent 
Example #23
Source File: tasks.py    From Django-2-by-Example with MIT License 5 votes vote down vote up
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,
                          'admin@myshop.com',
                          [order.email])
    return mail_sent 
Example #24
Source File: tasks.py    From Django-2-by-Example with MIT License 5 votes vote down vote up
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,
                          'admin@myshop.com',
                          [order.email])
    return mail_sent 
Example #25
Source File: tasks.py    From Django-2-by-Example with MIT License 5 votes vote down vote up
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,
                          'admin@myshop.com',
                          [order.email])
    return mail_sent 
Example #26
Source File: send_daily_member_update.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_new_members(team, new_members):
    if len(new_members) < 1:
        return
    admins = [
        member.user.user
        for member in Member.objects.filter(team=team, role=Member.ADMIN)
        if member.user.user.account.is_email_confirmed
    ]
    if len(admins) < 1:
        return
    context = {"team": team, "members": new_members, "site": Site.objects.get(id=1)}

    email_subject = "New members joined team %s" % strip_tags(team.name)
    email_body_text = render_to_string(
        "get_together/emails/teams/new_team_members.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/teams/new_team_members.html", context
    )
    email_recipients = [admin.email for admin in admins]
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    success = send_mail(
        from_email=email_from,
        html_message=email_body_html,
        message=email_body_text,
        recipient_list=email_recipients,
        subject=email_subject,
    )

    for admin in admins:
        EmailRecord.objects.create(
            sender=None,
            recipient=admin,
            email=admin.email,
            subject=email_subject,
            body=email_body_text,
            ok=success,
        ) 
Example #27
Source File: create_next_in_series.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def email_host_new_event(event):
    context = {"event": event, "site": Site.objects.get(id=1)}
    email_subject = "New event: %s" % event.name
    email_body_text = render_to_string(
        "get_together/emails/events/event_from_series.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/events/event_from_series.html", context
    )
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    for attendee in Attendee.objects.filter(
        event=event, role=Attendee.HOST, user__user__account__is_email_confirmed=True
    ):
        success = send_mail(
            from_email=email_from,
            html_message=email_body_html,
            message=email_body_text,
            recipient_list=[attendee.user.user.email],
            subject=email_subject,
            fail_silently=True,
        )
        EmailRecord.objects.create(
            sender=None,
            recipient=attendee.user.user,
            email=attendee.user.user.email,
            subject=email_subject,
            body=email_body_text,
            ok=success,
        ) 
Example #28
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_cancellation_emails(event, reason, canceled_by):
    context = {
        "event": event,
        "reason": reason,
        "by": canceled_by.profile,
        "site": Site.objects.get(id=1),
    }
    email_subject = "Event canceled: %s" % event.name
    email_body_text = render_to_string(
        "get_together/emails/events/event_canceled.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/events/event_canceled.html", context
    )
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    for attendee in event.attendees.filter(user__account__is_email_confirmed=True):
        success = send_mail(
            from_email=email_from,
            html_message=email_body_html,
            message=email_body_text,
            recipient_list=[attendee.user.email],
            subject=email_subject,
            fail_silently=True,
        )
        EmailRecord.objects.create(
            sender=canceled_by,
            recipient=attendee.user,
            email=attendee.user.email,
            subject=email_subject,
            body=email_body_text,
            ok=success,
        ) 
Example #29
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def contact_attendee(attendee, body, sender):
    context = {
        "sender": sender,
        "event": attendee.event,
        "body": body,
        "site": Site.objects.get(id=1),
    }
    email_subject = "A message about: %s" % attendee.event.name
    email_body_text = render_to_string(
        "get_together/emails/events/attendee_contact.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/events/attendee_contact.html", context
    )
    email_recipients = [attendee.user.user.email]
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    success = send_mail(
        from_email=email_from,
        html_message=email_body_html,
        message=email_body_text,
        recipient_list=email_recipients,
        subject=email_subject,
        fail_silently=True,
    )
    EmailRecord.objects.create(
        sender=sender.user,
        recipient=attendee.user.user,
        email=attendee.user.user.email,
        subject=email_subject,
        body=email_body_text,
        ok=success,
    ) 
Example #30
Source File: teams.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def contact_member(member, body, sender):
    context = {
        "sender": sender,
        "team": member.team,
        "body": body,
        "site": Site.objects.get(id=1),
    }
    email_subject = "A message from: %s" % member.team
    email_body_text = render_to_string(
        "get_together/emails/teams/member_contact.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/teams/member_contact.html", context
    )
    email_recipients = [member.user.user.email]
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    success = send_mail(
        from_email=email_from,
        html_message=email_body_html,
        message=email_body_text,
        recipient_list=email_recipients,
        subject=email_subject,
        fail_silently=True,
    )
    EmailRecord.objects.create(
        sender=sender.user,
        recipient=member.user.user,
        email=member.user.user.email,
        subject=email_subject,
        body=email_body_text,
        ok=success,
    )