Beispiel #1
0
def preset_submit(request):
    if request.method == "POST":
        form = SubmitForm(request.POST, request.FILES)
        
        if form.is_valid():
            preset = request.FILES["preset_file"]
            message = EmailMessage(**{
                "subject": "[Arista] Preset for %s" % preset.name[:-8],
                "body": "A user has uploaded a new preset!",
                "from_email": form.cleaned_data["email"],
                "to": [x[1] for x in settings.ADMINS],
                "attachments": [
                    (preset.name, preset.read(), "application/x-bzip-compressed-tar"),
                ],
            })
            
            message.send()
        
            return HttpResponseRedirect("/presets/?thanks=1")
    else:
        form = SubmitForm()
    
    return render(request, "presets/submit.html", {
        "form": form,
    })
Beispiel #2
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', 'from@example.com', ['other@example.com'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertMessageHasHeaders(message, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable'),
            ('Subject', 'Subject'),
            ('From', 'from@example.com'),
            ('To', 'other@example.com')})
        self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content, 'from@example.com', ['to@example.com'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        payload0 = msg.message().get_payload(0)
        self.assertMessageHasHeaders(payload0, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload0.as_bytes().endswith(b'\n\nFirstname S=FCrname is a great guy.'))
        payload1 = msg.message().get_payload(1)
        self.assertMessageHasHeaders(payload1, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/html; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload1.as_bytes().endswith(b'\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'))
Beispiel #3
0
 def test_multiple_recipients(self):
     email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com'])
     message = email.message()
     self.assertEqual(message['Subject'], 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], 'from@example.com')
     self.assertEqual(message['To'], 'to@example.com, other@example.com')
def contact(request):
    form_class = ContactForm

    # new logic!
    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = form.cleaned_data['contact_name']
            contact_email = form.cleaned_data['contact_email']
            form_content = form.cleaned_data['content']

            # email the profile with the contact info
            template = get_template('contact_template.txt')

            context = Context({
                'contact_name': contact_name,
                'contact_email': contact_email,
                'form_content': form_content,
            })
            content = template.render(context)

            email = EmailMessage(
                'New contact form submission',
                content,
                'Your website <hi@weddinglovely.com>',
                ['youremail@gmail.com'],
                headers = {'Reply-To': contact_email }
            )
            email.send()
            return redirect('contact')

    return render(request, 'contact.html', {
        'form': form_class,
    })
Beispiel #5
0
def request_access(request, requester=None, requestee=None):

	# send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False)


	'''
	- need to flag the requester as having requested a specific group
	- need to capture name, email, username, group name, group_pk
	- how do I capture the target recipient's email to populate in the "to" field 
	'''
	show_this_group = request.session['show_this_group']

	requester_name = '%s %s' % (User.objects.get(username=requester).first_name, User.objects.get(username=requester).last_name)
	requester_email = User.objects.get(username=requester).email
	requester_username = User.objects.get(username=requester).username
	requested_group_name = Group.objects.get(name=show_this_group)
	requested_group_pk = requested_group_name.id



	message = EmailMessage('Approve access for %s - %s' % (requester_name, requester_email), 'Click this link ____ to approve access for %s (%s, %s) to the group %s at primary key %s.' % (requester_name, requester_username, requester_email, requested_group_name, requested_group_pk), 'archimedes@careerhoot.com', [], ['andrewlchen@gmail.com'])

	message.send()

	return HttpResponseRedirect('/introkick/home')
Beispiel #6
0
def server_error(request):
    """Own view in order to pass RequestContext and send an error message.
    """
    exc_type, exc_info, tb = sys.exc_info()
    response = "%s\n" % exc_type.__name__
    response += "%s\n" % exc_info
    response += "TRACEBACK:\n"
    for tb in traceback.format_tb(tb):
        response += "%s\n" % tb

    if hasattr(request, 'user') and request.user:
        response += "User: %s\n" % request.user.username

    response += "\nREQUEST:\n%s" % request

    try:
        from_email = settings.ADMINS[0][1]
        to_emails = [a[1] for a in settings.ADMINS]
    except IndexError:
        pass
    else:
        mail = EmailMessage(
            subject="Error LFS", body=response, from_email=from_email, to=to_emails)
        mail.send(fail_silently=True)

    t = loader.get_template('500.html')
    return HttpResponseServerError(t.render(RequestContext(request)))
Beispiel #7
0
    def run(self, submission):
        logger.info('SendSubmissionEmail for submission %s' % (
            submission.id
        ))
        try:
            translation.activate(submission.submission_language)

            email = EmailMessage(
                'Cinema Perpetuum Mobile 2013',
                self.get_email_message(submission),
                'no-reply@filmfest.by',
                [submission.applicant_email],
                list(settings.MAIL_BCC_LIST),
                headers = {'Reply-To': '2013@filmfest.by'})

            email.attach(
                'cpm2013.pdf', self.create_pdf(submission), 'application/pdf'
            )

            email.send()
        except:
            logger.exception('')
            raise
        finally:
            translation.deactivate()
            try:
                submission = Submission.objects.get(pk=submission.pk)
            except Submission.DoesNotExist:
                logger.exception('Failed to update "email sent" status')
            else:
                submission.comment_email_sent = True
                submission.save()
    def do_email_reply(self, comment, content_object, request):
        """Send email notification of a new comment to the authors of
        the previous comments when email notifications have been requested."""
        exclude_list = self.mail_comment_notification_recipients + \
                       [author.email
                        for author in content_object.authors.all()] + \
                       [comment.email]
        recipient_list = set([comment.email
                              for comment in content_object.comments
                              if comment.email]) - \
                              set(exclude_list)

        if recipient_list:
            site = Site.objects.get_current()
            template = loader.get_template('comments/comment_reply_email.txt')
            context = Context({'comment': comment, 'site': site,
                               'protocol': PROTOCOL,
                               'content_object': content_object})
            subject = _('[%(site)s] New comment posted on "%(title)s"') % \
                      {'site': site.name,
                       'title': content_object.title}
            message = template.render(context)
            mail = EmailMessage(subject, message,
                                settings.DEFAULT_FROM_EMAIL,
                                bcc=recipient_list)
            mail.send(fail_silently=not settings.DEBUG)
def notify_about_exception(exception_title):
    """
    If exception is identified as critical - send email to recipients.
    """
    if EXCEPTION_TITLE_WORDS_TO_NOTIFY and EXCEPTION_RECIPIENTS:
        pattern = r'|'.join(EXCEPTION_TITLE_WORDS_TO_NOTIFY)
        search_result = search(pattern, exception_title, I)

        if search_result is not None:
            message_content = (
                "<p>%(body)s</p><p>Server: "
                "<a href='%(protocol)s://%(domain)s'>%(domain)s</a></p>" % (
                    {
                        'body': exception_title,
                        'protocol': settings.SERVER_PROTOCOL,
                        'domain': settings.CURRENT_SERVER_DOMAIN
                    }
                )
            )
            message = EmailMessage(
                "Error Monitor notification",
                message_content,
                settings.EMAIL_HOST_USER,
                EXCEPTION_RECIPIENTS
            )
            message.content_subtype = 'html'
            message.send(fail_silently=True)
Beispiel #10
0
 def request_new_password(self, request):
     email = self.cleaned_data['username']
     try:
         user = EmailUser.objects.get(email=email)
     except:
         raise PermissionDenied
     user.is_active = False
     user.save()
     try:
         tmp = TempUrl.objects.get(email=email)
     except:
         tmp = TempUrl(email=email, first_name=user.first_name, 
                       last_name=user.last_name)
     tmp.hash = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20))
     now = datetime.datetime.utcnow().replace(tzinfo=utc)
     tmp.invited = now
     tmp.created = now
     tmp.used = None
     tmp.save()
     #email...
     p = {'reason':'reset  password', 'service':'Django email username'}
     p['link'] = request.build_absolute_uri(reverse('django_email_user.views.activate_account', kwargs={'hasher': tmp.hash}))
     html = render_to_string('django_email_user/email-invitation.html', p)
     mail = EmailMessage('You have requested a password reset',
             html, '<Django email username>' + settings.EMAIL_HOST_USER,
             [tmp.email])
     mail.content_subtype = "html"
     mail.send()
     return email
Beispiel #11
0
    def send_mail(self, form, files=[]):
        form_data = self.get_form_data(form)
        message = self.compile_message(form_data)
        context_dict = self.get_form_data_dict(form_data)

        import re
        mail_to = re.compile('\s*[,;]+\s*').split(self.mail_to)
        for key, email in enumerate(mail_to):
            mail_to[key] = self.string_template_replace(email, context_dict)

        mail_from = self.mail_from or None
        if mail_from:
            mail_from = self.string_template_replace(mail_from, context_dict)

        if self.mail_subject:
            mail_subject = self.string_template_replace(self.mail_subject, context_dict)
        else:
            mail_subject = self.title

        import logging
        logging.debug('Mail: '+repr(mail_from)+' --> '+repr(mail_to));

        from django.core.mail import EmailMessage
        message = EmailMessage(mail_subject, message, mail_from or None, mail_to)

        if self.mail_uploaded_files:
            for file_path in files:
                message.attach_file(file_path)

        message.send(fail_silently=False)
 def send(self, **kwargs):
     current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
     protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
     activate_url = u"%s://%s%s" % (
         protocol,
         unicode(current_site.domain),
         reverse("account_confirm_email", args=[self.key])
     )
     ctx = {
         "email_address": self.email_address,
         "user": self.email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "key": self.key,
     }
     ext = "html" if settings.EMAIL_CONTENT_HTML else "txt"
     subject = render_to_string(
         "account/email/email_confirmation_subject.{0}".format(ext), ctx)
     subject = "".join(subject.splitlines())  # remove superfluous line breaks
     message = render_to_string(
         "account/email/email_confirmation_message.{0}".format(ext), ctx)
     msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email_address.email])
     if settings.EMAIL_CONTENT_HTML:
         msg.content_subtype = "html"
     msg.send()
     self.sent = timezone.now()
     self.save()
     signals.email_confirmation_sent.send(sender=self.__class__, confirmation=self)
 def send(self, **kwargs):
     protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
     current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
     signup_url = u"%s://%s%s?%s" % (
         protocol,
         unicode(current_site.domain),
         reverse("account_signup"),
         urllib.urlencode({"code": self.code})
     )
     ctx = {
         "signup_code": self,
         "current_site": current_site,
         "signup_url": signup_url,
     }
     ext = "html" if settings.EMAIL_CONTENT_HTML else "txt"
     subject = render_to_string(
         "account/email/invite_user_subject.{0}".format(ext), ctx)
     message = render_to_string(
         "account/email/invite_user.{0}".format(ext), ctx)
     msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
     if settings.EMAIL_CONTENT_HTML:
         msg.content_subtype = "html"
     msg.send()
     self.sent = timezone.now()
     self.save()
     signup_code_sent.send(sender=SignupCode, signup_code=self)
Beispiel #14
0
def enviar_email(from_email, subject, template, tags):
    """Envia o email para o destinatário definido, a partir do template
    definido para ser renderizado. Os argumentos são:
        * from_email - Email do remetente
        * subject - Assunto da Mensagem
        * template - Template que será usado para gerar o corpo
        da mensagem
        * tags - Variáveis de contexto para ser renderizado no
        template.
    """
    if from_email is None:
        raise ValueError("Insira o email do remetente.")
    elif subject is None:
        raise ValueError("Insira o assunto da mensagem.")
    elif template is None:
        raise ValueError(u"Template da mensagem não encontrado")
    elif tags is None:
        raise ValueError("Insira o conteúdo da mensagem.")

    # Gerando a mensagem
    mensagem = render_to_string(template, tags)

    # Enviando a mensagem
    email = EmailMessage(settings.EMAIL_SUBJECT_PREFIX + " " + subject, mensagem,
        from_email, [from_email])
    email.send()
Beispiel #15
0
def send_invitation_key(sender, invitation, **kwargs):
    from django.core.mail import EmailMessage
    body = """
    Hello there,

    This is an invitation to be part of the {group_name} group on a StartupWeekend event.

    Click on the following link to activate your Startup Weekend Manager account:
    
    http://localhost:8000/#!/user/registration?email={email}&code={code}
    

    Best of lucks on th event, and remember: Stop talk, more action!


    --
    Startup Weekend Team
    """.format(group_name=invitation.to.name, email=invitation.email, code=invitation.key)

    print body
    
    msg = EmailMessage(subject="[swmanager] Invitation to an swmanager event",
                         body=body,
                         to=[invitation.email])
                         #bcc=medellin@startupweekend.org)
    print "msg : %s" % msg
    print msg.send()
    print "######## Invitation key: %s" % invitation.key
Beispiel #16
0
    def send_editor_mail(self):
        """
        Send notification mails to all users in group editor.
        Only send if ChangeRequest is not yet accepted
        :return:
        """
        if self.status == ChangeRequest.PENDING:
            editors = User.objects.filter(groups__name='editor')

            body = render_to_string('frontend/email/new_change_request.txt',
                                    {
                                        'change_request': self,
                                        'document_url': self.document_url()
                                    })

            bcc = []
            for editor in editors:
                bcc.append(get_user_email(editor))

            email = EmailMessage(_("New change request", ),
                                 body,
                                 bcc=bcc)
            email.send()
            logger.info("Sent change request notification mail to editors",
                        extra={
                            'body': body,
                            'bcc': bcc,
                        })
Beispiel #17
0
def send_bookmark_reminder_email():
    for profile in UserProfile.objects.all():
        user = profile.user
        # Get all bookmarked events ending in the next 7 days from today
        # What day will it be 7 days from now-
        now = timezone.now().date()
        seven_days = now + timedelta(days=7)
        my_bookmarks = Bookmark.objects.filter(user=user, event__end_date__gte=now, event__end_date__lte=seven_days)

        if my_bookmarks:
            bookmarked_events = []

            for bookmark in my_bookmarks:
                bookmarked_events.append({"EVENT_TITLE": bookmark.event.title,
                                     "IMAGE_URL": bookmark.event.image.url,
                                     "EVENT_DESCRIPTION": bookmark.event.description,
                                     "EVENT_URL": "http://www." + Site.objects.get_current().domain + bookmark.event.get_absolute_url(),
                                     "END_DATE": "{}".format(bookmark.event.end_date.strftime("%A, %d. %B"))})
            subject = "Events ending soon on Alltoez"

            msg = EmailMessage(subject=subject, from_email=("Alltoez", "hi@alltoez.com"),
                               to=[user.email])
            msg.template_name = "Bookmarked Events Ending"
            msg.global_merge_vars = {
                "USER_NAME": profile.first_name,
                "events": bookmarked_events,
            }
            msg.send()
Beispiel #18
0
    def send_new_status_notification_mail(self):
        subject, body = "", ""
        if self.status == ChangeRequest.ACCEPTED:
            subject = _("Your change request has been accepted")
            body = render_to_string(
                'frontend/email/change_request_accepted.txt',
                {
                    'change_request': self,
                    'document_url': self.document_url()
                })
        if self.status == ChangeRequest.DECLINED:
            subject = _("Your change request has been declined")
            body = render_to_string(
                'frontend/email/change_request_declined.txt',
                {
                    'change_request': self,
                    'document_url': self.document_url()
                })

        to = get_user_email(self.author)
        email = EmailMessage(subject,
                             body,
                             to=[to])
        email.send(fail_silently=True)
        logger.info("Sent change request status notification mail to author",
                    extra={
                        'body': body,
                        'to': to,
                    })
Beispiel #19
0
def send_response(original_message, message_text, recipient_email, cc=None):
    """
    Helper function which sends an email message in response to a control
    message.

    :param original_message: The received control message.
    :type original_message: :py:class:`email.message.Message` or an object with
        an equivalent interface
    :param message_text: The text which should be included in the body of the
        response.
    :param cc: A list of emails which should receive a CC of the response.
    """
    subject = original_message.get('Subject')
    if not subject:
        subject = 'Your mail'
    message = EmailMessage(
        subject='Re: ' + subject,
        to=[original_message['From']],
        cc=cc,
        from_email=DISTRO_TRACKER_BOUNCES_EMAIL,
        headers={
            'From': DISTRO_TRACKER_CONTACT_EMAIL,
            'X-Loop': DISTRO_TRACKER_CONTROL_EMAIL,
            'References': ' '.join((original_message.get('References', ''),
                                    original_message.get('Message-ID', ''))),
            'In-Reply-To': original_message.get('Message-ID', ''),
        },
        body=message_text,
    )

    logger.info("control => %(to)s %(cc)s", {
        'to': recipient_email,
        'cc': " ".join(cc) if cc else "",
    })
    message.send()
Beispiel #20
0
def send_email(email_body, email_type=settings.GENERIC,
               recipients=None, site=None, headers=None, **kwargs):
    recipients = recipients or []

    company_name = 'My.jobs'
    domain = 'my.jobs'

    if site:
        domain = site.email_domain
        if site.canonical_company:
            company_name = site.canonical_company.name

    kwargs['company_name'] = company_name
    kwargs['domain'] = domain.lower()

    sender = settings.EMAIL_FORMATS[email_type]['address']
    sender = sender.format(**kwargs)

    # Capitalize domain for display purposes.
    kwargs['domain'] = kwargs['domain'].lower()
    subject = settings.EMAIL_FORMATS[email_type]['subject']
    subject = subject.format(**kwargs)

    email_kwargs = {
        'subject': subject, 'body': email_body, 'from_email': sender,
        'to': recipients
    }
    if headers is not None:
        email_kwargs['headers'] = headers
    message = EmailMessage(**email_kwargs)
    message.content_subtype = 'html'
    message.send()

    return message
Beispiel #21
0
    def run(self, submission, template_code):
        logger.info('SendEmailFromTemplate:%d template %s' % (
                submission.id, template_code
        ))
        
        try:
            translation.activate(submission.submission_language)

            letter = LetterTemplate.objects.language().get(code=template_code)
            email = EmailMessage(
                letter.subject,
                letter.text % {'name': submission.applicant},
                'no-reply@filmfest.by',
                [submission.applicant_email],
                list(settings.MAIL_BCC_LIST),
                headers = {'Reply-To': '2013@filmfest.by'}
            )
            email.send()
        except:
            logger.info('SendEmailFromTemplate:%d template %s exception' % (
                submission.id, template_code
            ))
            raise
        finally:
            translation.deactivate()
        logger.info('SendEmailFromTemplate:%d template %s done' % (
            submission.id, template_code
        ))
Beispiel #22
0
def SaleOrderEmail(order):
    """
    Send email Order
    order Int (ID)
    Return True/False
    """

    conn = connOOOP()
    shop = conn.SaleShop.get(OERP_SALE)

    context = {}
    context['active_id'] = shop.email_sale_order.id
    values = [
        [], #ids
        order, #rel_model_ref
        context, #context
    ]
    body_template = conn_webservice('poweremail.preview','on_change_ref', values)

    customer_email = body_template['value']['to']
    
    if customer_email != 'False':
        subject = body_template['value']['subject']
        body = body_template['value']['body_text']
        email = EmailMessage(subject, body, EMAIL_FROM, to=[customer_email], headers = {'Reply-To': EMAIL_REPPLY})

        try:
            email.send()
            return True
        except:
            error = _("Your order is in process but we don't send email. Check in your order customer section.")
            return False
Beispiel #23
0
def write(request, slug_story, activation_key, t='stories/write.html', d={}):
    story = get_object_or_404(Story, slug=slug_story)
    active_membership = story.active_membership()
    d['story']=story
    if not active_membership:
        story.turn_membership()
        return render(request, 'stories/done.html', d)
    membership = get_object_or_404(Membership, activation_key=activation_key)
    if active_membership.id != membership.id:
        return render(request, 'stories/done.html', d)
    new_line = Line(story=story)
    if request.POST:
        line_form=LineForm(request.POST, prefix='line', instance=new_line)
        if line_form.is_valid():
            line_form.save()
            next = story.turn_membership()
            mail_d = {
                'story': story,
                'site': get_current_site(request)
            }
            message = render_to_string('stories/email.txt', mail_d)
            email = EmailMessage(
                'Estas participando del concurso',
                message,
                to=[next.user.email])
            email.send()
            return render(request, 'stories/done.html', d)  
    else:
        line_form=LineForm(prefix='line')
    d = {
        'form': line_form,
        'story': story,
        'site': get_current_site(request)
    }
    return render(request, t, d)
def send_mail_task(subject, message, to, only_print=False, history_line=None, headers=None):
    if not isinstance(to, (list, tuple)):
        to = [to]

    to = [t for t in to if t is not None]

    to = list(set(to)) # remove duplicates
    if history_line is not None:
        if headers is None:
            headers = {}
        history_header = '<%s>' % history_line
        headers['In-Reply-To'] = history_header
        headers['References'] = history_header

    if settings.EPO_EMAIL_ONLY_PRINT or only_print:
        info(u'printing portal email to: %s: %s (%r)\n%s', to, subject, headers, message)
    else:

        info('sending email to: %s', to)
        try:
            email_message = EmailMessage(subject, message, settings.SMTP_CONF["from"], to)
            if headers is not None:
                email_message.extra_headers = headers
            email_message.send()
        except Exception as e:
            error('failed to send email: %s', e)
            raise
Beispiel #25
0
 def test_from_header(self):
     """
     Make sure we can manually set the From header (#9214)
     """
     email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
     message = email.message()
     self.assertEqual(message['From'], 'from@example.com')
Beispiel #26
0
def sendemail(request , id ):
    """
    For send emails toa partitcular student parents
    """
    print request.path
    p = request.POST
    student = Student.objects.get(id = id)
    studentemail = "scentedvolume3@gmail.com" #str(student.Email)
    if request.method == 'GET':
        emailform = Emailform()

    if request.method =='POST':
        emailform = Emailform(request.POST)
        if emailform.is_valid():
            subject = p.get('subject','')
            body = p.get('body','')
            emailsubject = "%(subprfx)s %(subject)s" % {'subprfx':subprfx , 'subject':subject}
            try:
                email = EmailMessage(emailsubject,body,"kwawannor@gmail.com",['fhim50@gmail.com',])
                email.send()
                print "Email sent"
            except:
                print "Msg not sent"
            try:    
                Email.objects.create(student = student , subject = subject ,body = body, sent_by=request.user)
            except:
                print "Email was not saves"
            return HttpResponse("Msg Sent")
    return render_to_response('msgs/sendmsg.html', dict(student = student ,emailform = emailform , user = request.user ,action="email"))
Beispiel #27
0
 def test_ascii(self):
     email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'])
     message = email.message()
     self.assertEqual(message['Subject'], 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], 'from@example.com')
     self.assertEqual(message['To'], 'to@example.com')
Beispiel #28
0
def cdclient_cargo(request, id):
    cdClient = get_object_or_404(CdClient, id=id)
    if request.method == "POST":
        form = CargoForm(request.POST.copy())
        if form.is_valid():
            cargo = form.save(commit=False)
            cargo.cdclient = cdClient
            cargo.save()
            message = loader.get_template("shipit/sent_email.html").render(Context({"cdClient":cdClient,"cargo":cargo}))
            mail = EmailMessage(
                "Pardus DVD isteğiniz",
                message,
                "Özgürlükiçin <%s>" % DEFAULT_FROM_EMAIL,
                [DVD_MAIL_LIST, cdClient.email],
                headers={"Message-ID":"%s-%s" % (cdClient.id, cdClient.hash)}
            )
            mail.content_subtype = "html"
            mail.send(fail_silently=True)
            cdClient.sent = True
            cdClient.save()

            return HttpResponseRedirect(cdClient.get_absoulte_url())
    else:
        form = CargoForm()
    return render_response(request, "shipit/cargo.html", locals())
Beispiel #29
0
    def send_mail(self, form, files=[]):
        # TODO: refactor, move to utils
        form_data = self.get_form_data(form)
        message = self.compile_message(form_data)
        context_dict = self.get_form_data_context(form_data)

        mail_to = re.compile('\s*[,;]+\s*').split(self.mail_to)
        for key, email in enumerate(mail_to):
            mail_to[key] = self.string_template_replace(email, context_dict)

        mail_from = self.mail_from or None
        if mail_from:
            mail_from = self.string_template_replace(mail_from, context_dict)

        if self.mail_subject:
            mail_subject = self.string_template_replace(self.mail_subject, context_dict)
        else:
            mail_subject = self.title

        from django.core.mail import EmailMessage
        message = EmailMessage(mail_subject, message, mail_from or None, mail_to)

        if self.mail_uploaded_files:
            for file_path in files:
                message.attach_file(file_path)

        message.send(fail_silently=False)
Beispiel #30
0
def follow(request,username):
    """
    Let one user follow another.
    """

    follower = get_object_or_404(Profile,user=request.user)
    followee = get_object_or_404(Profile,user__username=username)

    # Is current user already following this list/profile?
    if followee in follower.followees.all():
        messages.info(request, "You were already following %s" % followee)
    else:
        follower.followees.add(followee)

        # Only send email if followee has that option enabled in their profile
        if followee.email_on_follow == True:

            site = Site.objects.get(id=1) # Need this for link in email template.
            recipients = [followee.user.email,]
            email_subject = render_to_string("people/follow/followed-subject.txt", { 'follower': follower, 'followee': followee })
            email_body_txt = render_to_string("people/follow/followed-body.txt", { 'follower': follower, 'followee': followee, 'site': site, })

            msg = EmailMessage(email_subject, email_body_txt, settings.DEFAULT_FROM_EMAIL, recipients)
            msg.send(fail_silently=False)

        messages.success(request, "You are now following %s" % followee)

    return HttpResponseRedirect(reverse('people_profile_detail',args=[username]))