コード例 #1
0
ファイル: views.py プロジェクト: dekoza/weblate
def mail_admins_contact(request, subject, message, context, sender, to):
    """Send a message to the admins, as defined by the ADMINS setting."""
    LOGGER.info(
        'contact form from %s',
        sender,
    )
    if not to and settings.ADMINS:
        to = [a[1] for a in settings.ADMINS]
    elif not settings.ADMINS:
        messages.error(
            request,
            _('Message could not be sent to administrator!')
        )
        LOGGER.error(
            'ADMINS not configured, can not send message!'
        )
        return

    mail = EmailMultiAlternatives(
        '{0}{1}'.format(settings.EMAIL_SUBJECT_PREFIX, subject % context),
        message % context,
        to=to,
        headers={'Reply-To': sender},
    )

    mail.send(fail_silently=False)

    messages.success(
        request,
        _('Message has been sent to administrator.')
    )
コード例 #2
0
 def deliver_to(self, user, context, notification, language):
     to_email = self.get_email(user)
     context.update({
         'to_email': to_email,
     })
     subject = render_to_string(
         (
             "notifyme/notification_types/%s/email/subject.txt" % notification.identifier,
             "notifyme/notification_types/generic/email/subject.txt",
         ),
         context_instance=context
     )
     body = render_to_string(
         (
             "notifyme/notification_types/%s/email/body.txt" % notification.identifier,
             "notifyme/notification_types/generic/email/body.txt",
         ),
         context_instance=context
     )
     body_html = render_to_string(
         (
             "notifyme/notification_types/%s/email/body.html" % notification.identifier,
             "notifyme/notification_types/generic/email/body.html",
         ),
         context_instance=context
     )
     # send the HTML Email
     email_msg = EmailMultiAlternatives(subject, body, self.get_from_email(user),
         [to_email], headers={})
     email_msg.attach_alternative(body_html, "text/html")
     email_msg.send()
     
     
コード例 #3
0
ファイル: smartgrid.py プロジェクト: jtakayama/makahiki-draft
def check_new_submissions():
    """Check the action submission queue and send out notifications to admin when there is new
    submissions in the queue.
    algorithm for queue processing:
      1. on zero to one transition: send email unless email already sent within N minutes.
    """
    submission_count = ActionMember.objects.filter(
        action__type="activity",
        approval_status="pending").count()

    if submission_count:
        try:
            admin = User.objects.get(username=settings.ADMIN_USER)
            action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY)
            reminder = EmailReminder.objects.filter(user=admin, action=action)
            if not reminder:
                EmailReminder.objects.create(user=admin,
                                             action=action,
                                             send_at=datetime.datetime.today(),
                                             sent=True)

                challenge = challenge_mgr.get_challenge()
                subject = "[%s] %d New Pending Action Submissions" % (challenge.name,
                                                                      submission_count)
                message = "There are %d new pending action submissions as of %s." % (
                    submission_count, datetime.datetime.today())

                if challenge.email_enabled and challenge.contact_email:
                    print "Sending new submission notification to %s" % challenge.contact_email
                    mail = EmailMultiAlternatives(subject, message, challenge.contact_email,
                        [challenge.contact_email, ])
                    mail.send()
        except ObjectDoesNotExist:
            pass
コード例 #4
0
ファイル: emails.py プロジェクト: xenops/course-discovery
def send_email_for_studio_instance_created(course_run, site):
    """ Send an email to course team on studio instance creation.

        Arguments:
            course_run (CourseRun): CourseRun object
            site (Site): Current site
    """
    try:
        course_key = CourseKey.from_string(course_run.lms_course_id)
        object_path = reverse('publisher:publisher_course_run_detail',
                              kwargs={'pk': course_run.id})
        subject = _('Studio URL created: {title} {run_number}').format(  # pylint: disable=no-member
            title=course_run.course.title,
            run_number=course_key.run)

        to_addresses = [course_run.course.course_team_admin.email]
        from_address = settings.PUBLISHER_FROM_EMAIL

        course_team_admin = course_run.course.course_team_admin
        project_coordinator = course_run.course.project_coordinator

        context = {
            'course_run':
            course_run,
            'course_run_page_url':
            'https://{host}{path}'.format(host=site.domain.strip('/'),
                                          path=object_path),
            'course_name':
            course_run.course.title,
            'from_address':
            from_address,
            'course_team_name':
            course_team_admin.get_full_name() or course_team_admin.username,
            'project_coordinator_name':
            project_coordinator.get_full_name()
            or project_coordinator.username,
            'contact_us_email':
            project_coordinator.email,
            'studio_url':
            course_run.studio_url
        }

        txt_template_path = 'publisher/email/studio_instance_created.txt'
        html_template_path = 'publisher/email/studio_instance_created.html'

        txt_template = get_template(txt_template_path)
        plain_content = txt_template.render(context)
        html_template = get_template(html_template_path)
        html_content = html_template.render(context)
        email_msg = EmailMultiAlternatives(subject,
                                           plain_content,
                                           from_address,
                                           to=to_addresses)
        email_msg.attach_alternative(html_content, 'text/html')
        email_msg.send()
    except Exception:  # pylint: disable=broad-except
        error_message = 'Failed to send email notifications for course_run [{run_id}]'.format(
            run_id=course_run.id)
        logger.exception(error_message)
        raise Exception(error_message)
コード例 #5
0
 def html_email_user(self, subject, message, from_email=None):
     from premailer import transform
     from django.core.mail.message import EmailMultiAlternatives
     inlined_mail = transform(message)
     mail = EmailMultiAlternatives(subject, '', settings.SERVER_EMAIL, [self.email, ], )
     mail.attach_alternative(inlined_mail, 'text/html')
     mail.send(fail_silently=True)
コード例 #6
0
ファイル: emails.py プロジェクト: liqd/euth_wagtail
    def dispatch(self, object, *args, **kwargs):
        self.object = object
        languages = [get_language(), self.fallback_language]
        receivers = self.get_receiver_emails()
        context = self.get_context()
        context.update(kwargs)
        attachments = self.get_attachments()
        template = self.template_name

        subject = select_template([
            'emails/{}.{}.subject'.format(template, lang) for lang in languages
        ])
        plaintext = select_template([
            'emails/{}.{}.txt'.format(template, lang) for lang in languages
         ])
        html = select_template([
            'emails/{}.{}.html'.format(template, lang) for lang in languages
        ])
        mail = EmailMultiAlternatives(
            subject=subject.render(context).strip(),
            body=plaintext.render(context),
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=receivers,
        )
        if len(attachments) > 0:
            mail.mixed_subtype = 'related'

            for attachment in attachments:
                mail.attach(attachment)

        mail.attach_alternative(html.render(context), 'text/html')
        mail.send()
        return mail
コード例 #7
0
    def handle(self, *args, **options):
        while True:
            last_hour = datetime.datetime.utcnow().replace(tzinfo=utc) - datetime.timedelta(hours=1)
            profiles = Profile.objects.select_related().filter(
                user__date_joined__gte=last_hour,
                user_referrer__profile__enable_email_updates=True,
                user_referrer__is_active=True,
            )
            for profile in profiles:
                if not profile.user_referrer.email:
                    continue

                try:
                    FriendJoinedEmailLog.objects.get(user=profile.user_referrer, user_referred=profile.user)
                except FriendJoinedEmailLog.DoesNotExist:
                    dict_context = {
                        'site': self.site,
                        'referred_profile': profile,
                        'referring_profile': profile.user_referrer.get_profile(),
                    }
                    email_subject = render_to_string('emails/friend-joined/subject.txt', dict_context).strip()
                    email_txt = render_to_string('emails/friend-joined/message.txt', dict_context)
                    email_html = render_to_string('emails/friend-joined/message.html', dict_context)
                    email = EmailMultiAlternatives(
                        email_subject, email_txt, settings.DEFAULT_FROM_EMAIL, [profile.user_referrer.email,]
                    )
                    email.attach_alternative(email_html, 'text/html')
                    email.send()
                    FriendJoinedEmailLog.objects.create(user=profile.user_referrer, user_referred=profile.user)
            self.close_db_connection()
            time.sleep(600)
コード例 #8
0
    def send_email(self, request, user):
        current_site = get_current_site(request)
        site_name = current_site.name
        domain = current_site.domain
        # email_field_name = USER_MODEL.get_email_field_name()

        context = {
            'email': user.email,
            'domain': domain,
            'site_name': site_name,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'user': user,
            'token': self.token_generator.make_token(user),
            'protocol': 'https' if self.use_https else 'http',
            **self.extra_email_context
        }

        subject = loader.render_to_string(self.subject_template_name, context)
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(self.email_template_name, context)
        email_message = EmailMultiAlternatives(subject, body, self.from_email,
                                               [user.email])

        if self.html_email_template_name is not None:
            html_email = loader.render_to_string(self.html_email_template_name,
                                                 context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()
コード例 #9
0
    def send_email(self, prefix):
        subject_file = 'authemail/%s_subject.txt' % prefix
        txt_file = 'authemail/%s.txt' % prefix
        html_file = 'authemail/%s.html' % prefix

        subject = render_to_string(subject_file).strip()
        from_email = settings.DEFAULT_EMAIL_FROM
        to = self.user.email
        bcc_email = settings.DEFAULT_EMAIL_BCC
        # Make some context available
        ctxt = {
            'email': self.user.email,
            'first_name': self.user.first_name,
            'last_name': self.user.last_name,
            'code': self.code,
            'MEDIA_URL': settings.MEDIA_URL,
            'STATIC_URL': settings.STATIC_URL,
            'BASE_URL': settings.BASE_URL
        }
        text_content = render_to_string(txt_file, ctxt)
        html_content = render_to_string(html_file, ctxt)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
                  bcc=[bcc_email])
        msg.attach_alternative(html_content, 'text/html')
        msg.send()
コード例 #10
0
ファイル: mail.py プロジェクト: IntersectAustralia/asvo-tao
def send_mail(template_name, context, subject, to_addrs, bcc=None, from_addr=None):
    from tao.models import GlobalParameter
    if from_addr is None:
        from_addr = settings.EMAIL_FROM_ADDRESS

    if type(context) == dict:
        context = Context(context)

    try:
        html_mail = GlobalParameter.objects.get(parameter_name='{template_name}.html'.format(template_name=template_name))
        html_content = Template(html_mail.parameter_value).render(context)
    except GlobalParameter.DoesNotExist:
        html_content = None

    try:
        text_mail = GlobalParameter.objects.get(parameter_name='{template_name}.txt'.format(template_name=template_name))
        if len(text_mail.parameter_value.strip()) == 0:
            # Don't send the email if the txt template is empty
            # Just log the event for posterity
            logger.warn("Not sending template '{0}' to {1}".format(template_name, str(to_addrs)))
            return
        text_content = Template(text_mail.parameter_value).render(context)
        msg = EmailMultiAlternatives(subject, text_content, from_addr, to_addrs, bcc=bcc)
        if html_content is not None:
            msg.attach_alternative(html_content, 'text/html')
        msg.send(fail_silently=False)
        logger.info("Sent template '{0}' to {1}".format(template_name, str(to_addrs)))
    except GlobalParameter.DoesNotExist:
        msg = EmailMultiAlternatives("CONFIGURATION ERROR", "Template {template_name}.txt is not found".format(template_name=template_name), from_addr, (from_addr,))
        msg.send(fail_silently=False)
コード例 #11
0
ファイル: mailutils.py プロジェクト: ebrelsford/596acres
def mail_multiple(
    subject,
    message,
    email_addresses,
    from_email=settings.ORGANIZERS_EMAIL,
    cc=None,
    bcc=None,
    html_message=None,
    connection=None,
    fail_silently=True,
):
    """
    Sends a message to multiple email addresses. Based on
    django.core.mail.mail_admins()
    """
    for email_address in email_addresses:
        mail = EmailMultiAlternatives(
            u"%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
            message,
            bcc=bcc,
            cc=cc,
            connection=connection,
            from_email=from_email,
            to=[email_address],
        )
        if html_message:
            mail.attach_alternative(html_message, "text/html")
        mail.send(fail_silently=fail_silently)
コード例 #12
0
ファイル: return_mail_sender.py プロジェクト: wolet/zTools
def fixSizes():
    from django.core.mail.message import EmailMultiAlternatives
    from django.template.loader import render_to_string
    from django.utils.html import strip_tags
    from rts.models import ReturnedItemDetails, rts_status

    for item in ReturnedItemDetails.objects.filter(status = rts_status.REFUNDED,isEmailSent=False):

        from_email = "<*****@*****.**>"
        from_name = str(FROM_EMAIL_NAME)
        #to = item.order_item.customer_email
        to = "*****@*****.**"

        subject = str(FROM_EMAIL_SUBJECT)
        html_content = render_to_string('zidaya_return_email_template_1.html', {
            'billing_name':item.order_item.billing_name.title(),
            'order_date': str(item.order_item.order_date.day).zfill(2)+"."+str(item.order_item.order_date.month).zfill(2)+"."+str(item.order_item.order_date.year),
            'order_nr':item.order_item.order_nr,
            'paid_price':item.order_item.paid_price,
            'refund_reference_number':item.refund_reference_number,
            'product_image':"http://static.zidaya.com/p/-"+str(item.order_item.id_catalog_config)[::-1]+"-1-catalog.jpg",
            'name':item.order_item.name,
            'new_coupon':item.new_coupon,
            'sku':item.order_item.sku
            })
        text_content = strip_tags(html_content)

        msg = EmailMultiAlternatives(subject, text_content, from_name+" "+from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        try:
            msg.send()
            item.isEmailSent = True
            item.save()
        except:
            pass
コード例 #13
0
def send_active_email(active_form,user_email):
    subject,form_email,to = u'数据服务平台-激活邮件','*****@*****.**',user_email
    text_content = u'数据服务平台-激活邮件'
    html_content = active_form
    msg = EmailMultiAlternatives(subject,text_content,form_email,[to])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()
コード例 #14
0
def recover_password(user, request):
    try:
        #current_site = get_current_site(request)
        #current_site.domain
        new_code = pass_generator(20)
        to = user.email
        data = {'msg': 'Your new password',
                'code': new_code,
                'username': user.username,
                'domain_fron': 'app.ezonseller.com',
                'url': settings.URL,
                }
        subject, from_email = data['msg'], EMAIL_HOST_USER
        text_content = render_to_string("email/recovery_password.html", data)
        html_content = render_to_string("email/recovery_password.html", data)
        send = EmailMultiAlternatives(subject, text_content, from_email, [to],
                                      headers={'From': 'Ezonseller <'+from_email+'>',
                                               'Reply-to': 'Ezonseller <'+from_email+'>'})
        send.attach_alternative(html_content, "text/html")
        send.send()
        user.recovery = new_code
        user.save()
        return True
    except:
        return False
コード例 #15
0
ファイル: models.py プロジェクト: spenglerBR/Recrutase
    def enviarEmailParaCandidato(self, vTipoEmail):
        try:
            iEmail              = EmailMultiAlternatives()
            iEmail.subject      = self.assunto
            iEmail.body         = self.mensagem
            iEmail.from_email   = self.email_remetente
            iEmail.to           = [self.destinatario.email]
            iTemplate           = loader.get_template('emails/nova-mensagem.html')
            if vTipoEmail == constantes.cntTipoEmailEnviadoPelaEmpresa:
                iContext        = Context({'imagem':'%s/email/confirmar/%s/' % (settings.PROJECT_ROOT_URL, self.id),
                                           'texto': self.mensagem,
                                           'nome_empresa': self.remetente.empresa.nome_fantasia,
                                           'logo_empresa': '%s%s%s' % (settings.PROJECT_ROOT_URL, settings.MEDIA_URL, self.remetente.empresa.imagem),
                                           'nome_candidato': self.destinatario.nome})
            elif vTipoEmail == constantes.cntTipoEmailEnviadoPeloRecrutase:
                iContext        = Context({'imagem':'%s%s%s' % (settings.PROJECT_ROOT_URL, settings.MEDIA_URL, 'img/email/recrutase.jpg'),
                                           'texto': self.mensagem,
                                           'nome_empresa': self.remetente.empresa.nome_fantasia,
                                           'logo_empresa': '%s%s%s' % (settings.PROJECT_ROOT_URL, settings.MEDIA_URL, 'img/email/recrutase-cabecalho.jpg'),
                                           'nome_candidato': self.destinatario.nome})

            iEmail.attach_alternative(iTemplate.render(iContext),'text/html')
            iEmail.send(fail_silently=True)
            return True
        except Exception, e:
            Erro().registraLog('enviarEmailParaCandidato', 'models.py', 'comunicacao', str(e), constantes.cntTipoLogErro)
            return False
コード例 #16
0
def activate_account(user, request):
    try:
        to = user.email
        uid = str(urlsafe_base64_encode(force_bytes(user.pk)))
        uid = uid[2:len(uid)-1]
        data = {'domain_fron': 'app.ezonseller.com',
                'url': settings.URL,
                #'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'uid': uid,
                'token': account_activation_token.make_token(user),
                'username': user.username,
                'msg': 'Account verification'
                }
        subject, from_email = data['msg'], EMAIL_HOST_USER
        text_content = render_to_string("email/user_verification.html", data)
        html_content = render_to_string("email/user_verification.html", data)
        send = EmailMultiAlternatives(subject, text_content, from_email, [to],
                                      headers={'From': 'Ezonseller <'+from_email+'>',
                                               'Reply-to': 'Ezonseller <'+from_email+'>'})
        send.attach_alternative(html_content, "text/html")
        send.send()
        return True
    except Exception as e:
        print(e)
        return False
コード例 #17
0
ファイル: views.py プロジェクト: Tatoo988/SIGeP
def contact_view(request):
    if request.method == "POST":
        form1 = ContactoForm(request.POST,request.FILES)
        form2 = MensajeContactoForm(request.POST,request.FILES)
        
        if form1.is_valid() and form2.is_valid() :        
           nombre = form1.cleaned_data['nombre'] 
           apellido = form1.cleaned_data['apellido'] 
           email = form1.cleaned_data['email'] 
           mensaje =form2.cleaned_data['mensaje'] 
           
           email_context = {
                'titulo': 'Has recibido un correo del usuario:',
                'usuario': nombre +','+ apellido,
                'mensaje': mensaje,
            }
            # se renderiza el template con el context
           email_html = render_to_string('email_contacto.html', email_context)
           email_text = strip_tags(email_html)
           correo = EmailMultiAlternatives('Mensaje de Usuario: '+nombre+', '+apellido, email_text, email,['*****@*****.**'],)
           # se especifica que el contenido es html
           correo.attach_alternative(email_html, 'text/html')
           # se envía el correo
           correo.send()
           
           return render_to_response('RecursosDeEmpresa/message_sent.html',context_instance=RequestContext(request)) 
          
    else:
        form1 = ContactoForm()
        form2 = MensajeContactoForm()
         
    boton = 'Enviar Solicitud' 
    ctx = {'form1': form1,'form2':form2,'boton':boton}
    return render_to_response('contacto.html',ctx,context_instance=RequestContext(request))
コード例 #18
0
ファイル: email_helpers.py プロジェクト: judy2k/pipsevents
def send_waiting_list_email(event,
                            users,
                            host="http://booking.thewatermelonstudio.co.uk"):
    ev_type = 'classes' if event.event_type.event_type == 'CL' else 'events'

    msg = EmailMultiAlternatives(
        '{} {}'.format(settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, event),
        get_template('booking/email/waiting_list_email.txt').render({
            'event':
            event,
            'host':
            host,
            'ev_type':
            ev_type
        }),
        settings.DEFAULT_FROM_EMAIL,
        bcc=[user.email for user in users],
    )
    msg.attach_alternative(
        get_template('booking/email/waiting_list_email.html').render({
            'event':
            event,
            'host':
            host,
            'ev_type':
            ev_type
        }), "text/html")
    msg.send(fail_silently=False)
コード例 #19
0
ファイル: __init__.py プロジェクト: schlos/write-it
    def send(self, outbound_message):
        # Here there should be somewhere the contacts
        # Returns a tuple with the result_of_sending, fatal_error
        # so False, True means that there was an error sending and you should not try again
        try:
            writeitinstance = outbound_message.message.writeitinstance
            template = writeitinstance.mailit_template
        except:
            return False, False

        author_name = outbound_message.message.author_name
        context = {
            'subject': outbound_message.message.subject,
            'content': outbound_message.message.content,
            'content_indented': process_content(outbound_message.message.content),
            'person': outbound_message.contact.person.name,
            'author': author_name,
            'writeit_url': writeitinstance.get_absolute_url(),
            'message_url': outbound_message.message.get_absolute_url(),
            'writeit_name': writeitinstance.name,
            'owner_email': writeitinstance.owner.email,
            }
        text_content = template.get_content_template().format(**context)
        html_content = template.content_html_template.format(**escape_dictionary_values(context))
        subject = template.subject_template.format(**context)

        if settings.SEND_ALL_EMAILS_FROM_DEFAULT_FROM_EMAIL:
            from_email = author_name + " <" + settings.DEFAULT_FROM_EMAIL + ">"
        else:
            from_domain = writeitinstance.config.custom_from_domain or settings.DEFAULT_FROM_DOMAIN
            from_email = (
                author_name + " <" + writeitinstance.slug +
                "+" + outbound_message.outboundmessageidentifier.key +
                '@' + from_domain + ">"
                )

        # There there should be a try and except looking
        # for errors and stuff
        try:
            to_email = writeitinstance.owner.email if writeitinstance.config.testing_mode else outbound_message.contact.value

            msg = EmailMultiAlternatives(
                subject,
                text_content,
                from_email,
                [to_email],
                connection=writeitinstance.config.get_mail_connection(),
                )
            if html_content:
                msg.attach_alternative(html_content, "text/html")
            msg.send(fail_silently=False)
            log = "Mail sent from %(from)s to %(to)s"

            log = log % {
                'from': from_email,
                'to': outbound_message.contact.value,
                }
            logging.info(log)
        except SMTPServerDisconnected, e:
            return False, False
コード例 #20
0
ファイル: utils.py プロジェクト: rwakulszowa/poradnia
def mail_managers_replyable(
    subject,
    message,
    fail_silently=False,
    connection=None,
    html_message=None,
    reply_email=None,
):
    """Sends a message to the managers, as defined by the MANAGERS setting."""
    if not settings.MANAGERS:
        return
    if reply_email:
        headers = {"Reply-To": reply_email}
    else:
        headers = {}
    mail = EmailMultiAlternatives(
        "{}{}".format(settings.EMAIL_SUBJECT_PREFIX, subject),
        message,
        settings.SERVER_EMAIL,
        [a[1] for a in settings.MANAGERS],
        connection=connection,
        headers=headers,
    )
    if html_message:
        mail.attach_alternative(html_message, "text/html")
    mail.send(fail_silently=fail_silently)
コード例 #21
0
ファイル: views.py プロジェクト: moskrc/django-init
def index(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():


            t = loader.get_template('feedback/emails/body.txt')
            c = {
                'data': form.cleaned_data,
                'site': Site.objects.get_current(),
                'date': datetime.now(),
            }

            subject = render_to_string('feedback/emails/subject.txt', c).replace('\n','')
            html_body = t.render(Context(c))
            text_body = strip_tags(html_body)

            msg = EmailMultiAlternatives(subject, text_body, form.cleaned_data['email'], settings.MANAGERS)
            msg.attach_alternative(html_body, "text/html")
            msg.send()

            form = ContactForm()

            messages.success(request, "Ваше сообщение успешно отправлено!")

    else:
        form = ContactForm()

    return render(request, 'feedback/index.html', {'form':form})
コード例 #22
0
ファイル: views.py プロジェクト: gregorylburgess/makahiki
def send_feedback(request):
    """send feedback."""
    if request.method == "POST":
        form = FeedbackForm(request.POST)
        if form.is_valid():
            html_message = render_to_string(
                "email/ask_admin.html",
                {"user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"]},
            )
            message = render_to_string(
                "email/ask_admin.txt",
                {"user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"]},
            )

            challenge = challenge_mgr.get_challenge()
            # Using adapted version from Django source code
            subject = u"[%s] %s asked a question" % (challenge.competition_name, request.user.get_profile().name)

            if challenge.email_enabled:
                mail = EmailMultiAlternatives(
                    subject, message, FROM_EMAIL, [challenge.contact_email], headers={"Reply-To": request.user.email}
                )

                mail.attach_alternative(html_message, "text/html")
                mail.send()

            # print "email sent %s" % html_message
            if request.is_ajax():
                return HttpResponse(json.dumps({"success": True}), mimetype="application/json")

    raise Http404
コード例 #23
0
ファイル: __init__.py プロジェクト: StanislavKraev/rekvizitka
    def execute(self):
        print >> sys.stdout, 'Executing DeferredNotificationsTask'

        start = time.time()
        notifications = Notification.objects.collection.find({'is_sent': False,
                                                            'send_date': {'$lte': timezone.now()}
                                                             }).sort('send_date', -1)
        for notification in notifications:
            msg = EmailMultiAlternatives(notification['subject'],
                                         notification['message_text'],
                                         settings.EMAIL_HOST_USER,
                                         [notification['email'], ], [])

            if len(notification['message_html']):
                msg.attach_alternative(notification['message_html'], "text/html")

#           mustdo: implement attaches
#            attaches = NotificationAttaches.objects.filter(nid=notification)
#            sys.stdout.write(u'    Find %d attache files\n' % attaches.count())
#
#            if attaches.count():
#                for attache in attaches:
#                    sys.stdout.write(u'    Attache file: %s\n' % attache.file)
#                    msg.attach_file(attache.file)

            msg.send()

            Notification.objects.update({'_id' : notification['_id']}, {'$set' : {'is_sent' : True}})

            finish = time.time()
            run_time = finish - start
            if run_time > SECONDS_LIMIT:
                return
コード例 #24
0
def send_mail_account_confirmation(user, code, marketplace):
    """
        Send message to the user to confirm your account
    """
    link = "http://www.%s/buy/confirmemail/%s/" % (marketplace.base_domain,
                                                   code)

    subject = "%s Account Confirmation" % marketplace.name

    text_content = _("""
    Hi %(username)s,
    
    You recently registered at %(marketplace_name)s. Please confirm your account by following this link: %(link)s
                       
    Thanks.
                       
    %(marketplace_name)s Team.""") % {
        'username': user.username,
        'link': link,
        'marketplace_name': marketplace.name
    }

    msg = EmailMultiAlternatives(
        subject,
        text_content,
        settings.EMAIL_FROM, [user.email, settings.EMAIL_FROM],
        headers={'X-SMTPAPI': '{\"category\": \"Account Confirmation\"}'})
    logging.critical(text_content)

    try:
        msg.send()
    except:
        logging.exception("failure sending mail")
コード例 #25
0
ファイル: views.py プロジェクト: keokilee/makahiki
def send_feedback(request):
  if request.method == "POST":
    form = FeedbackForm(request.POST)
    if form.is_valid():
      html_message = render_to_string("email/ask_admin.html", {
          "user": request.user,
          "url": form.cleaned_data["url"],
          "question": form.cleaned_data["question"],
      })
      message = render_to_string("email/ask_admin.txt", {
          "user": request.user,
          "url": form.cleaned_data["url"],
          "question": form.cleaned_data["question"],
      })
      
      # Using adapted version from Django source code
      current_site = Site.objects.get(id=settings.SITE_ID)
      subject = u'[%s] %s asked a question' % (current_site.domain, request.user.get_profile().name)
      mail = EmailMultiAlternatives(subject, message, FROM_EMAIL, 
          [settings.CONTACT_EMAIL,], headers={"Reply-To": request.user.email})
      
      mail.attach_alternative(html_message, 'text/html')
      mail.send()
      
      # mail_admins("[%s] Message for admins" % current_site.domain,
      #           message, html_message=html_message, headers={'Reply-To': request.user.email})
          
      if request.is_ajax():
        return HttpResponse(json.dumps({"success": True}), mimetype="application/json")
      
      return HttpResponseRedirect(form.cleaned_data["url"])
  
  raise Http404
コード例 #26
0
def mail_admins_with_from(subj,
                          msg,
                          from_addr,
                          fail_silently=False,
                          connection=None,
                          html_message=None):
    """
    Mail admins but allow specifying of from address.
    """

    if not settings.ADMINS:
        return

    # set plain text message
    strip_tags(msg)
    mail = EmailMultiAlternatives(
        f"{settings.EMAIL_SUBJECT_PREFIX}{subj}",
        msg,
        from_addr,
        [a[1] for a in settings.ADMINS],
        connection=connection,
    )

    # attach html message
    mail.attach_alternative(msg.replace("\n", "<br />\n"), "text/html")

    mail.send(fail_silently=fail_silently)
コード例 #27
0
def send_mail_account_confirmation(user, code, marketplace):
    """
        Send message to the user to confirm your account
    """
    link = "http://www.%s/buy/confirmemail/%s/" % (marketplace.base_domain , code)
    
    subject = "%s Account Confirmation" % marketplace.name    
    
    text_content = _("""
    Hi %(username)s,
    
    You recently registered at %(marketplace_name)s. Please confirm your account by following this link: %(link)s
                       
    Thanks.
                       
    %(marketplace_name)s Team.""") % {'username': user.username, 'link': link, 'marketplace_name': marketplace.name}
    
    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 settings.EMAIL_FROM,
                                 [user.email, settings.EMAIL_FROM],
                                 headers={'X-SMTPAPI': '{\"category\": \"Account Confirmation\"}'})
    logging.critical(text_content);
    
    try:
        msg.send()
    except:
        logging.exception("failure sending mail")
コード例 #28
0
ファイル: views.py プロジェクト: stfluckly29/Django-Angular
    def forget_password(self, request):
        email = request.DATA.get('email', False)

        # validate posted params
        errors = {}
        if not email:
            errors['email'] = 'Required'

        pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
        if not re.match(pattern, email):
            errors['email'] = 'Please input valid email address.'

        if not errors:
            user = User.objects.filter(username=email).first()
            if user:
                user_code, created = UserCode.objects.get_or_create(user=user, code=random_key(), is_signup=False)
                reg_url = settings.DOMAIN + 'api/password_reset/' + user_code.code + '/'
                plaintext = get_template('pw_reset.txt')
                htmly = get_template('pw_reset.html')
                d = Context({'url': reg_url})

                subject, from_email, to = 'Password Reset [InAppTranslation]', '*****@*****.**', user.username
                text_content = plaintext.render(d)
                html_content = htmly.render(d)
                msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
                msg.attach_alternative(html_content, "text/html")
                msg.send()

                return Response({'status': 'success'})
            else:
                errors['email'] = "We can't find any user with the email."

        return Response(errors, status=status.HTTP_400_BAD_REQUEST)
コード例 #29
0
ファイル: views.py プロジェクト: dany431/cityfusion
def feedback(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            hostname = request.get_host()
            time = datetime.datetime.now()

            if settings.MANAGERS:
                subject = '%s / Feedback' % hostname
                message_data = form.cleaned_data.copy()
                message_data['time'] = time.strftime('%d-%m-%Y, %-1I:%M %p')
                message = '''From: %(name)s <%(email)s>\n\nType: %(type)s\n\nTime: %(time)s
                            \nText: %(comments)s''' % message_data
                mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
                                              message, message_data['email'], [a[1] for a in settings.MANAGERS],
                                              headers = {'Reply-To': message_data['email']})
                mail.send(fail_silently=True)

            feedback = Feedback(time=time, **form.cleaned_data)
            feedback.save()
            return HttpResponseRedirect( reverse('feedback_thanks') )
    else:
        form = ContactForm()

    try:
        page_info = Page.objects.get(alias='feedback')
    except Page.DoesNotExist:
        page_info = {}

    return render_to_response("feedback/contact.html",
                              {'form': form,
                               'page_info': page_info},
                              context_instance=RequestContext(request))
コード例 #30
0
ファイル: handleemail.py プロジェクト: KohoVolit/write-it
    def handle(self, *args, **options):
        lines = sys.stdin.readlines()
        if settings.INCOMING_EMAIL_LOGGING == 'ALL':
            if not settings.ADMINS:
                return
            text_content = "New incomming email"
            subject = "New incomming email"

            mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
                text_content,  # content
                settings.DEFAULT_FROM_EMAIL,  # From
                [a[1] for a in settings.ADMINS]  # To
                )
            mail.attach('mail.txt', ''.join(lines), 'text/plain')
            mail.send()

        handler = EmailHandler(answer_class=AnswerForManageCommand)
        try:
            answer = handler.handle(lines)
            answer.send_back()
        except CouldNotFindIdentifier:
            pass
        except:
            tb = traceback.format_exc()
            text_content = "Error the traceback was:\n" + tb
            #mail_admins('Error handling incoming email', html_message, html_message=html_message)
            subject = "Error handling incoming email"
            mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
                text_content,  # content
                settings.DEFAULT_FROM_EMAIL,  # From
                [a[1] for a in settings.ADMINS],  # To
                )
            mail.attach('mail.txt', ''.join(lines), 'text/plain')
            mail.send()
コード例 #31
0
ファイル: mailer.py プロジェクト: pdelkowski/expenses
 def send(self):
     try:
         mail = EmailMultiAlternatives(self.subject, self.html_body, self.sender, self.recipients, connection=self.connection)
         mail.attach_alternative(self.html_body, 'text/html')
         mail.send()
     except Exception as e:
         print "Unexpected error while sending email:", e
コード例 #32
0
def payment_failure(user, plan, attempt):
    """
    notification of when the attempt of Payment from the User fails
    :param user:
    :param plan:
    :param attempt:
    :return:
    """
    try:
        to = user.email
        data = {'domain_fron': 'app.ezonseller.com',
                'url': settings.URL,
                'username': user.username,
                'msg': 'Payment Failure',
                'plan': plan,
                }
        subject, from_email = data['msg'], EMAIL_HOST_USER
        if attempt != 0:
            text_content = render_to_string("email/payment_fail.html", data)
            html_content = render_to_string("email/payment_fail.html", data)
        else:
            text_content = render_to_string("email/disable_user.html", data)
            html_content = render_to_string("email/disable_user.html", data)
        send = EmailMultiAlternatives(subject, text_content, from_email, [to],
                                      headers={'From': 'Ezonseller <'+from_email+'>',
                                               'Reply-to': 'Ezonseller <'+from_email+'>'})
        send.attach_alternative(html_content, "text/html")
        send.send()
        return True
    except:
        return False
コード例 #33
0
def send_email_charge_failed(sender, **kwargs):
    st_charge = kwargs.get('stripe_charge')
    if st_charge:
        payment = st_charge.payment
        invoice = Invoice.objects.get_invoice_by_payment(payment=payment)

        customer = invoice.proposal.event.customer
        email = customer.email

        subject = "Intento de pago invalido"
        from_email = settings.ADMIN_EMAIL
        to = email
        template = loader.get_template("base/email/stripe/charge_failed.html")

        stripe_json_error = kwargs.get('stripe_json_error')
        context = Context({
            'customer': customer,
            'invoice': invoice,
            'charge': st_charge,
            'stripe_json_error': stripe_json_error
        })
        text_content = template.render(context)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        try:
            msg.send(fail_silently=False)

            # if kwargs has task notify task done
        except SMTPException as e:
            pass
コード例 #34
0
ファイル: utilities.py プロジェクト: singuliere/opencraft
    def _mail_admins_with_attachment(subject,
                                     message,
                                     fail_silently=True,
                                     connection=None,
                                     html_message=None,
                                     attachments=None):
        """ Mimics mail_admins, but allows attaching files to the message"""
        if not settings.ADMINS:
            return

        mail = EmailMultiAlternatives(
            "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
            message,
            settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
            connection=connection)

        if html_message:
            mail.attach_alternative(html_message, "text/html")

        if attachments:
            for attachment_name, attachment_content, attachment_mime in attachments:
                mail.attach(attachment_name, attachment_content,
                            attachment_mime)

        mail.send(fail_silently=fail_silently)
コード例 #35
0
def send_email_subscription_past_due_active(sender, **kwargs):
    st_subscription = kwargs.get('subscription')
    if st_subscription:
        st_customer = st_subscription.stripecustomer
        business = Business.objects.get_by_stripe_customer(
            stripe_customer=st_customer)
        email = business.contact_email()

        subject = "Probelma resuelto"
        from_email = settings.ADMIN_EMAIL
        to = email
        template = loader.get_template(
            "base/email/stripe/past_due_to_active_subscription.html")

        context = Context({
            'business': business,
            'subscription': st_subscription
        })
        text_content = template.render(context)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        try:
            msg.send(fail_silently=False)

            # if kwargs has task notify task done
        except SMTPException as e:
            pass
コード例 #36
0
ファイル: auth.py プロジェクト: vanderheyde/ecm
def alert_user_for_invalid_apis(user, invalid_apis):
    from ecm.views import HTML
    ctx_dict = {
        'host_name': settings.EXTERNAL_HOST_NAME,
        'use_https': settings.USE_HTTPS,
        'user_name': user.username,
        'invalid_apis': invalid_apis
    }
    dummy_request = HttpRequest()
    dummy_request.user = AnonymousUser()

    subject = render_to_string('ecm/common/email/invalid_api_subject.txt',
                               ctx_dict, Ctx(dummy_request))
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    txt_content = render_to_string('ecm/common/email/invalid_api.txt',
                                   ctx_dict, Ctx(dummy_request))
    html_content = render_to_string('ecm/common/email/invalid_api.html',
                                    ctx_dict, Ctx(dummy_request))

    msg = EmailMultiAlternatives(subject, body=txt_content, to=[user.email])
    msg.attach_alternative(html_content, mimetype=HTML)
    msg.send()

    LOG.warning(
        "API credentials for '%s' are invalid. User notified by email." %
        user.username)
コード例 #37
0
def send_email_payment_failed(sender, **kwargs):
    st_invoice = kwargs.get('stripe_invoice')
    last_attempt = kwargs.get('last_attempt')
    if st_invoice:
        st_subscription = st_invoice.subscription
        st_customer = st_subscription.stripecustomer
        business = Business.objects.get_by_stripe_customer(
            stripe_customer=st_customer)
        email = business.contact_email()

        subject = "Fallo al cobrar por su subscripcion"
        from_email = settings.ADMIN_EMAIL
        to = email
        template = loader.get_template("base/email/stripe/invoice_failed.html")

        context = Context({
            'business': business,
            'subscription': st_subscription,
            'stripe_invoice': st_invoice,
            'last_attempt': last_attempt
        })
        text_content = template.render(context)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        try:
            msg.send(fail_silently=False)

            # if kwargs has task notify task done
        except SMTPException as e:
            pass
コード例 #38
0
ファイル: views.py プロジェクト: macik/weblate
def mail_admins_contact(request, subject, message, context, sender):
    '''
    Sends a message to the admins, as defined by the ADMINS setting.
    '''
    weblate.logger.info(
        'contact from from %s: %s',
        sender,
        subject,
    )
    if not settings.ADMINS:
        messages.error(
            request,
            _('Message could not be sent to administrator!')
        )
        weblate.logger.error(
            'ADMINS not configured, can not send message!'
        )
        return

    mail = EmailMultiAlternatives(
        u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject % context),
        message % context,
        to=[a[1] for a in settings.ADMINS],
        headers={'Reply-To': sender},
    )

    mail.send(fail_silently=False)

    messages.info(
        request,
        _('Message has been sent to administrator.')
    )
コード例 #39
0
def send_email_trail_will_end(sender, **kwargs):
    st_subscription = kwargs.get('subscription')
    if st_subscription:
        trial_end = kwargs.get('trial_end')
        st_customer = st_subscription.stripecustomer
        business = Business.objects.get_by_stripe_customer(
            stripe_customer=st_customer)
        email = business.contact_email()

        subject = "Se acaba el periodo se prueba"
        from_email = settings.ADMIN_EMAIL
        to = email
        template = loader.get_template("base/email/stripe/trial_will_end.html")

        context = Context({
            'business': business,
            'subscription': st_subscription,
            'trial_end': trial_end
        })
        text_content = template.render(context)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        try:
            msg.send(fail_silently=False)

            # if kwargs has task notify task done
        except SMTPException as e:
            pass
コード例 #40
0
ファイル: views.py プロジェクト: fesquivelc/appjaveros
def contacto_view(request):
    info_enviado = False
    email = ''
    titulo = ''
    contenido = ''

    if request.method == 'POST':
        formulario = ContactoForm(request.POST)
        if formulario.is_valid():
            info_enviado = True
            email = formulario.cleaned_data['email']
            titulo = formulario.cleaned_data['titulo']
            contenido = formulario.cleaned_data['contenido']

            #configuracion para enviar el mensaje a GMAIL
            html_content = 'Informacion recibida <br/> <br/> <h3> ******* Mensaje de %s ******* </h3> <br/> <br/>' \
                           '<h4>Titulo: %s </h4>' \
                           '<p>%s</p>' % (email, titulo, contenido)

            to = '*****@*****.**'
            msje = EmailMultiAlternatives('Correo de contacto', html_content, '*****@*****.**', [to])
            msje.attach_alternative(html_content, 'text/html')
            msje.send()
    else:
        formulario = ContactoForm()
    ctx = {'enviado': info_enviado, 'email': email, 'titulo': titulo, 'contenido': contenido, 'form': formulario}
    return render_to_response('contacto.html', ctx, context_instance=RequestContext(request))
コード例 #41
0
    def post(self, request, id, format=None):

        user = request.user
        print(user.email, user.username)
        token = self.make_token(7)
        try:
            token_obj = Token.objects.get(email=user.email,
                                          username=user.username)
            token_obj.token = token
            token_obj.save()
        except Token.DoesNotExist:
            Token.objects.create(email=user.email,
                                 username=user.username,
                                 token=token)

        # 메일 발송
        # TODO 메일 템플릿 바꿔줘야함
        html_content = render_to_string('mail_template.html', {'token': token})
        email = EmailMultiAlternatives('[연하대] 인증 메일', to=[user.email])
        email.attach_alternative(html_content, "text/html")
        email.send()

        return Response(status=status.HTTP_201_CREATED,
                        data={
                            "success": True,
                            "message": "메일이 발송되었습니다.",
                            'data': token
                        })
コード例 #42
0
ファイル: views.py プロジェクト: likemike91/weblate
def mail_admins_contact(request, subject, message, context, sender, to):
    """Send a message to the admins, as defined by the ADMINS setting."""
    LOGGER.info("contact form from %s", sender)
    if not to and settings.ADMINS:
        to = [a[1] for a in settings.ADMINS]
    elif not settings.ADMINS:
        messages.error(request, _("Could not send message to administrator."))
        LOGGER.error("ADMINS not configured, cannot send message")
        return

    mail = EmailMultiAlternatives(
        "{}{}".format(settings.EMAIL_SUBJECT_PREFIX, subject % context),
        "{}\n{}".format(
            message % context,
            TEMPLATE_FOOTER.format(
                address=get_ip_address(request),
                agent=get_user_agent(request),
                username=request.user.username,
            ),
        ),
        to=to,
        headers={"Reply-To": sender},
    )

    mail.send(fail_silently=False)

    messages.success(
        request,
        _("Your request has been sent, you will shortly hear from us."))
コード例 #43
0
ファイル: tasks.py プロジェクト: knyazz/gbWeb001
def send_email(self,
               subject,
               text_content,
               recipients,
               html_content=None,
               attachments=None,
               reply_to=None):
    logger.info("sending email '%s'..." % subject)
    if reply_to is None:
        reply_to = settings.NO_REPLY_EMAIL

    _recipients = filter(None, recipients)
    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 settings.NO_REPLY_EMAIL,
                                 _recipients,
                                 reply_to=[reply_to])
    if html_content:
        logger.info("attaching HTML alternative")
        msg.attach_alternative(html_content, "text/html")
    if attachments:
        for a in attachments:
            logger.info("attaching file: " + a.filename)
            msg.attach(a.filename, a.file, a.mime)
    if _recipients:
        msg.send()
        logger.info("sent successfully")
コード例 #44
0
ファイル: sendemail.py プロジェクト: Srbpunyani/yoolotto
def common_send_email(subject, text_template_path, html_template_path,
                      context_data, recipients, from_email=None):
    """
    This method is a common method to send email via the bhane system.
    """
    coupon_obj = context_data['coupon_obj']
    if not from_email:
        from_email = DEFAULT_FROM_EMAIL

    #get templates from file system
    text_raw_content = get_template(text_template_path)                    
    try:
        html_raw_content = get_template(coupon_obj.vendor.email_content.path)#will return absolute path
    except:
    	html_raw_content = get_template(html_template_path)#else pickup common_vendor_email.html
    #render the raw data in the template
    d = Context(context_data)
    text_content = text_raw_content.render(d)
    html_content = html_raw_content.render(d)

    #contstruct the message and send it
    msg = EmailMultiAlternatives(subject, text_content, from_email, recipients)
    
    if coupon_obj.image.name:
        msg.attach_file(coupon_obj.image.path)
    msg.attach_alternative(html_content, "text/html")
    msg.send()
コード例 #45
0
    def handle(self, *args, **options):
        voting_enabled = settings.VOTING_ENABLED
        if not voting_enabled:
            print('Voting is disabled')
            return

        vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user')

        txt_template = get_template('voting/email/vote_invite.txt')
        html_template = get_template('voting/email/vote_invite.html')

        for vote_token in vote_tokens:
            context = Context({'token': vote_token})
            txt = txt_template.render(context)
            html = html_template.render(context)
            msg = EmailMultiAlternatives(
                'Community voting open',
                txt,
                'WebCamp Zagreb <*****@*****.**>',
                [vote_token.user.email],
            )

            msg.attach_alternative(html, "text/html")
            msg.send()

            print("Voting email sent to %r" % vote_token.user.email)

            vote_token.token_sent = datetime.datetime.now()
            vote_token.save()
コード例 #46
0
    def send_notification_email(self):
        # TODO this could be async to avoid too long api calls in case of mail server issue
        serializer = ActionPointMailSerializer(self, context={})

        recipient = self.person_responsible.email
        cc = self.assigned_by.email
        subject = '[eTools] ACTION POINT ASSIGNED to {}'.format(
            self.person_responsible)
        url = 'https://{host}/t2f/action-point/{action_point_id}/'.format(
            host=settings.HOST, action_point_id=self.id)
        trip_url = 'https://{host}/t2f/edit-travel/{travel_id}'.format(
            host=settings.HOST, travel_id=self.travel.id)
        html_content = render_to_string('emails/action_point_assigned.html', {
            'action_point': serializer.data,
            'url': url,
            'trip_url': trip_url
        })

        # TODO what should be used?
        sender = settings.DEFAULT_FROM_EMAIL
        msg = EmailMultiAlternatives(subject, '', sender, [recipient], cc=[cc])
        msg.attach_alternative(html_content, 'text/html')

        try:
            msg.send(fail_silently=False)
        except ValidationError:
            log.exception(u'Was not able to send the email.')
コード例 #47
0
def send_active_email(active_form, user_email):
    subject, form_email, to = u'数据服务平台-激活邮件', '*****@*****.**', user_email
    text_content = u'数据服务平台-激活邮件'
    html_content = active_form
    msg = EmailMultiAlternatives(subject, text_content, form_email, [to])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()
コード例 #48
0
ファイル: email.py プロジェクト: cumtjie/commcarehq-venv
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=None):
    if not text_content:
        text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE',
                               NO_HTML_EMAIL_MESSAGE)

    # If you get the return_path header wrong, this may impede mail delivery. It appears that the SMTP server
    # has to recognize the return_path as being valid for the sending host. If we set it to, say, our SMTP
    # server, this will always be the case (as the server is explicitly serving the host).
    if email_from is None:
        #todo: verify that this is even necessary here since it seems like email_return_path == email_from
        email_return_path = getattr(settings, 'EMAIL_RETURN_PATH', None)
        if email_return_path is None:
            email_return_path = settings.EMAIL_LOGIN

        email_from = getattr(settings, 'EMAIL_FROM', None)
        if email_from is None:
            email_from = email_return_path
    else:
        email_return_path = email_from

    from_header = {'From': email_from}  # From-header
    connection = get_connection()
    
    msg = EmailMultiAlternatives(subject, text_content, email_return_path, [recipient], headers=from_header, connection=connection, cc=cc)
    msg.attach_alternative(html_content, "text/html")
    msg.send()
コード例 #49
0
ファイル: views.py プロジェクト: brettg381/PaycheckCalc-Py
def recommend(request):

    data = request.POST
    if "clients" in data:
        bcc = ['*****@*****.**', '*****@*****.**']
        clients = data['clients'].split(",")
        for client in clients:
            to = client
            from_email = settings.DEFAULT_FROM_EMAIL

            email = data['email']
            message = data['message']

            subject = "Intuit Easy Paycheck"
            text_content = render_to_string('email/recommend.txt', {
                'email': email,
                'message': message
            })
            html_content = render_to_string('email/recommend.html', {
                'email': email,
                'message': message
            })

            msg = EmailMultiAlternatives(subject,
                                         text_content,
                                         from_email, [to],
                                         bcc=bcc)
            msg.attach_alternative(html_content, "text/html")
            msg.send()

    return HttpResponse(json.dumps({
        'status': 'ok',
    }),
                        mimetype="application/json")
コード例 #50
0
def mail_admins_contact(request, subject, message, context, sender, to):
    """Send a message to the admins, as defined by the ADMINS setting."""
    LOGGER.info('contact form from %s', sender)
    if not to and settings.ADMINS:
        to = [a[1] for a in settings.ADMINS]
    elif not settings.ADMINS:
        messages.error(request,
                       _('Message could not be sent to administrator!'))
        LOGGER.error('ADMINS not configured, can not send message!')
        return

    mail = EmailMultiAlternatives(
        '{0}{1}'.format(settings.EMAIL_SUBJECT_PREFIX, subject % context),
        '{}\n{}'.format(
            message % context,
            TEMPLATE_FOOTER.format(
                address=get_ip_address(request),
                agent=get_user_agent(request),
                username=request.user.username,
            ),
        ),
        to=to,
        headers={'Reply-To': sender},
    )

    mail.send(fail_silently=False)

    messages.success(request, _('Message has been sent to administrator.'))
コード例 #51
0
ファイル: views.py プロジェクト: brettg381/PaycheckCalc-Py
def contact(request):

    data = request.POST
    bcc = ['*****@*****.**', '*****@*****.**']
    to = ['*****@*****.**']
    from_email = settings.DEFAULT_FROM_EMAIL

    email = data['email']
    message = data['message']

    subject = "Contact from Intuit Easy Paycheck"
    text_content = render_to_string('email/contact.txt', {
        'email': email,
        'message': message
    })
    html_content = render_to_string('email/contact.html', {
        'email': email,
        'message': message
    })

    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 from_email,
                                 to,
                                 bcc=bcc)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

    return HttpResponse(json.dumps({
        'status': 'ok',
    }),
                        mimetype="application/json")
コード例 #52
0
ファイル: models.py プロジェクト: sanfutou/dannysite.com
    def send(self):
        try:
            model_name = ContentType.objects.get_for_model(self.related_object)
        except:
            set_log('info', 'The related object has been deleted when trying to send mail to {0}'.format(self.email_addresses))
            self.is_sent = True
            return True

        emails = self.email_addresses.split(',')
        sended = []

        for email in emails:
            subject, text, html = getattr(self, '_'.join(['_pack', model_name.name.lower().replace(' ', '_')]))(email)

            message = EmailMultiAlternatives(subject, text,
                                             settings.DEFAULT_FROM_EMAIL,
                                             [email])
            if html:
                message.attach_alternative(html, "text/html")

            try:
                message.send()
            except Exception, e:
                set_log('error', 'Mail Server eror: ' + str(e))
                self.email_addresses = ','.join(set(emails) - set(sended))
                return False
            else:
                sended.append(email)

            self.mark_sent()
コード例 #53
0
ファイル: email.py プロジェクト: inmagik/dimagi-utils
def send_HTML_email(subject,
                    recipient,
                    html_content,
                    text_content=None,
                    cc=None,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=None,
                    bcc=None):
    if not text_content:
        text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE',
                               NO_HTML_EMAIL_MESSAGE)

    from_header = {'From': email_from}  # From-header
    connection = get_connection()
    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 email_from, [recipient],
                                 headers=from_header,
                                 connection=connection,
                                 cc=cc,
                                 bcc=bcc)
    for file in (file_attachments or []):
        if file:
            msg.attach(file["title"], file["file_obj"].getvalue(),
                       file["mimetype"])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
コード例 #54
0
def mail_username_retrieve(email, secret):
    """
    Send an email to the specified email address containing
    the url for username retrieval.

    Arguments:
        - email <str>
        - secret <str>: username retrieval secret in the user's session
    """

    msg = loader.get_template("email/username-retrieve.txt").render({
        "email":
        email,
        "secret":
        secret,
        "username_retrieve_url":
        "{}/username-retrieve/complete?secret={}".format(
            settings.BASE_URL, secret),
    })

    subject = "PeeringDB username retrieval"

    mail = EmailMultiAlternatives(subject, msg, settings.DEFAULT_FROM_EMAIL,
                                  [email])
    mail.send(fail_silently=False)
コード例 #55
0
ファイル: email.py プロジェクト: HengeSense/moocng
def send_contact_message(communication_type, sender_username, sender_email,
                         message, fail_silently=False, connection=None):

    subject = "%s | %s <%s>" % (communication_type.title,
                                sender_username,
                                sender_email)
    headers = {'Reply-To': sender_email}

    destination = communication_type.destination
    if not destination:
        if not settings.MANAGERS:
            logger.error('Could not send a contact message because there is no destination email configured neither in the communication type or the MANAGERS setting.')
            return
        else:
            to = [m[1] for m in settings.MANAGERS]
    else:
        to = [destination]

    mail = EmailMultiAlternatives(
        u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
        message,
        settings.SERVER_EMAIL,
        to,
        connection=connection,
        headers=headers,
    )
    mail.send(fail_silently=fail_silently)
コード例 #56
0
ファイル: forms.py プロジェクト: Gargamel1989/Seasoning-old
    def save(self, domain_override=None,
             subject_template_name='authentication/password_reset_subject.txt',
             email_template_name='registration/password_reset_email.html',
             use_https=False, token_generator=default_token_generator,
             from_email=None, request=None):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        for user in self.users_cache:
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            c = {
                'email': user.email,
                'domain': domain,
                'site_name': site_name,
                'uid': int_to_base36(user.pk),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': use_https and 'https' or 'http',
            }
            subject = loader.render_to_string('authentication/password_reset_subject.txt', c)
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines())
            message_text = loader.render_to_string('authentication/password_reset_email.txt', c)
            message_html = loader.render_to_string('authentication/password_reset_email.html', c)            
            

            msg = EmailMultiAlternatives(subject, message_text, settings.DEFAULT_FROM_EMAIL, [self.user.email])
            msg.attach_alternative(message_html, "text/html")
            msg.send()
コード例 #57
0
ファイル: deploy_notice.py プロジェクト: madhu05/opadmin
def deploy_mail(to_mail, cc_mail, *args):
    subject, body = gen_body(*args)
    msg = EmailMultiAlternatives(subject,
                                 body,
                                 to=[i.strip() for i in to_mail.split(',')],
                                 cc=[i.strip() for i in cc_mail.split(',')])
    msg.send()
コード例 #58
0
ファイル: views.py プロジェクト: blockgiven/weblate
def mail_admins_contact(request, subject, message, context, sender):
    '''
    Sends a message to the admins, as defined by the ADMINS setting.
    '''
    weblate.logger.info(
        'contact from from %s: %s',
        sender,
        subject,
    )
    if not settings.ADMINS:
        messages.error(
            request,
            _('Message could not be sent to administrator!')
        )
        weblate.logger.error(
            'ADMINS not configured, can not send message!'
        )
        return

    mail = EmailMultiAlternatives(
        u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject % context),
        message % context,
        to=[a[1] for a in settings.ADMINS],
        headers={'Reply-To': sender},
    )

    mail.send(fail_silently=False)

    messages.success(
        request,
        _('Message has been sent to administrator.')
    )
コード例 #59
0
    def form_valid(self, form):
        data = form.cleaned_data
        email = data['email']

        try:
            user = User.objects.get(email=email)
            password = User.objects.make_random_password()
            user.set_password(password)
            user.save()

            t = loader.get_template('commerce/mails/recover-password.html')
            c = Context({
                'host': COMMERCE_URL,
                'password': password,
            })

            message = EmailMultiAlternatives(
                _(u'Password recover'), '', COMMERCE_EMAIL_FROM, [user.email])
            message.attach_alternative(t.render(c), 'text/html')
            message.send()
        except ObjectDoesNotExist:
            pass

        messages.success(
            self.request,
            _(u'New password was successfully sent on your email.'))
        return super(RecoverView, self).form_valid(form)