Beispiel #1
0
def contact(request):
    if request.method == 'POST':
        form = ContactView(request.POST)
        if form.is_valid():
            email = EmailMessage()
            email.from_email = form.cleaned_data.get('email')
            email.to = [request.POST.get('email')]
            email.topic = form.cleaned_data.get('topic')
            email.body = form.cleaned_data.get('message')

            data = EmailMessage()
            data.from_email = form.cleaned_data.get('email')
            data.to = ['*****@*****.**']
            data.topic = 'form received'
            data.body = 'message'

            my_form = form.save(commit=False)
            my_form.save()
            messages.add_message(request, messages.INFO, 'Your message has been sent. Thank you.')
            email.send()
            data.send()
            return HttpResponseRedirect('/')
    else:
        form = ContactView()

    return render(request, 'contact.html', {'form': form})
Beispiel #2
0
def send_task_byMail(task):
    """
    Send Email to all Task Donelist Level User ID's
    where to is Level1, from is Level2 and
    cc is all in Level3
    """
    donelist = Donelist.objects.filter(dl_projtask_id=task)
    for element in donelist:
        print "Donelist Element: " + str(element) + "// Level: " + str(element.dl_level)
    shorttxt = str(task.id) + " / " + str(task.ta_shorttxt)
    email = EmailMessage(shorttxt, "Immotask Message: please read the Attachement")
    for item in donelist:
        if item.dl_level == 1:
            email.to.append(item.dl_user_id.email)
        elif item.dl_level == 2:
            email.from_email = item.dl_user_id.email
        else:
            email.cc.append(item.dl_user_id.email)
    task_pdf = get_task_pdf('', task)
    print type(task_pdf)
    filename = "Immotask-" + str(task.id) + "-" + task.ta_shorttxt
    email.attach(filename, task_pdf.content, 'text/html') # TODO: Attache File as PDF from Django Html
    print str(email)
    try:
        email.send(fail_silently=False)  # TODO: Validate this and make it secure for Law
        email.send()
        print "Send Email to: " + str(email.to) + " cc: " + str(email.cc)
        return True
    except Exception, e:
        print "Exception in task/views line 227: " + str(e)
        return False
Beispiel #3
0
def jobs_info_email(request, pk):
    job = Job.objects.get(id=pk)
    to = Option.objects.get(title='job_report_email').value

    subject = job.subject
    body = """Created by: {username}
{job_no}
Created on : {created}
Appointment date : {appointment_date}
Client Name : {client_name}
Client Address : {client_address}

Report : {body}
    """.format(username=job.user,
               job_no=job.job_no,
               created=job.created,
               appointment_date=job.appointment_date.strftime("%B %d, %Y"),
               client_name=job.client_name,
               client_address=job.client_address,
               body=job.body)
    from_email = request.user.email
    to = [to]

    email = EmailMessage()
    email.subject = "Job Report : {subject}".format(subject=subject)
    email.body = body
    email.from_email = from_email
    email.to = to

    email.send()

    return HttpResponseRedirect(reverse('europarts:jobs_detail', args=[
        pk,
    ]))
def forgot_password(request):
    reset_message = 'You will receive an email with reset instructions shortly'
    not_found_message = 'We could not find a user for that email address'

    if request.method == 'POST':
        form = forms.ForgotPasswordForm(request.POST)

        if form.is_valid():
            email = form.cleaned_data['email']
            user = KagisoUser.get_user_from_auth_db(email)

            if user:
                msg = EmailMessage()
                msg.to = [user.email]
                msg.from_email = get_setting(settings.AUTH_FROM_EMAIL, request)
                msg.subject = 'Password Reset'
                msg.template = get_setting(
                    settings.PASSWORD_RESET_EMAIL_TEMPLATE, request)
                msg.substitution_data = {
                    'link':
                    request.build_absolute_uri(reverse('reset_password')),
                    'token': user.generate_reset_password_token(),
                    'user_id': user.id
                }
                msg.send()

                messages.success(request, reset_message)
                return HttpResponseRedirect(reverse('forgot_password'))
            else:
                messages.error(request, not_found_message)
                return HttpResponseRedirect(reverse('forgot_password'))
    else:
        form = forms.ForgotPasswordForm()

    return render(request, 'kagiso_auth/forgot_password.html', {'form': form})
Beispiel #5
0
def send_confirmation(registrant, event ,password=None):

    message = EmailMessage()
    message.subject = u'Registration to %s' % (event.get_full_name())
    message.from_email = u'*****@*****.**'
    message.to = [registrant.email]

    details = {'name': registrant.get_full_name(),
               'username': registrant.username,
               'password': password,
               'event_name': event.get_full_name(),
               'event_scope': event.scope,
            }

    confirmation_newuser = """Dear %(name)s,

Thank you, for registering for %(event_name)s!

You may log in to the %(event_name)s website at
http://scipy.in/%(event_scope)s/login using the username -
%(username)s and the password - %(password)s.

Looking forward to meet you at %(event_name)s.

Regards,
SciPy.in Team

If you lose your password, visit: http://scipy.in/password-reset
"""

    message.body = confirmation_newuser %(details)

    message.send()
Beispiel #6
0
def leave(request, hash, carid):
    flat = Flat.objects.filter(hash=hash).first()
    car = flat.car_set.filter(id=carid, parked=True).first()
    if car:
        plate = car.plate
        time = timezone.now()
        car.parked = False
        car.blocked = True
        car.endtime = time
        car.save()
        email = EmailMessage()
        email.to = [flat.email]
        email.subject = 'Auto weggefahren'
        email.from_email = settings.FROM_EMAIL
        body = 'Das Auto mit der Nummer {} wurde um {} ausgetragen'.format(
            plate, time)
        password = settings.SECRET_KEY.encode()
        password += b'=' * (32 - len(password))
        password = password[:32]
        key = Fernet(base64.b64encode(password))
        encrypted = key.encrypt(body.encode()).decode()
        email.body = '{}' \
                     '\n Signatur\n{}'.format(body, encrypted)
        email.send()
        return render(request, 'leave.html', {'plate': plate})
    return render(request, 'alreadyleft.html')
Beispiel #7
0
def park(request, hash):
    flat = Flat.objects.filter(hash=hash).first()
    cars_error = False
    if request.method == 'POST':
        plate = request.POST['plate'].upper()
        cars = Car.objects.filter(parked=True).count()
        car = Car.objects.filter(plate=plate).first()
        if cars >= 2 or car:
            cars_error = True
        else:
            time = timezone.now()
            car = Car.objects.create(flat=flat, plate=plate, starttime=time)
            url = request.get_host() + reverse('leave', args=[hash, car.pk])
            email = EmailMessage()
            email.to = [flat.email]
            email.subject = 'Auto geparkt'
            email.from_email = settings.FROM_EMAIL
            body = 'Das Auto mit der Nummer {} wurde um {} parkiert' \
                   '\n hier kann es wieder ausgetragen werden' \
                   '\n {}'.format(plate, time, url)
            password = settings.SECRET_KEY.encode()
            password += b'=' * (32 - len(password))
            password = password[:32]
            key = Fernet(base64.b64encode(password))
            encrypted = key.encrypt(body.encode()).decode()
            email.body = '{}' \
                         '\n Signatur\n{}'.format(body, encrypted)
            email.send()
            return redirect(reverse('success', args=[car.pk]))
    return render(request, 'park.html', {'cars_error': cars_error})
Beispiel #8
0
    def send_email(self):
        now = datetime.now()

        subject = 'BPJSKS_%s_%s' % (self.KODE_CA, now.strftime('%d%m%Y'))
        sender = settings.EMAIL_HOST_USER
        pwd = settings.EMAIL_HOST_PASSWORD
        recepient = config.RECEPIENT
        message = config.MESSAGE

        file_bpjs_name = '%s_BPJSKS_%s.txt' % (self.KODE_CA,
                                               now.strftime('%d%m%Y'))
        src = os.path.join(self.FTR_QUEUE, file_bpjs_name)

        try:
            email = EmailMessage()
            email.subject = subject
            email.body = message
            email.from_email = sender
            email.to = [recepient]
            email.attach_file(src)

            email.send()
            logger.info("Sending email success.")
        except:
            scheduler.enqueue_in(timedelta(minutes=1), self.main)
            logger.error("Sending email fail. Schedule task to restart.")
Beispiel #9
0
def contact(request, event_slug):
    event = Event.objects.filter(slug__iexact=event_slug).first()
    if not event:
        return handler404(request)
    contact_message = ContactMessage()
    form = ContactMessageForm(request.POST or None, instance=contact_message)
    if request.POST:
        if form.is_valid():
            contact_message = form.save()
            info = _("Message received from ") + contact_message.name + "\n"
            info += _("User email: ") + contact_message.email + "\n"
            contact_message.message = info + contact_message.message

            email = EmailMessage()
            email.subject = _("eventoL Contact Message from " + contact_message.name)
            email.body = contact_message.message
            email.from_email = contact_message.email
            email.to = [event.email]
            email.extra_headers = {'Reply-To': contact_message.email}
            email.send(fail_silently=False)
            event = Event.objects.filter(slug__iexact=event_slug).first()
            if not event:
                return handler404(request)
            contact_message.event = event
            contact_message.save()
            messages.success(request, _("The message has been sent. You will receive a reply by email"))
            return HttpResponseRedirect('/event/' + event_slug)
        messages.error(request, _("There was a problem sending your message. Please try again in a few minutes."))

    return render(request, 'contact-message.html', update_event_info(event_slug, request, {'form': form}, event))
Beispiel #10
0
    def on_approved(self, application, member):
        msg = "on_approved called for %s" % application
        logger.info(msg)
        print(msg)
        mail = EmailMessage()
        mail.to = [ member.email, ]
        mail.body = """Your membership has been approved, your member id is #%d""" % member.member_id
        mail.send()

        # Auto-add the membership fee as recurring transaction
        membership_fee = env.float('MEMBEREXAMPLE_MEMBERSHIP_FEE', default=None)
        membership_tag = env.int('MEMBEREXAMPLE_MEMBERSHIP_TAG_PK', default=None)
        if membership_fee and membership_tag:
            from creditor.models import RecurringTransaction, TransactionTag
            rt = RecurringTransaction()
            rt.tag = TransactionTag.objects.get(pk=membership_tag)
            rt.owner = member
            rt.amount = -membership_fee
            rt.rtype = RecurringTransaction.YEARLY
            # If application was received in Q4 set the recurringtransaction to start from next year
            if application.received.month >= 10:
                rt.start = datetime.date(year=application.received.year+1, month=1, day=1)
            rt.save()
            rt.conditional_add_transaction()

        mailman_subscribe = env('MEMBEREXAMPLE_MAILMAN_SUBSCRIBE', default=None)
        if mailman_subscribe:
            mail = EmailMessage()
            mail.from_email = member.email
            mail.to = [ mailman_subscribe, ]
            mail.subject = 'subscribe'
            mail.body = 'subscribe'
            mail.send()
def send_mail(users, context, template):
    """
    Uses Anymail to send templated emails.
    Returns a list of email addresses to which emails failed to be delivered.
    """
    if settings.LOCAL_SETTINGS['EMAIL_SERVICE'] is False:
        raise MailServiceError(_("Email service is disabled."))
    MAIL_SERVICE = settings.ANYMAIL

    failed_emails = list()
    for user in users:
        message = EmailMessage(
            subject=None,  # required for SendinBlue templates
            body='',  # required for SendinBlue templates
            to=[user.email])
        message.from_email = None  # required for SendinBlue templates
        # use this SendinBlue template
        message.template_id = MAIL_SERVICE["TEMPLATES"].get(template)
        message.merge_global_data = context
        response = message.send()  # return number of successfully sent emails

        if not response:
            failed_emails.append(user.email)

    return failed_emails
Beispiel #12
0
def contact(request, event_slug):
    event = Event.objects.filter(slug__iexact=event_slug).first()
    if not event:
        return handler404(request)
    contact_message = ContactMessage()
    form = ContactMessageForm(request.POST or None, instance=contact_message)
    if request.POST:
        if form.is_valid():
            contact_message = form.save()
            info = _("Message received from ") + contact_message.name + "\n"
            info += _("User email: ") + contact_message.email + "\n"
            contact_message.message = info + contact_message.message

            email = EmailMessage()
            email.subject = _("eventoL Contact Message from " + contact_message.name)
            email.body = contact_message.message
            email.from_email = contact_message.email
            email.to = [event.email]
            email.extra_headers = {'Reply-To': contact_message.email}
            email.send(fail_silently=False)
            event = Event.objects.filter(slug__iexact=event_slug).first()
            if not event:
                return handler404(request)
            contact_message.event = event
            contact_message.save()
            messages.success(request, _("The message has been sent. You will receive a reply by email"))
            return HttpResponseRedirect('/event/' + event_slug)
        messages.error(request, _("There was a problem sending your message. Please try again in a few minutes."))

    return render(request, 'contact-message.html', update_event_info(event_slug, request, {'form': form}, event))
Beispiel #13
0
    def send( subject, body, to, from_email = None, cc = None, bcc = None, attachments = None ):
        """
        Send the email using Django's EmailMessage class

        :param: subject
        :param: body
        :param: to
        :param: from_email
        :param: cc
        :param: bcc
        :param: attachments
        :return: String
        """

        if not settings.IS_PROD:
            return True

        email = EmailMessage()
        email.content_subtype = "html"
        email.subject = subject
        email.body = body
        email.to = [to] if isinstance( to, str ) else to
        if from_email:
            email.from_email = from_email
        if cc:
            email.cc = [cc] if isinstance( cc, str ) else cc
        if bcc:
            email.bcc = [bcc] if isinstance( bcc, str ) else bcc
        if attachments:
            for attachment in attachments:
                email.attach( attachment )

        return email.send()
Beispiel #14
0
def send_task_byMail(task):
    """
    Send Email to all Task Donelist Level User ID's
    where to is Level1, from is Level2 and
    cc is all in Level3
    """
    donelist = Donelist.objects.filter(dl_projtask_id=task)
    for element in donelist:
        print "Donelist Element: " + str(element) + "// Level: " + str(
            element.dl_level)
    shorttxt = str(task.id) + " / " + str(task.ta_shorttxt)
    email = EmailMessage(shorttxt,
                         "Immotask Message: please read the Attachement")
    for item in donelist:
        if item.dl_level == 1:
            email.to.append(item.dl_user_id.email)
        elif item.dl_level == 2:
            email.from_email = item.dl_user_id.email
        else:
            email.cc.append(item.dl_user_id.email)
    task_pdf = get_task_pdf('', task)
    print type(task_pdf)
    filename = "Immotask-" + str(task.id) + "-" + task.ta_shorttxt
    email.attach(filename, task_pdf.content,
                 'text/html')  # TODO: Attache File as PDF from Django Html
    print str(email)
    try:
        email.send(fail_silently=False
                   )  # TODO: Validate this and make it secure for Law
        email.send()
        print "Send Email to: " + str(email.to) + " cc: " + str(email.cc)
        return True
    except Exception, e:
        print "Exception in task/views line 227: " + str(e)
        return False
    def test_message_reply(self):
        email_object = EmailMessage('Test subject',  # subject
            'Test body',  # body
            '*****@*****.**',  # from
            ['*****@*****.**'],  # to
        )
        msg = self.mailbox.record_outgoing_message(email_object.message())

        self.assertTrue(msg.outgoing)

        actual_from = '*****@*****.**'
        reply_email_object = EmailMessage(
            'Test subject',  # subject
            'Test body',  # body
            actual_from,  # from
            ['*****@*****.**'],  # to
        )

        with mock.patch.object(reply_email_object, 'send'):
            reply_msg = msg.reply(reply_email_object)

        self.assertEqual(reply_msg.in_reply_to, msg)

        self.assertEqual(actual_from, msg.from_header)

        reply_email_object.from_email = None

        second_reply_msg = msg.reply(reply_email_object)

        self.assertEqual(self.mailbox.from_email, second_reply_msg.from_header)
Beispiel #16
0
    def generate_message(teacher):
        any_incomplete = False
        status_lines = []
        
        for student in sorted(teacher_student_mapping[teacher], key=lambda s: (s.last_name, s.first_name)):
            complete_count = len(teacher_student_mapping[teacher][student]['complete'])
            incomplete_count = len(teacher_student_mapping[teacher][student]['incomplete'])
            total_count = complete_count + incomplete_count
            
            if teacher_student_mapping[teacher][student]['incomplete']:    
                any_incomplete = True
                status_lines.append("{student:}: {complete_count:}/{total_count:} complete".format(student=student.name, complete_count=complete_count, incomplete_count=incomplete_count, total_count=total_count))
            else:
                status_lines.append("{student:}: All complete".format(student=student.name))
        
        msg = EmailMessage()
        msg.to = [teacher.email]
        
        if any_incomplete:
            msg.subject = "Course evaluation status: Incomplete student list"
        else:
            msg.subject = "Course evaluation status: All students completed"

        msg.body = "Evaluation status for the tutees and advisees of {teacher:}:\n\n{status:}".format(status="\n".join(status_lines), teacher=teacher.name)
        msg.from_email = "*****@*****.**"
        
        return msg
Beispiel #17
0
def inscription_confirmee_handler(sender, **kwargs):
    send_courriel_inscrit("recu_ok", sender)

#    if sender.etablissement_delinquant():
#        modele_courriel = ModeleCourriel.objects.get(code="coti_rel")
#        message = EmailMessage()
#        message.subject = modele_courriel.sujet
#        message.body = modele_courriel.corps
#        if hasattr(settings, 'MAILING_TEST_ADDRESS'):
#            message.to = [settings.MAILING_TEST_ADDRESS,]
#        else:
#            message.to = [sender.courriel,]
#        message.from_email = settings.GESTION_AG_SENDER
#        message.content_subtype = "html" if modele_courriel.html else "text"
#        message.send(fail_silently=True)
#
    region = sender.get_etablissement().region
    nom_region = region.nom
    type_inscription = u"mandaté" if sender.est_pour_mandate() \
        else u"accompagnateur"

    subject = u"ag2017 nouvelle inscription web " + nom_region + u"-" +\
              type_inscription + u"-" + sender.get_etablissement().nom
    body = u"" + format_url(
        reverse('admin:gestion_inscriptionweb_change', args=(sender.id,)))
    envoyer_a_service('inscription', subject, body)

    message = EmailMessage()
    message.subject = subject
    message.body = body
    message.to = [adresse_email_region(region.code)]
    message.from_email = settings.GESTION_AG_SENDER
    message.send(fail_silently=True)
Beispiel #18
0
def send_priority_email(log, priority):
    user = priority.user
    first_name = capfirst(user.first_name)
    username = user.username
    expire = priority.expire.strftime('%Y-%m-%d')
    admin_name, admin_email = settings.ADMINS[0]
    mail = EmailMessage()
    mail.subject = "Browsershots priority processing activated"
    mail.body = """
Hi %(first_name)s,

Thank you for supporting the Browsershots project.

Priority processing has been activated for %(username)s
until %(expire)s. Please let me know how it works for you,
and if you have ideas for improvement.

Cheers,
%(admin_name)s
%(admin_email)s
""".strip() % locals()
    mail.to = ['"%s %s" <%s>' % (user.first_name, user.last_name, user.email)]
    mail.bcc = [admin_email]
    mail.from_email = '"%s" <%s>' % (admin_name, admin_email)
    # mail.headers = {'Reply-To': admin_email}
    mail.send()
Beispiel #19
0
def send_priority_email(log, priority):
    user = priority.user
    first_name = capfirst(user.first_name)
    username = user.username
    expire = priority.expire.strftime('%Y-%m-%d')
    admin_name, admin_email = settings.ADMINS[0]
    mail = EmailMessage()
    mail.subject = "Browsershots priority processing activated"
    mail.body = """
Hi %(first_name)s,

Thank you for supporting the Browsershots project.

Priority processing has been activated for %(username)s
until %(expire)s. Please let me know how it works for you,
and if you have ideas for improvement.

Cheers,
%(admin_name)s
%(admin_email)s
""".strip() % locals()
    mail.to = ['"%s %s" <%s>' % (user.first_name, user.last_name, user.email)]
    mail.bcc = [admin_email]
    mail.from_email = '"%s" <%s>' % (admin_name, admin_email)
    # mail.headers = {'Reply-To': admin_email}
    mail.send()
def register(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(
                user_form.cleaned_data['password1']
            )
            new_user.save()
            Profile.objects.create(user=new_user)
            context = {'new_user':new_user, 'menu_class': 'menu-login'}

            message_name = user_form.cleaned_data['first_name']
            message_email = user_form.cleaned_data['email']
            message = EmailMessage(
                subject="Welcome "+str(message_name)+" to 0&X Candles",
                to=[str(message_email)],
                )
            message.template_id = 2  # use this Sendinblue template
            message.from_email = None  # to use the template's default sender
            message.merge_global_data = {'name': message_name,}
            message.send()

            return render(request, 'account/register_done.html', context)
    else:
        user_form = UserRegistrationForm()
        context = {'user_form':user_form}
    return render(request, 'account/register.html', context)
def enviaremail(subject, to, fr_mail,  message):
    e = EmailMessage()
    e.subject = subject
    e.to = [to]
    e.from_email = fr_mail
    e.body = message
    e.send()
Beispiel #22
0
def envoyer_a_bureau_regional(participant, subject, body):
    adresse_bureau = participant.get_region().implantation_bureau.courriel_interne
    if adresse_bureau:
        message = EmailMessage()
        message.subject = subject
        message.body = body
        message.to = adresse_bureau
        message.from_email = settings.GESTION_AG_SENDER
        message.send(fail_silently=True)
Beispiel #23
0
    def get_message(self, student):
        m = EmailMessage()
        m.subject = self.render_subject(student)
        m.body = self.render_body(student)
        m.from_email = email.utils.formataddr((self.from_name, self.from_address))
        m.to = [student.email]
        m.content_subtype = self.content_subtype

        return m
Beispiel #24
0
    def informStudents(self, request, selectedCompanies):
        print "Informing students about ",selectedCompanies;

        t = loader.get_template('company/informStudents_mail.html');
        conn = get_connection(); #for mailing
        
        for c in selectedCompanies:
            #don't send email intimations about old company arrivals wrongly as done on Sat Mar 17.

            if c.date_of_process < datetime.today(): #company process date has already passed
               print "Not informing because date of process %s has already passed!!" % (c.date_of_process)
               continue
                
            ppltoInform = c.came_for_group.get_query_set()[0].user_set.all() 
            context = Context(
                {
                    'company' : c,
                })

            body = t.render(context)

            to = [];
            for p in ppltoInform:
                to += ["*****@*****.**" % str(p.username)]; #for primary sicsrwala address
       
            #send mail actually.
            email = EmailMessage();
            email.from_email = '"Ashwini Narayan" <*****@*****.**>';
            email.subject = '[Placements] %s coming to campus' % c.name;
            #email.from = '*****@*****.**'; #left for automatic putting
            email.connection = conn;
            email.body = body;
            
            cc = [];
            # Getting the From/ CC from the placement Committee group.
            from django.contrib.auth.models import Group;
            g = Group.objects.get(name = 'placement committee')
            
            for u in g.user_set.all():
               cc.append(u.email)
            
            bcc = []
            for m in MANAGERS:
                bcc.append(list(m)[1])
            
            email.to = to + cc;
            email.bcc = bcc;
            print "to is ",email.to;
            print "bcc is ",email.bcc;
            print "body is ",email.body
            email.content_subtype='html';
            email.send();
            dir(email)
            print "Done with %s" % (c);

        self.message_user(request,"Successfully informd students");    
Beispiel #25
0
    def handle(self, *args, **kwargs):
        root_path =  os.path.abspath(os.path.dirname(os.pardir))
        lock =  os.path.join(root_path, 'lock')
        #Till the fetch_data script is running do not execute send script         
        if  os.path.exists(lock) == False:
            if connected_to_internet() is False:
                return None
            syncdata_folder_path = os.path.dirname(__file__).split('/management')[0] + '/MailClient/syncdata'
            list_of_syncdata_folders = []
            sent_folder_path = os.path.dirname(__file__).split('/management')[0] + '/MailClient/sent_syncdata_files'
            
            manage_path =  os.path.abspath(os.path.dirname(os.pardir))
            registry_path =  os.path.join(manage_path, 'Info_Registry.txt')
            if not os.path.exists(sent_folder_path):
                os.makedirs(sent_folder_path)

            try:
                # we take list of directories sorted by 'last modified time' so that changes captured first are sent first
                list_of_syncdata_folders = sorted_ls(syncdata_folder_path)
                print list_of_syncdata_folders
            except Exception as error:
                print 'File name and location is: ', str(__file__)
                print 'Error is : ', error
            
            for i,folder_name in enumerate(list_of_syncdata_folders):
                #send_counter = "%06d" % i
                path = syncdata_folder_path + '/' + folder_name
                #list_of_syncdata_files = os.listdir(syncdata_folder_path)
                #list_of_syncdata_files = os.listdir(path)
                if connected_to_internet() is True:
                    mail = EmailMessage()
                    tstamp = folder_name
                    #mail.subject= str(SYNCDATA_KEY_PUB) + "SYNCDATA_"+tstamp
                    mail.subject= str(SYNCDATA_KEY_PUB) + "_SYNCDATA_"+ tstamp  

                    folder_empty = 0
                    ''''
                    for filename in list_of_syncdata_files:
                        file_path = path + '/' + filename
                        #attch Info registry with every mail
                        print file_path,filename
                        mail.attach_file(file_path)
                        folder_empty = 0
                    ''' 
                    print path
                    mail.attach_file(path)
                    mail.from_email = SYNCDATA_FROM_EMAIL_ID
                    mail.to = list(SYNCDATA_SENDING_EMAIL_ID)
                    if folder_empty == 0:
                        mail.send()
                    shutil.move(path,sent_folder_path)
                    
                    
                else:
                    return 'Internet no longer available'
Beispiel #26
0
def envoyer_a_service(code_service, subject, body):
    """ code_service correspond à une clé du setting DESTINATAIRES_NOTIFICATIONS
    """
    destinataires = settings.DESTINATAIRES_NOTIFICATIONS.get(code_service, None)
    if destinataires:
        message = EmailMessage()
        message.subject = subject
        message.body = body
        message.to = settings.DESTINATAIRES_NOTIFICATIONS[code_service]
        message.from_email = settings.GESTION_AG_SENDER
        message.send(fail_silently=True)
Beispiel #27
0
 def begin_password_reset_process(self):
     log.info("Password reset requested by '{0}'".format(self.user.user.username))
     email = EmailMessage()
     email.subject = "[ratonator] (ACTION NEEDED) Password reset requested"
     email.body = render_to_string(
         "password_reset_email.html", {"key": self.uuid, "days_to_expire": settings.PASSWORD_RESET_EXPIRATION_DAYS}
     )
     email.from_email = "*****@*****.**"
     email.to = [self.user.user.email]
     email.send()
     return self
Beispiel #28
0
def send_email_from_template(to_profile, template_name, global_merge_vars=None, merge_vars=None, from_name=None, from_email=None, subject=None, sent_before_control=False):

    log_type = template_name

    if sent_before_control:
        if mail_is_sent_before(to_profile, log_type):
            return False

    if to_profile.mail_subscription is False:
        return False

    msg = EmailMessage(
        to=[to_profile.email, ]
    )

    msg.template_name = template_name

    if not global_merge_vars:
        global_merge_vars = {}

    msg.global_merge_vars = global_merge_vars

    if merge_vars:
        msg.merge_vars = merge_vars

    msg.subject = subject

    if not from_email:
        from_email = settings.MAILING_FROM_EMAIL

    if not from_name:
        from_name = settings.MAILING_FROM_NAME

    msg.from_email = from_email
    msg.from_name = from_name

    msg.send()

    mandrill_id, mandrill_status = "-1", "unknown"
    try:
        if msg.mandrill_response and len(msg.mandrill_response):
            mandrill_id, mandrill_status = msg.mandrill_response[0].get("_id"), msg.mandrill_response[0].get("status")
    except Exception as error:
        pass

    mail_log = MailLog(
        to=to_profile,
        type=log_type,
        mandrill_response_id=mandrill_id,
        mandrill_status=mandrill_status,
    )

    mail_log.save()
Beispiel #29
0
def send_courriel_inscrit(modele_code, inscription):
    modele_courriel = ModeleCourriel.objects.get(code=modele_code)
    message = EmailMessage()
    message.subject = modele_courriel.sujet
    modele_corps = Template(modele_courriel.corps)
    context = inscription.invitation.get_courriel_template_context()
    message.body = modele_corps.render(Context(context))
    if hasattr(settings, 'MAILING_TEST_ADDRESS'):
        message.to = [settings.MAILING_TEST_ADDRESS, ]
    else:
        message.to = [inscription.courriel, ]
    message.from_email = settings.GESTION_AG_SENDER
    message.content_subtype = "html" if modele_courriel.html else "text"
    message.send(fail_silently=True)
def _send_confirmation_email(user, request):
    msg = EmailMessage()
    msg.to = [user.email]
    msg.from_email = get_setting(settings.AUTH_FROM_EMAIL, request)
    msg.subject = 'Confirm Your Account'
    msg.template = get_setting(settings.SIGN_UP_EMAIL_TEMPLATE, request)
    msg.substitution_data = {
        'link': request.build_absolute_uri(reverse('confirm_account')),
        'token': user.confirmation_token,
        'user_id': user.id,
        'first_name': user.first_name,
        'next': request.GET.get('next', '/')
    }
    msg.send()
Beispiel #31
0
def contact(request):
        if 'username' not in request.session:
            request.session['redirect'] = request.get_full_path();
            return HttpResponse('please signup first ;)')
        if request.method == 'POST': # If the form has been submitted...
           form = ContactForm(request.POST) # A form bound to the POST
           
           if form.is_valid(): # All validation rules pass
               # Process the data in form.cleaned_data
               # ...
               print form;
               post=request.POST;
               #print "=======POST======",post;

               # sending the email NOW...
               to = []
               for m in MANAGERS:
                   to.append(list(m)[1])
               
               email=EmailMessage();
               for f in request.FILES.values() :
                   dest=RESUME_STORE+"/error/"+request.session['username']+".png";
                   destination = open(dest,'wb+')
                   for c in f.chunks():
                       destination.write(c)
                   destination.close()
                   email.attach_file(dest); 
               
               body=post['subject']+"<BR><BR><BR>\n\n\n";
               body += post['message'];
               body += post['url']
               email.from_email=request.session['username']+'@sicsr.ac.in';
               email.subject='[Laresumex'+ post['messageType']+']'
               email.to=to;
               email.body=body;
               email.send();
               #print email.subject;
               
               
               return our_redirect("/common/Thank-you/done") # Redirect after POST
        else:     
           form = ContactForm() # An unbound form
         
        #if the form was invalid OR if there wasn't any submission, just display the form.
        t=loader.get_template('common/contact.html')
        c=RequestContext(request, {
                                'form': form,
                                'ROOT':ROOT,
                                 })
        return HttpResponse(t.render(c));
def mail_invoice(request):

    if request.method == 'POST':
        if 'submit' in request.POST\
                and 'mail' in request.POST:
            submit = request.POST['submit']
            mail = request.POST['mail']
            invoice_id = request.POST['invoice_id']
            invoice = get_invoice_for_id(invoice_id)
            if submit == 'Send':
                invoice_pdf = get_invoice_pdf(invoice_id).content

                email = EmailMessage('Auticiel invoice')
                email.body = 'Hello, Please find the invoice in attachments.'
                email.from_email = EMAIL_HOST_USER
                email.to = [mail,]
                email.attach(invoice['InvoiceID']+'.pdf',
                                     invoice_pdf,
                                     'application/pdf')
                email.send()

                messages.add_message(request, messages.INFO,
                                     'Invoice ' + invoice['InvoiceNumber'] +
                                     ' successfully mailed to' + mail + '.')
                return HttpResponseRedirect('/invoice/')
            else:  # Cancel
                return HttpResponseRedirect('/invoice/')
        else:
            return HttpResponseBadRequest('Missing arg')
    elif request.method == 'GET':
        if 'invoice_id' in request.GET:
            invoice_id = request.GET['invoice_id']
            invoice = get_invoice_for_id(invoice_id)
            contact = get_contact_for_id(invoice['Contact']['ContactID'])

            if contact['EmailAddress'] == "":
                messages.add_message(request, messages.WARNING,
                                     'Contact does not specified an email address')
                return HttpResponseRedirect('/invoice/')
        else:
            return HttpResponseBadRequest('Missing arg')

    context = {
        'title': 'Mail',
        'invoice_id': invoice_id,
        'mail': contact['EmailAddress'],
    }

    return render(request, 'invoicing/mail.html', context)
def send_routine_email(title,message):
    logfilepath = os.path.join(LOG_DIRECTORY, 'twitter.log')
    logfile = open(logfilepath, 'r')
    adresses = [user.email for user in User.objects.filter(is_superuser=True)]
    try:
        email = EmailMessage(title, message)
        email.attachments = [('twitterlogger.log', logfile.read(), 'text/plain')]
        email.to = adresses
        email.from_email = 'Aspira'
        email.send()
        print('%s - Routine email sent to %s'%(datetime.datetime.now().strftime('%y-%m-%d_%H:%M'),adresses))
    except Exception as e:
        print('Routine email failed to send')
        print(e)
        twitterLogger.exception('An error occured while sending an email to admin')
Beispiel #34
0
def send_password_reset_email(request, token):
    msg = EmailMessage()
    msg.subject = 'Password Reset for My Drink Nation'
    msg.body = """
    You recently requested to reset your password. To do so, simply follow the link below:

    %s

    Thanks,
    The My Drink Nation team
    %s
    """ % (request.build_absolute_uri(reverse('user:reset-password', args=(token.token,))), request.build_absolute_uri(reverse('core:home')))
    msg.from_email = settings.EMAIL_FROM_EMAIL
    msg.to = [token.user.email]
    msg.send()
    return msg
Beispiel #35
0
def contact(request):
    if "username" not in request.session:
        request.session["redirect"] = request.get_full_path()
        return HttpResponse("please signup first ;)")
    if request.method == "POST":  # If the form has been submitted...
        form = ContactForm(request.POST)  # A form bound to the POST

        if form.is_valid():  # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            print form
            post = request.POST
            # print "=======POST======",post;

            # sending the email NOW...
            to = []
            for m in MANAGERS:
                to.append(list(m)[1])

            email = EmailMessage()
            for f in request.FILES.values():
                dest = RESUME_STORE + "/error/" + request.session["username"] + ".png"
                destination = open(dest, "wb+")
                for c in f.chunks():
                    destination.write(c)
                destination.close()
                email.attach_file(dest)

            body = post["subject"] + "<BR><BR><BR>\n\n\n"
            body += post["message"]
            body += post["url"]
            email.from_email = request.session["username"] + "@sicsr.ac.in"
            email.subject = "[Laresumex" + post["messageType"] + "]"
            email.to = to
            email.body = body
            email.send()
            # print email.subject;

            return our_redirect("/common/Thank-you/done")  # Redirect after POST
    else:
        form = ContactForm()  # An unbound form

    # if the form was invalid OR if there wasn't any submission, just display the form.
    t = loader.get_template("common/contact.html")
    c = RequestContext(request, {"form": form, "ROOT": ROOT})
    return HttpResponse(t.render(c))
Beispiel #36
0
def send_account_activate_email(request, token):
    msg = EmailMessage()
    msg.subject = 'Thanks for signing up for My Drink Nation'
    msg.body = """
    Your newly created account is ready to be activated. To activate, simply follow the link below:

    %s

    Note: If you forgo activation for too long, you run the risk of your account being suspended.

    Thanks,
    The My Drink Nation team
    %s
    """ % (request.build_absolute_uri(reverse('user:activate', args=(token.token,))), request.build_absolute_uri(reverse('core:home')))
    msg.from_email = settings.EMAIL_FROM_EMAIL
    msg.to = [token.user.email]
    msg.send()
    return msg
Beispiel #37
0
def template_to_email(template_name, context):
    """
    Render a template with its context, parse the result and build an
    EmailMessage from it.
    """
    context.setdefault("default_from", "*****@*****.**")
    context.setdefault("default_subject", "Notification from nm.debian.org")
    text = render_to_string(template_name, context).strip()
    m = email.message_from_string(text.encode('utf-8'))
    msg = EmailMessage()
    msg.from_email = m.get("From", context["default_from"])
    msg.to = parse_recipient_list(m.get("To", EMAIL_PRIVATE_ANNOUNCES))
    if "Cc" in m: msg.cc = parse_recipient_list(m.get("Cc"))
    if "Bcc" in m: msg.bcc = parse_recipient_list(m.get("Bcc"))
    rt = m.get("Reply-To", None)
    if rt is not None: msg.extra_headers["Reply-To"] = rt
    msg.subject = m.get("Subject", context["default_subject"])
    msg.body = m.get_payload()
    return msg
Beispiel #38
0
    def form_valid(self, form):
        """
        Send email with cleaned_data from form
        """
        email = EmailMessage()
        contact_name = form.cleaned_data['name']
        contact_email = form.cleaned_data['email']
        contact_message = form.cleaned_data['message']

        # Set up the EmailMessage object
        email.body = self.MESSAGE_TEMPLATE.format(contact_name, contact_email,
                contact_message)
        email.to = [ settings.CONTACT_EMAIL ]
        email.subject = settings.CONTACT_SUBJECT
        email.from_email = settings.CONTACT_SENDER
        email.reply_to = [ form.cleaned_data['email'] ]

        email.send()

        return super().form_valid(form)
Beispiel #39
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            email = EmailMessage()
            email.from_email = form.cleaned_data.get('email')
            email.to = ['*****@*****.**']
            email.topic = form.cleaned_data.get('topic')
            email.body = form.cleaned_data.get('message')
            our_form = form.save(commit=False)
            our_form.save()
            email.send()
            messages.add_message(request, messages.SUCCESS, 'Your contact message has been sent. Thank you.')
            return render(request, 'index.html')
        else:
            render(request, 'contact.html')

    else:
        form = ContactForm()
        return render(request, 'contact.html', {'form': form})
Beispiel #40
0
def send_user_email(request, user, email_dict):
    context = {
        'user': user,
    }
    context.update(email_dict.get('extra_context', {}))
    email = EmailMessage(subject=email_dict['subject'])
    if request:
        email.body = render_to_string(
            email_dict['template'],
            context,
            context_instance=RequestContext(request),
        )
    else:
        email.body = render_to_string(email_dict['template'], context)
    default_from = '*****@*****.**'
    default_from = getattr(settings, 'DEFAULT_EMAIL_FROM', default_from)
    default_from = getattr(settings, 'DEFAULT_FROM_EMAIL', default_from)
    email.from_email = email_dict.get('from', default_from)
    email.to = ["%s %s <%s>" % (user.first_name, user.last_name, user.email)]
    email.send()
Beispiel #41
0
 def bill_invoice(self):
     if self.client.profile.get_email_address and self.pdf:
         email = EmailMessage()
         email.subject = ("Brownstone Tutors Invoice for " + 
             self.start_date.strftime("%B%Y") )
         email.body = "PDF of bill"
         email.from_email = settings.EMAIL_HOST_USER
         email.to = [ self.client.profile.get_email_address, ]
         # Attach PDF file to the email
         email.attach_file(settings.MEDIA_ROOT + self.pdf.name)
         # Send email
         email.send()
     if self.client.outstanding_balance < 0:
         if self.amount_paid - self.client.outstanding_balance > self.amount:
             self.amount_paid = self.amount
             self.pay()
             self.client.outstanding_balance = self.client.outstanding_balance + (self.amount - self.amount_paid)
         else:
             self.amount_paid = self.amount_paid - self.client.outstanding_balance
             self.client.outstanding_balance = 0