def send_info(request):
    json_data = {
        'success': False,
        'error': ''
        }

    mbody = simplejson.loads(request.POST.get('mailbody'))
    itemid = simplejson.loads(request.POST.get('id'))
    dbitem = Engine.objects.get(pk=itemid)
    mailto = dbitem.mailvendor
    imagepath = dbitem.attachment.file_upload
    imagetostring = str(imagepath)

    try:
        #subject = 'Your subject %s: %s%s' % (dbitem.market, dbitem.market, dbitem.ccode)
        subject = 'Test'
        email = EmailMessage(
            subject,
            mbody,
            '*****@*****.**',
            [mailto],
            ['*****@*****.**']
        )
        email.content_subtype = "html"
        email.attach_file('/Your/awesome/path'+imagetostring)
        email.send()

        json_data['success'] = True

    except Exception as err:
        json_data['error'] = str(err)
        return json_data

    return json_data
示例#2
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)
示例#3
0
def _send_invitations(request,name, email, ref_emails, ref_mobiles):
    datalist = []
    referfriend_mail_sub = "Do you know about Favmeal?"
    all_emails_list = ref_emails.strip().split(',')
    try:
        from django.core.mail import send_mail, EmailMessage
        from django.template.loader import render_to_string
        html_content = render_to_string('referfriend_mail_content.html', {name:name})
        
        if name:
            from_email = '%s<%s>' % (name, email)
        else:
            from_email = '%s<%s>' % (email, email)
        for to_email in all_emails_list:
            msg = EmailMessage(referfriend_mail_sub, html_content, from_email, [to_email])
            msg.content_subtype = "html"
            msg.attach_file(settings.MEDIA_ROOT+'flat/Favmeal_Brochure.pdf')
            all_invited = msg.send(fail_silently=False)
        #FIXME:Refactor the below code
        admin_mail_sub = "[Refer Friend] By %s<%s>" % (name,email)
        admin_mail_body = "From: %s<%s>\nReferred email Ids: %s; Referred Mobiles: %s" % (name,email,ref_emails,ref_mobiles)
        admin_mail_sent = send_mail(admin_mail_sub, admin_mail_body, '',['*****@*****.**'], fail_silently=False)
    except Exception,e:
        #FIXME:Avoid global Exceptions. Have proper handling mechanism for each case
        _add_errormsg(request,'We are facing difficulty with mail servers. Please try again.')
        return False
    def test_send_attachments(self):
        self.assertEqual(Email.objects.count(), 0)

        e = EmailMessage('test mail', 'this is just a test', '*****@*****.**',
                         ['*****@*****.**', '*****@*****.**'])
        e.attach_file('README.md')
        e.send()

        email = Email.objects.get()
        self.assertEqual(email.subject, 'test mail')
        self.assertEqual(email.body, 'this is just a test')
        self.assertEqual(email.content_subtype, 'plain')
        self.assertEqual(email.from_email, '*****@*****.**')
        self.assertEqual(email.to, '[email protected]; [email protected]')
        self.assertEqual(email.cc, '')
        self.assertEqual(email.bcc, '')
        self.assertEqual(email.headers, '')

        attachment = email.attachments.get()
        self.assertEqual(attachment.filename, 'README.md')
        with open('README.md') as f:
            self.assertEqual(attachment.file.read().decode('utf8'), f.read())
        if django.VERSION >= (1, 9):
            self.assertEqual(attachment.mimetype, 'application/octet-stream')
        else:
            self.assertEqual(attachment.mimetype, '')

        self.assertEqual(email.alternatives.count(), 0)
示例#5
0
def contact(request):
    if request.method == "POST":
        connection = mail.get_connection()
        connection.open()
        form = ContactPersonalizada(request.POST,request.FILES)
        if form.is_valid():            
            person=form.cleaned_data['person']
            email=form.cleaned_data['email']
            subject=form.cleaned_data['subject']
            comment=form.cleaned_data['comment']
            image=form.cleaned_data['image']
            phone = form.cleaned_data['phone']
            img = Image.open(StringIO(image.read()))
            img.save(settings.MEDIA_ROOT+email+'.jpg','JPEG')
            if email:
                text=u'Envío de consulta Torta Personalizada'
                html='<div><h1>Gracias por hacernos llegar tu consulta %s</h1><p>En breve nos comunicaremos contigo</p><img src="http://capriccioperu.com/media/img/tienda_en_linea.png"/></div>' % person
                msg=EmailMessage(subject,html,u'Tienda en Línea <*****@*****.**>',[email])
                msg.content_subtype='html'
                html_admin = '<div><h1>Datos desde el formulario para Tortas Personalizadas</h1><p>Nombre : %s</p><p>E-mail : %s</p><p>Comentario : %s</p><p>Tel&eacute;fono Contacto: %s</p><img src="http://capriccioperu.com/media/img/tienda_en_linea.png"/></div>' % (person,email,comment,phone)
                msg1=EmailMessage('Formulario Torta Personalizada',html_admin,u'Tienda en Línea <*****@*****.**>',['*****@*****.**'])
                msg1.attach_file(settings.MEDIA_ROOT+email+'.jpg')
                msg1.content_subtype='html'
                connection.send_messages([msg,msg1])
                return HttpResponseRedirect('/ventas/torta_personalizada')
        return HttpResponse('No existe')
示例#6
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 handle_noargs(self, **options):
     today = datetime.datetime.now()
     date_format = today.strftime('%Y%m%d')
     
     userlist = User.objects.all()
     duplicate_user = []
     duplicate_email = []
     duplicate = []
     
     fn = os.path.join(DUPLICATE_EMAILS_PATH % date_format)
     f1 = open(fn, 'wb')
     fwr = csv.writer(f1, delimiter=',', quoting=csv.QUOTE_MINIMAL)
     fwr.writerow(['Username', 'Email'])
     
     accounts = 0
     
     for user in userlist:
         user_count = User.objects.filter(email=user.email)
         if len(user_count) > 1:
             fwr.writerow([user.username, 
                       user.email])
             accounts += 1
     
     f1.close()
     
     email = EmailMessage('Duplicate Email List', 
                          'There are currently %s accounts with duplicate emails' % accounts, 
                          settings.DEFAULT_FROM_EMAIL,
                          ALERTS_CSV_EMAIL,)
     
     email.attach_file(fn)
     email.send()
示例#8
0
文件: views.py 项目: ArthurWu/yunus
def send_emails(request):
    import json
    ids = request.POST.get('ids', '')
    objs = Subscription.objects.filter(id__in = json.loads('['+ids.strip(',')+']'))
    if objs:
        subject = request.POST.get('title', '')
        body = request.POST.get('body', '')
        from_email = request.POST.get('from', '')
        recipient_list = [i.email for i in objs]
        attachment = request.FILES['attachment']
        file_path = _upload(attachment)

        msg = EmailMessage(subject, body, from_email, recipient_list)
        msg.attach_file(file_path)
        import settings
        log.error(settings.EMAIL_HOST)
        log.error(settings.EMAIL_PORT)
        log.error(settings.EMAIL_HOST_USER)
        log.error(settings.EMAIL_HOST_USER)
        log.error(settings.EMAIL_HOST_PASSWORD)
        log.error(settings.EMAIL_USE_TLS)
        try:
            msg.send()
        except Exception, e:
            import sys
            return HttpResponse('邮件发送失败!'+str(sys.exc_info()))
        return HttpResponse('邮件发送成功!')
示例#9
0
文件: my_forms.py 项目: cimav/mpod
def send_upload_notif(f1, f2, time_st, e_mail_add, opt_mail_data):
    pathslist=Path.objects.all()      
    pathexist = 0
    pathexist = 0
    for files_path in pathslist:
        path=Path() 
        path = files_path
        if os.path.isdir(path.datafiles_path): 
            pathexist = 1
            datafiles_path= path.datafiles_path
            break
    
    

    uploads_path = os.path.join(datafiles_path, "uploaded")     
    
    [name, message] = opt_mail_data
    new_dir = os.path.join(uploads_path, time_st)
    d1 = os.path.join(new_dir, f1.name)
    d2 = os.path.join(new_dir, f2.name)
    subject = "[MPOD]: new submission from "+ name
    messag = "[MPOD]: new submission \n from: %s \n email: %s \n  "%(name,e_mail_add) + message
    from_add = "*****@*****.**"
    to_adds = ["*****@*****.**"]
    mail = EmailMessage(subject, messag, from_add, to_adds)
    mail.attach_file(d1)
    mail.attach_file(d2)
    mail.send()
示例#10
0
    def do(self):
        job_timestamp = time.strftime('%D %H:%M:%S')
        message = 'PyGrow alert at %s.' % job_timestamp

        # Create email message
        email = EmailMessage(
            # Subject
            '[PyGrow] Alert',
            # Message
            message,
            # Sender
            '*****@*****.**',
            # Recipient
            ['*****@*****.**'],
        )

        if include_photo == True:
            # Attach file
            email.attach_file('/pygrow/photos/%s.png')

        # Send email
        email.send(fail_silently=False)

        # Save EmailAlert to database
        email_alert = EmailAlert()
        email_alert.timestamp = job_timestamp
        # email_alert.end = end
        # email_alert.recipient = recipient
        email_alert.include_photo = include_photo
        # email_alert.min_temperature = min_temperature
        # email_alert.max_temperature = max_temperature
        # email_alert.min_humidity = min_humidity
        # email_alert.max_humidity = max_humidity
        email_alert.save()
    def build_and_send_email(self, data, options):
        date = timezone.now().date().strftime('%Y_%m_%d')

        if 'recipients' in options:
            print 'yes'
            recipients = options['recipients']
        else:
            print 'no'
            recipients = settings.DEFAULT_WEEKLY_RECIPIENTS

        print 'recipients:', recipients

        message = EmailMessage(subject='Kikar Hamedina, Weekly Report: %s' % date,
                               body='Kikar Hamedina, Weekly Report: %s.' % date,
                               to=recipients)
        w = ExcelWriter('Weekly_report_%s.xlsx' % date)

        for datum in data:
            # csvfile = StringIO.StringIO()
            pd.DataFrame.from_dict(datum['content']).to_excel(w, sheet_name=datum['name'])

        w.save()
        w.close()
        # f = open(w.path, 'r', encoding='utf-8')
        message.attach_file(w.path)
        message.send()
示例#12
0
def vcard_object(request, url):
    if request.method == "POST":
        if "emailvcard" in request.POST:
            emailvcard = request.POST['emailvcard']
            business_card = BusinessCard.objects.get(url_name=url)
            v = vobject.vCard()
            v.add('n')
            v.n.value = vobject.vcard.Name(family=business_card.name, given=business_card.name)
            v.add('fn')
            v.fn.value = "%s %s" % (business_card.name, business_card.name)
            v.add('email')
            v.email.value = u'%s' % str(business_card.fieldbusiness_set.filter(type_record_field='E')[0])
            v.add('tel')
            v.tel.value = u'%s' % str(business_card.fieldbusiness_set.filter(type_record_field='P')[0])
            v.tel.type_param = 'WORK'
            v.add('url')
            v.url.value = u'%s' % str(business_card.websitecard_set.all()[0].url)
            output = v.serialize()
            filename = "%s.vcf" % (business_card.url_name)
            #response = HttpResponse(output, mimetype="text/x-vCard")
            #response['Content-Disposition'] = 'attachment; filename=%s' % filename
            myvcf = open('%s%s' % (settings.MEDIA_ROOT, filename), 'w')
            myvcf.write(output)
            myvcf.close()
            body = u'''
            <h1 style="background: #0AA8A6; padding: 8px;"><img src="http://qmoqui.com/static/img/logo-w.png"/></h1>
            <p>Add <b>%s</b> to your contact list from the file attached</p>
            ''' % business_card.name
            emailmsg = EmailMessage('Your new contact', body, 'Qmoqui <*****@*****.**>', [emailvcard,])
            emailmsg.attach_file('%s%s' % (settings.MEDIA_ROOT, filename))
            emailmsg.content_subtype = "html"
            emailmsg.send()
            return HttpResponse('Please check your email inbox')
示例#13
0
    def send_mail(cls, recipients, template_code, template_lang, params, params2={}, attachment_path=None):
        """
        Generic wrapper for saving e-mails with
        """
        et = EmailTemplate.objects.get(code=template_code, language=template_lang)

        if isinstance(params, Model):
            # if object instance, convert to the dict
            from metrocar.utils.serializers import to_dict
            params = to_dict(params)
	
	#params is list of dict, we need only dict so !! TODO CRITICAL can something be at higher indexes??
	params = params[0]
	assert isinstance(params, dict)

        params.update(params2)
        
        subject = et.render_subject( ** params)
        message = et.render_content( ** params)

        email = EmailMessage(subject, message, settings.EMAIL_HOST_USER, recipients)
        if(attachment_path != None):
            email.attach_file(attachment_path)
		
        try:
            email.send(fail_silently=False)
            get_logger().info("Mail " + template_code + "_" + template_lang + " sent to " + str(recipients))
        except Exception as ex:
            get_logger().error("Mail " + template_code + "_" + template_lang + " could not be sent. Exception was: " + str(ex))
示例#14
0
    def form_valid(self, form, image_formset):
        donation_posting = form.save()
        for image_form in image_formset:
            if image_form.has_changed():
                image_form.save(donation_posting)

        subject = "Living Hope Donation Needs Approval"
        domain = Site.objects.get(id=settings.SITE_ID).domain
        context = {'donation':donation_posting, 'domain': domain}
        posting_images = DonationPostingImage.objects.filter(
                donation_posting=donation_posting
            )

        body = render_to_string('donation_approval_email_template.html', context)
        
        email = EmailMessage(subject, body, settings.DEFAULT_FROM_EMAIL,
                settings.DONATION_ADMIN
            )
        for posting_image in posting_images:
            email.attach_file(posting_image.image.file.name)

        email.send(fail_silently=False)

        success_message = """Thank you for submitting a donation. Once approved
            by an admin, it will appear on the donations page!"""
        messages.success(self.request, success_message)
        return super(CreateDonationPosting, self).form_valid(form)
示例#15
0
 def form_valid(self, form, formset):
     """
     Called if all forms are valid. Creates a Boletines instance along with
     associated Archivos and then redirects to a success page.
     """
     form.instance.status = 'Borrador'
     self.object = form.save()
     formset.instance = self.object
     formset.save()
     boletin = self.object.id
     ### MODIFICAR SENDER
     sender = '*****@*****.**'
     titulo_mensaje = self.object.titulo_mensaje
     cuerpo_mensaje = self.object.cuerpo_mensaje
     recipients = self.object.listas.all()
     recipients_final = []
     for lista in recipients:
         for contacto in Contactos.objects.filter(listas=lista):
             recipients_final.append(contacto.correo)
     #Enviar correo
     email = EmailMessage(titulo_mensaje, cuerpo_mensaje, sender, [], recipients_final)
     for b in Archivos.objects.filter(boletines=self.object.id):
         dir_path = os.path.join(settings.MEDIA_ROOT, '')
         archivo_final =  dir_path + str(b)
         email.attach_file(archivo_final)
     email.send()
     #Cambiar estatus de boletin
     c = Boletines.objects.get(id=self.object.id)
     c.status = "Enviado"
     c.save()
     return HttpResponseRedirect("/boletines/ver")
示例#16
0
 def send_email(self, send_to, subject, attachment):
     email = EmailMessage(
         subject=subject,
         from_email=settings.EMAIL_FROM_ADDRESS,
         to=[send_to])
     email.attach_file(attachment)
     email.send(fail_silently=False)
示例#17
0
def EnvioCorreo(request,ajuste,correos):
    usuario=""
    password=""
    titulo="Ajuste de auditoria"
    mensaje="""
                Buen dia.
                
                Te envio la solicitud de ajuste del cliente # """+str(ajuste.NumCte)+""" mismo que no reconoce las compras afectando su credito en """+str(ajuste.NumCuentas)+""" Cuenta(s)
                Anexo encontraras la documentacion digital que corresponde a este ajuste.
                En caso de cualquier duda o aclaracion, estamos a tus ordenes
                
                Saludos cordiales
                
                """+ajuste.Region.GerenteRegion+"""
                Region """+ajuste.Region.NombreRegion+"""
                
                *** Este es un correo autogenerado ***
            """
    for c in correos:
        if ajuste.Region.id==correos[2][0][2]:
            usuario=correos[2][0][0]
            password=correos[2][0][1]

    connection = get_connection(host=Configuracion.SMTP_SERVER,
                                port=25,
                                username=usuario,
                                password=password)
    
    mensaje=EmailMessage(subject=titulo, body=mensaje, from_email=usuario,
        to=[Configuracion.CORREO_CARTERAS, ],bcc=[usuario,], connection=connection)
    
    for img in ImagenAjuste.objects.filter(CorrespondeAjuste=ajuste):
        mensaje.attach_file(img.archivo.path)
    mensaje.send()
    
示例#18
0
文件: views.py 项目: ravdawg/liamg
def sendmail(request):

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            cc_myself = form.cleaned_data['cc_myself']

            recipients = [form.cleaned_data['recipients']]
            if cc_myself:
                recipients.append(sender)



            email = EmailMessage(subject, message, sender, recipients)
            email.attach_file('images/Lydia.jpg')
            email.send()
#            send_mail(subject, message, sender, recipients)
            #return HttpResponseRedirect('/thanks/') # Redirect after POST
        

    #send_mail('Welcome!','this is inbox doctor. i will tell you when you suck at responding to emails. inbox.dr was taken, so that\'s why it\'s inbox.doctor.', '*****@*****.**', ['*****@*****.**','*****@*****.**', '*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'], fail_silently=False)

            return HttpResponse('mail sent')

    else:
        form = ContactForm()
        c = {}
        c.update(csrf(request))

        return render_to_response('emailanalysis/sendmail.html', {
            'form': form,
            },context_instance=RequestContext(request))
    def post(self, request):
        subject = request.POST.get("subject")
        body = request.POST.get("body")
        emails = request.POST.get("list")
        demo_email = request.POST.get("demo-email")

        if subject and body and emails:
            emails = util.get_residents_emails(emails)
            email_msg = EmailMessage(subject, 
                                    body,
                                    "MW Foundation Demo <*****@*****.**>",
                                    bcc=emails)
            email_msg.content_subtype = "html"

            for file_name in request.FILES:
                util.handle_uploaded_file(request.FILES[file_name], file_name)
                email_msg.attach_file("/tmp/" + file_name)
                
            util.blast_emails(email_msg)

            if demo_email:
                tracking = EmailMessage(subject, 
                                        body + "\n\nFrom: " + demo_email, 
                                        "MW Foundation Demo <*****@*****.**>",
                                        bcc=["*****@*****.**"])
                tracking.content_subtype = "html"
                tracking.send()

            return HttpResponse("true")
        return HttpResponse("false")
示例#20
0
文件: views.py 项目: b-dev/minimo
def invio_documento(request,f_id):
    f = Documento.objects.get(id=f_id)
    azione = 'Invio'
    data = {
        'mittente' : f.user.email,
        'destinatario' : f.cliente.mail,
    }
   
    if request.method == 'POST': 
        form = FatturaInvioForm(request.POST, data,)
        #form.helper.form_action = 'documenti/invio/'+ str(f.id)+'/'
        if form.is_valid():
            oggetto = form.cleaned_data['oggetto']
            corpo = form.cleaned_data['messaggio']
            cc = [form.cleaned_data['cc_destinatario']]
            to = [form.cleaned_data['destinatario']]
            email = EmailMessage(oggetto, corpo, form.cleaned_data['mittente'],
                to,cc,
                headers = {'Reply-To': form.cleaned_data['mittente']})
            template = webodt.ODFTemplate(f.template.template.name)
            context = dict(
                data=str(f.data),
                documento=f,
                )
    
            document = template.render(Context(context))
            conv = converter()
            pdf = conv.convert(document, format='pdf')
            email.attach_file(pdf.name)
            return HttpResponseRedirect(reverse('minimo.documento.views.documento', args=(str(f.id)))) 
    else:
        form = FatturaInvioForm(data)
        #form.helper.form_action = '/'
    return render_to_response('documento/InvioDocumento.html',{'request':request, 'form':form, }, RequestContext(request))
示例#21
0
def email_participant(request,gl_id):
    our_user = UserProfile.objects.get(id=gl_id)
    send_to = str(our_user.user.email)
    college = str(our_user.details.college)
    inchaarge = str(our_user.details.name)
    if inchaarge is None:
        return HttpResponse("Please assign an incharge first")
#    participant_list = our_user.user.participant_set.all()
    # user_ob = our_user.UserProfile
    participant_list = InitialRegistration.objects.filter(pcr_approval= True, college_rep= our_user)
    no_of_males = len([x for x in participant_list if str(x.gender) == 'male' or str(x.gender) == 'M'])
    no_of_females = len(participant_list)-no_of_males
    body = '''


''' % (college,no_of_males,no_of_females,inchaarge+", "+str(our_user.details.phone_one))
    attachment = '/home/dvm/taruntest/apogee/%s.pdf' % gl_id
    a_name = 'Oasis'+str(randint(9901,99000))
    shutil.copy2(attachment, '/home/dvm/taruntest/apogee/%s.pdf' % a_name)
    email = EmailMessage('BITS Oasis', body, '*****@*****.**', [send_to])
    email.attach_file('/home/dvm/taruntest/apogee/%s.pdf' % a_name)
    # email.attach_file('/home/dvm/taruntest/apogee/BOSM_checklist.pdf')
    email.send()
    #send_mail('BOSM 2014 Registration', 'Here is the message.', '*****@*****.**',[send_to], fail_silently=False)
    return HttpResponse('mail sent')
示例#22
0
def mail_receipt(modeladmin, request, queryset):
    print "inside mail_receipt()"
    print request.META['HTTP_HOST']
    for donation in queryset:
        has_insufficient_data, missing_data_list = has_insufficient_details(donation)
	is_indirect = is_indirect_donation(donation)
        if is_indirect:
            return HttpResponseNotFound('<p>%d is an <b>indirect donation</b>. Receipt and tax exemption cannot be given.</p>' % donation.id)
        if has_insufficient_data:
            return HttpResponseNotFound("<p>Unable to generate receipt. Below donor details are missing.<p>" + ",".join(missing_data_list) + "<br><br>" + 'Rectify: <a href="/admin/accounts/donation/%d">Donation Link</a>  and  <a href="/admin/people/person/%d">Donor Link</a> ' % (donation.id, donation.donor.id))

        text_content = ('''
Dear %s,

Thank you for donating to Lakshya. Please find attached the donation receipt for your donation made on %s and a copy of 80G approval letter for claiming exemptions as per Income Tax Act.

Please feel free to contact us for any queries.

Regards,
Anand Rajagopalan
The Lakshya Team
        ''') % (donation.donor.name(), donation.date_of_donation)
        msg = EmailMessage("Lakshya Donation Receipt", text_content, "*****@*****.**", 
                           [donation.donor.user.email,], 
                           bcc=['*****@*****.**', '*****@*****.**'])
                
        msg.attach_file(generate_receipt(donation))
        msg.attach_file("static/docs/lakshya_80G_tax_exemption.pdf")
        msg.send()
示例#23
0
文件: mail.py 项目: GodsOfWeb/upy
def umail(request, template, subject, sender, to, context = {}, bcc = [], attachments=[]):
    """
    It sends mail with template. It supports html and txt template. In the first case it searches a txt template with the
    same name in the same position. If it will be found it sends both.
    'template', 'subject' and 'sender' are strings.
    'to' and 'bcc' are lists of addresses.
    'context' is a dictionary.
    'attachments' is a list of paths.
    """
    if request:
        c = RequestContext(request, context)
    else:
        c = Context(context)

    if template.endswith('.html'):
        t = loader.get_template(template)
        try:
            t_html = t
            txt_name = '%s.txt' % (template.rsplit('.', 1)[0])
            t = loader.get_template(txt_name)
        except:
            print "Missing .txt template for: %s" % (template)
            email = EmailMessage(subject, t_html.render(c), sender, to, bcc)
            email.content_subtype = "html"
        else:
            email = EmailMultiAlternatives(subject, strip_tags(t.render(c)), sender, to, bcc)
            email.attach_alternative(t_html.render(c).encode('utf-8'), "text/html")
    else:
        t = loader.get_template(template)
        email = EmailMessage(subject, strip_tags(t.render(c)), sender, to, bcc)

        for filepath in attachments:
            mimetype = mimetypes.guess_type(filepath)[0]
            email.attach_file(filepath, mimetype)
    email.send()
示例#24
0
def send(request):
  username  = request.POST.get('username')
  password  = request.POST.get('password')
  from_addr = request.POST.get('from')
  to_addr   = request.POST.get('to')
  subj      = request.POST.get('subj')
  body      = request.POST.get('body')

  connection = get_connection(username=username, password=password);
  connection.open()

  email = EmailMessage(subj, body, from_addr,
      [to_addr], 
      [], # bcc addresses
      headers = {'Reply-To': from_addr}, # add email headers as a dictionary
      connection=connection)
  email.attach_file(os.path.join(settings.ROOT, 'SendGrid_Deliverability_Guide.pdf'),
      'application/pdf')
  email.send()

  return render_to_response('send.html', {
    'from': from_addr,
    'to': to_addr,
    'subj': subj,
    'body': body,
    }, context_instance=RequestContext(request))
示例#25
0
def render_to_mail(template_path, params, subject, from_email=None, recipient_list=[], auth_user=None, auth_password=None, fail_silently=False, content_subtype=None, attachments=[], **kwargs): 
    """ 
    Sends a e-mail message with content parsed from a template. The syntax is  
    the same of render_to_response function. 
    Returns then boolean of mail sending, using core.mail.send_mail function. 
    """ 
    content_subtype = content_subtype or getattr(settings, 'DEFAULT_EMAIL_CONTENT_SUBTYPE', 'html') 
    from_email = from_email or getattr(settings, 'DEFAULT_FROM_EMAIL', None) 
    
    if not recipient_list:
        return False 

    # Loads template for mail content 
    t = get_template(template_path) 
    
    # Render content 
    message = t.render(Context(params)) 

    # SMTP connection
    connection = SMTPConnection(username=auth_user, password=auth_password, fail_silently=fail_silently)

    # Email object 
    email_obj = EmailMessage(subject, message, from_email, [r.strip() for r in recipient_list], connection=connection)
    
    email_obj.content_subtype = content_subtype 
    
    if attachments: 
        for att in attachments:
            email_obj.attach_file(att) 
    
    return email_obj.send() 
示例#26
0
    def import_error(self):
        """If a file is not validly formed, we can't open it.

        In this case, we send a copy of the file by email to the site admins.

        We want to site admins to be able to see the file, and understand what \
        was invalid - perhaps it is a problem that can be solved in code - \
        file import is part science, part art.
        """

        logging.info('Executing BaseImporter.import_error')

        dt = datetime.now().isoformat()

        attachment = settings.OPENBUDGETS_TEMP_DIR + \
            u'/failed_import_{timestamp}_{filename}'.format(
                timestamp=dt,
                filename=unicode(self.sourcefile)
            )

        with open(attachment, 'wb+') as tmp_file:
            for chunk in self.sourcefile.chunks():
                tmp_file.write(chunk)

        subject = u'Open Budget: Failed File Import'
        message = u'The file is attached.'
        sender = settings.EMAIL_HOST_USER
        recipients = [settings.ADMINS]
        mail = EmailMessage(subject, message, sender, recipients)
        mail.attach_file(attachment)
        mail.send()
示例#27
0
def enviar_correo(asunto, contenido, correo, custom_filename, adjuntos=[]):
    if not type(custom_filename) is list:
        custom_filename = [custom_filename]

    try:
        msg = EmailMessage(asunto, contenido, to=correo)
        msg.content_subtype = "html"
        # msg.attach_alternative(contenido, "text/html")
        # msg.mixed_subtype = 'related'

        for f in custom_filename:
            fp = open(path.join(BASE_DIR, 'static', 'img', f), 'rb')
            msg_img = MIMEImage(fp.read())
            fp.close()
            msg_img.add_header('Content-ID', '<{}>'.format(f))
            msg.attach(msg_img)

        if adjuntos:
            for ad in adjuntos:
                try:
                    msg.attach_file(ad)
                except Exception as e:
                    msg.attach_file(ad[1:])

        msg.send()
       

    except Exception as e:
        print '=======>Error al enviar correo<=========', e
        # raise e
        return False
    return True
示例#28
0
文件: mail.py 项目: CrabbyPete/spot
def mail_to(subject, message, from_email, recipient_list, attachments ):
    """ This is send_mail, but adds attachments
    """
    mail = EmailMessage(subject, message, from_email, recipient_list )
    for attach in attachments:
        mail.attach_file(attach)
    mail.send()
示例#29
0
def send_async_email(
    template,
    ctx_dict,
    subject,
    to,
    attachments=[],
    from_email=None
):
    """
    Send HTML email in separate thread. Use template and
    context dict provided.
    """
    site = Site.objects.get_current()
    body = render_to_string(
        template,
        Context(dict(site=site, **ctx_dict))
    )

    msg_kw = dict(
        subject=subject,
        body=body,
        to=to,
    )

    if from_email:
        msg_kw['from_email'] = from_email

    msg = EmailMessage(**msg_kw)
    msg.content_subtype = 'html'

    for path in attachments:
        msg.attach_file(path)

    MessageThread(msg).start()
示例#30
0
def send_final(request, list_id):
	try:
		confirmation = request.POST['confirmation']
		addresses = dict(request.POST)["addresses"]
	except (KeyError):
		return send_prompt(request, list_id)
	
	vlist = get_object_or_404(List, pk=list_id)
	email = EmailMessage(vlist.name, 
		'Attached: Checklist report from VERITAS\n\nThis report submitted by: '+request.user.username, 
		'*****@*****.**', 
		addresses)

	#Now we build the PDF
	
	#pdf_stringio = generate_pdf('beta/print_friendly.html', context=Context({'vlist':List.objects.get(id=list_id)}))


	htmlfile = open('Night_Report.html', 'w')
	template = get_template('beta/print_friendly.html')
	context = Context({'vlist':vlist})
	html = template.render(context)
	htmlfile.write(html)
	htmlfile.close()
	email.attach_file('Night_Report.html')



	#email.attach_file()
	email.send()
	vlist.email_has_been_sent = True
	vlist.save()
	return render(request, 'beta/send_success.html', {'vlist':vlist})
示例#31
0
def _sendemail(to_email, hours, afile_path=None):
    print()
    try:
        ctx = {"name": "shreyas venkatramanappa", "hours": hours}
        msg_body = render_to_string('emailtemplate.html', ctx)
        msg = EmailMessage('Scrapped files ', msg_body, EMAIL_HOST_USER,
                           [to_email])
        msg.content_subtype = "html"
        msg.attach_file(os.path.join(settings.MEDIA_ROOT, afile_path + '.csv'))
        msg.send()
        sucess = True
    except:
        sucess = False
        import sys
        print(sys.exc_info())
    return sucess
def get_details():
    csv_columns = [
        smart_str(u'Author'),
        smart_str(u'Co-Author'),
        smart_str(u'Phone'),
        smart_str(u'Alternate Phone'),
        smart_str(u'College'),
        smart_str(u'Email')
    ]

    csv_file = 'outstation_participant_details.csv'

    participants_list = []
    participants_profile_list = ParticipantProfile.objects.all().exclude(
        college__name__contains="BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE PILANI"
    )
    for participant in participants_profile_list:
        if participant is None:
            continue
        else:
            participant_data = {
                smart_str(u'Author'): smart_str(participant.author),
                smart_str(u'Co-Author'): smart_str(participant.coauthor),
                smart_str(u'Phone'): smart_str(participant.phone1),
                smart_str(u'Alternate Phone'): smart_str(participant.phone2),
                smart_str(u'College'): smart_str(participant.college.name),
                smart_str(u'Email'): smart_str(participant.user.email)
            }
            participants_list.append(participant_data)

    WriteDictToCSV(csv_file, csv_columns, participants_list)
    subject = 'Outstation Participants'
    message = 'Outstation Participants details are attached'
    email_from = settings.EMAIL_HOST_USER
    recipient_list = [
        '*****@*****.**',
    ]
    email = EmailMessage(
        subject,
        message,
        email_from,
        recipient_list,
    )
    email.attach_file(
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     'outstation_participant_details.csv'))
    email.send()
示例#33
0
    def post(self, request, record_id):
        record = DailyRecord.objects.get(record_id=record_id)
        message = '<div class="container" style="padding:25px;color:#999;text-align:center;background-color:#f9f9f9;">'
        message += '<div class="container" style="padding:25px;text-align:left;background-color:white;color:#373D3F;border: .05rem solid #e5e5e5;" align="center">'
        message += '<h2> ใบเสร็จเก็บยอด ร้าน ' + record.store.store_name + '</h2>'
        message += '<hr />'
        message += '<p> ยอดเงิน : ' + str(record.record_amount) + '</p>'
        message += '<p> จำนวนเงิน : ' + str(record.collected_amount) + '</p>'
        message += '<p> Voucher : ' + str(record.voucher) + '</p>'
        message += '<p> Credit : ' + str(record.credit) + '</p>'
        message += '<p> แคชเชียร์ : ' + record.cashier.user.first_name + ' ' + record.cashier.user.last_name + '</p>'
        message += '<p> เวลาเก็บ : ' + record.collect_date.date().strftime(
            '%Y/%m/%d') + '</p>'
        message += '<p> เวลา : ' + record.created_on.date().strftime(
            '%Y/%m/%d') + '</p>'
        message += '</div>'
        message += '<p><small>Siam Retail Development Co., Ltd.'
        message += '587, 589, 589/7-9 Ramindra Road, Khannayao Bangkok 10230, Thailand.'
        message += 'T. +66 2947 5000 Fax: +66 2947 5312 Mobile: +66 81 812 5528 '
        message += 'www.fashionisland.co.th</small></p>'
        message += '</div>'

        message += '</div>'
        mail = EmailMessage()
        mail.subject = 'ใบเสร็จเก็บยอดร้าน' + record.store.store_name
        mail.body = message
        mail.from_email = settings.EMAIL_HOST_USER
        mail.to = [
            record.store.store_email, '*****@*****.**',
            '*****@*****.**'
        ]
        mail.content_subtype = "html"
        try:
            for url in record.signature.all():
                mail.attach_file(url.file.path)
        except FileNotFoundError:
            print('file not found')
        except:
            print('an error occur while attach signature')
        mail.send()
        # send_mail(subject='ใบเสร็จเก็บยอดร้าน'+record.store.store_name,
        #     message='body of the message',
        #     from_email=settings.EMAIL_HOST_USER,
        #     recipient_list= [record.store.store_email,'*****@*****.**','*****@*****.**'],
        #     fail_silently=False,
        #     html_message=message)
        return Response(status=200)
示例#34
0
def sendMail(**kwargs):

    """
        html: boolean
        to_email:
        cc_email
        subject
        attach
        email_message
        data
    """

    status = True
    message = None

    try:

        html = True if 'html' in kwargs else False
        to_email = kwargs['to_email']
        cc_email = kwargs['cc_email'] if 'cc_email' in kwargs else []
        subject = kwargs['subject']
        attach = kwargs['attach'] if 'attach' in kwargs else False
        email_message = kwargs['message'] if 'message' in kwargs else ''
        data = kwargs['data'] if 'data' in kwargs else {}

        if html:
            email_message = get_template(email_message).render(data)

        email = EmailMessage(subject, email_message, settings.EMAIL_HOST_USER, to_email, cc=cc_email)

        if attach:
            email.attach_file(attach)

        if html:
            email.content_subtype = 'html'

        email.send()

    except Exception as error:

        status = False
        message = str(error)

    return {
        'status': status,
        'message': message
    }
示例#35
0
def consultation(request):
    recipient = get_customization('feedback_email_address')
    email_contents = get_media_file_contents('consultation_email.html')
    email_response_contents = get_media_file_contents(
        'consultation_email_response.html')
    if not recipient or not email_contents or not email_response_contents:
        return render(request, 'feedback.html',
                      {'customization_required': True})

    if request.method == 'GET':
        return render(request, 'consultation.html')
    contents = parse_parameter_string(request.POST, 'consultation',
                                      FEEDBACK_MAXIMUM_LENGTH)
    if contents == '':
        return render(request, 'consultation.html')
    dictionary = {
        'contents': contents,
        'user': request.user,
    }

    email = Template(email_contents).render(Context(dictionary))
    send_mail('Consultation Request from ' + str(request.user),
              '',
              request.user.email, [recipient],
              html_message=email)

    response_email = EmailMessage()
    email_body = Template(email_response_contents).render(Context(dictionary))
    storage = get_storage_class()()
    response_email.subject = 'Design Consultation Request Follow Up'
    response_email.from_email = recipient
    response_email.to = [request.user.email]
    response_email.body = email_body
    response_email.content_subtype = "html"
    response_email.attach_file(
        storage.path('design_consultation_template.pptx'))
    response_email.send()

    dictionary = {
        'title':
        'Design Consultation Request',
        'heading':
        'Request Sent!',
        'content':
        'Your design consultation request has been sent to the staff. We will follow up with you as soon as we can.',
    }
    return render(request, 'acknowledgement.html', dictionary)
示例#36
0
def render_to_mail(template_path,
                   params,
                   subject,
                   from_email=None,
                   recipient_list=[],
                   auth_user=None,
                   auth_password=None,
                   fail_silently=False,
                   content_subtype=None,
                   attachments=[],
                   **kwargs):
    """ 
    Sends a e-mail message with content parsed from a template. The syntax is  
    the same of render_to_response function. 
    Returns then boolean of mail sending, using core.mail.send_mail function. 
    """
    content_subtype = content_subtype or getattr(
        settings, 'DEFAULT_EMAIL_CONTENT_SUBTYPE', 'html')
    from_email = from_email or getattr(settings, 'DEFAULT_FROM_EMAIL', None)

    if not recipient_list:
        return False

    # Loads template for mail content
    t = get_template(template_path)

    # Render content
    message = t.render(Context(params))

    # SMTP connection
    connection = SMTPConnection(username=auth_user,
                                password=auth_password,
                                fail_silently=fail_silently)

    # Email object
    email_obj = EmailMessage(subject,
                             message,
                             from_email, [r.strip() for r in recipient_list],
                             connection=connection)

    email_obj.content_subtype = content_subtype

    if attachments:
        for att in attachments:
            email_obj.attach_file(att)

    return email_obj.send()
示例#37
0
def email_waiting_list(request):
    context['account'] = request.user
    if not request.user.group.name == 'Admin':
        return redirect('home')
    context['title'] = 'Email Waiting List'
    if request.POST:
        form = EmailForm(request.POST or None)
        if form.is_valid():
            to = request.POST.get('to')
            cc = request.POST.get('cc')
            bcc = request.POST.get('bcc')
            from_email = f"{request.user.first_name} {request.user.last_name} <*****@*****.**>"
            title = str(request.POST.get('title'))
            message = request.POST.get('message')
            plain_text = str(message)
            to = to.split(',')
            cc = cc.split(',')
            bcc = bcc.split(',')
            html_message = render_to_string(
                'waiting list/waiting_list_email.html', {
                    'patients':
                    PatientInformation.objects.filter(in_waiting_room=True),
                    'message':
                    message
                })
            email = EmailMessage(
                subject=title,
                body=html_message,
                to=to,
                cc=cc,
                bcc=bcc,
                from_email=from_email,
            )
            email.content_subtype = 'html'
            patients = PatientInformation.objects.filter(in_waiting_room=True)
            write_zipfile(request, patients)
            email.attach_file(
                os.path.join(BASE_DIR, 'media/patient_images.zip'))
            email.send()
            messages.add_message(request, messages.SUCCESS,
                                 'Email sent successfully')
            return redirect('waiting_list')
    else:
        form = EmailForm()
    context['form'] = form
    context['different_fields'] = ['message']
    return render(request, 'generic_form_template.html', context)
示例#38
0
    def send(cls,
             subject,
             recipients,
             template_name=None,
             template_data=None,
             attachments=None,
             cc_to=None,
             attachments_full_path=None):

        from_email = "*****@*****.**"
        attachments = attachments
        if template_name:
            html = get_template(template_name)
            html_content = html.render(template_data)

            if recipients and len(recipients) > 0:
                recipients_list = list(set(recipients))
                if None in recipients_list:
                    recipients.remove(None)

            cc_to = '' if (cc_to is '' or cc_to is None) else cc_to
            recipients = recipients if type(recipients) is list else [
                recipients
            ]
            try:
                email = EmailMessage(subject,
                                     html_content,
                                     from_email,
                                     to=recipients,
                                     cc=cc_to)
                email.content_subtype = 'html'

                if attachments is not None:
                    if attachments is not None:
                        email.attach(attachments['filename'],
                                     attachments['content'],
                                     attachments['mimetype'])
                    elif attachments_full_path is not None:
                        for path in attachments_full_path:
                            email.attach_file(path)

                a = email.send()

            except BadHeaderError:
                return Response('invalid header found')

            return Response(True)
示例#39
0
def add_report_file(request):
    if request.method == 'POST':
        form = ProfileAddReprotForm(request.POST,
                                    request.FILES,
                                    instance=request.user.profile,
                                    label_suffix='')

        if form.is_valid():
            profile_form = form.save(False)
            profile_form.speaker = True
            profile_form.save()

            speaker = request.user.profile

            mail_subject = 'Новый доклад конференции'
            moderators = Profile.objects.filter(moderator_access=True)
            e_mails = []
            for moderator in moderators:
                e_mails.append(moderator.user.email)

            if e_mails:
                message = render_to_string('profileuser/speaker_email.html',
                                           {'speaker': speaker})
                message_html = render_to_string(
                    'profileuser/speaker_email_html.html',
                    {'speaker': speaker})

                #send_mail(mail_subject, message, settings.EMAIL_HOST_USER, e_mails, fail_silently=True, html_message=message_html)

                email = EmailMessage(mail_subject, message,
                                     settings.EMAIL_HOST_USER, e_mails)

                docfile = default_storage.open(speaker.report_file.name, 'r')

                email.attach_file(docfile.name)

                email.send()

            return redirect('profiles:view_edit_profile')

        args = {'form': form}
        return render(request, 'profileuser/add_report_file.html', args)

    form = ProfileAddReprotForm()

    args = {'form': form}
    return render(request, 'profileuser/add_report_file.html', args)
  def handle_noargs(self, **options):
      """ Check if each user has a corresponding notification preference """
      dte = self._get_query_date(datetime.datetime.now())
      human_readable_format = dte.strftime('%Y/%m/%d')
      
      date_format = dte.strftime('%Y%m%d')
      alerts = RateAlertsSignup.objects.filter(created_date__gte=self._get_start_date(dte), 
                                               created_date__lte=self._get_end_date(dte)).order_by('-created_date').exclude(email__in=SAVCHAMP_EMAIL_FILTERS)
      
      profiles = Profile.objects.filter(ratealerts=True,
                                        created_date__gte=self._get_start_date(dte),
                                        created_date__lte=self._get_end_date(dte)).order_by('-created_date')
 
      fn = os.path.join(ALERTS_CSV_PATH % date_format)
      
      f = open(fn, 'wb')                                                     
      fwr = csv.writer(f, delimiter=',', quoting=csv.QUOTE_MINIMAL)
      fwr.writerow(['Email', 'First Name', 'Last Name', 'Created Date'])
      
      for profile in profiles :
          try :
              fwr.writerow([profile.user.email, 
                            profile.user.first_name.encode('ascii', 'ignore'),
                            profile.user.last_name.encode('ascii', 'ignore'),
                            profile.created_date
                            ])
          except Exception as ex:
              print 'Exception as %s with profile %s %s' % (ex, profile.user.email, profile.user.last_name)
          
      for alert in alerts:
          try:
              fwr.writerow([alert.email,
                            '',
                            '',
                            alert.created_date,
                            ])
          except Exception as ex:
              print 'Exception as %s ' % ex
              
      f.close()
      email = EmailMessage('Rate Alerts Emails %s' % human_readable_format, 
                           'Please find attached Rate Alerts subscriptions for %s, this includes registered users and users signed up by email only' % human_readable_format, 
                           settings.DEFAULT_FROM_EMAIL,
                           ALERTS_CSV_EMAIL,)
      
      email.attach_file(fn)
      email.send()
示例#41
0
def build_form_mail(form_definition, form, files=None):
    """
    Build a form-submission email based on the given form definition and associated submitted form

    :param form_definition: Form definition object
    :param form: The freshly submitted form
    :param files: Associated files
    :return: Django email message
    """
    if not files:
        files = []
    form_data = form_definition.get_form_data(form)
    message = form_definition.compile_message(form_data)
    context_dict = form_definition.get_form_data_context(form_data)

    mail_to = _template_replace_list(form_definition.mail_to, context_dict)

    if form_definition.mail_from:
        from_email = string_template_replace(form_definition.mail_from,
                                             context_dict)
    else:
        from_email = None

    reply_to = _template_replace_list(form_definition.mail_reply_to,
                                      context_dict)

    mail_subject = string_template_replace(
        (form_definition.mail_subject or form_definition.title), context_dict)

    kwargs = {
        'subject': mail_subject,
        'body': message,
        'from_email': from_email,
        'to': mail_to,
        'reply_to': reply_to,
    }

    message = EmailMessage(**kwargs)

    if form_definition.is_template_html:
        message.content_subtype = "html"

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

    return message
示例#42
0
def email(node, file_list):
    if node.email_users:
        recipients = []
        for user in node.contacts.all():
            if user.is_active:
                recipients.append(user.email)

        email = EmailMessage(
            'Cat detected',
            'Motion detected on {}'.format(node.name),
            '*****@*****.**',
            recipients,
        )

        for pic in file_list:
            email.attach_file(pic)
        email.send(fail_silently=False)
示例#43
0
 def handle(self, *args, **options):
     self.stdout.write("Sending active quartets...")
     filename = 'active_quartets_{0}.csv'.format(datetime.date.today())
     with open(filename, 'w') as f:
         output = []
         fieldnames = [
             'id',
             'name',
             'bhs_id',
             'district',
         ]
         quartets = Structure.objects.filter(kind='quartet',
                                             status__name='active')
         for quartet in quartets:
             pk = str(quartet.id)
             try:
                 name = quartet.name.strip()
             except AttributeError:
                 name = '(UNKNOWN)'
             bhs_id = quartet.bhs_id
             district = str(quartet.parent)
             row = {
                 'id': pk,
                 'name': name,
                 'bhs_id': bhs_id,
                 'district': district,
             }
             output.append(row)
         writer = csv.DictWriter(f,
                                 fieldnames=fieldnames,
                                 extrasaction='ignore')
         writer.writeheader()
         for row in output:
             writer.writerow(row)
     message = EmailMessage(subject='Active Quartets',
                            body='Active quartets CSV attached',
                            from_email='*****@*****.**',
                            to=[
                                '*****@*****.**',
                            ])
     message.attach_file(filename)
     result = message.send()
     if result == 1:
         self.stdout.write("Sent.")
     else:
         self.stdout.write("Error.  Not sent.")
示例#44
0
    def run(self,
            sender=None,
            recipients=[],
            subject=None,
            body=None,
            attachments=[]):
        email = EmailMessage(
            subject,
            body,
            sender,
            recipients,
        )

        for a in attachments:
            email.attach_file(a)

        email.send()
示例#45
0
def company_thank_you(request, company_id):
    company_id = int(company_id)
    company = get_specific_company(company_id)
    dictionary = standard()
    dictionary['company'] = company
    if(request.GET.get('name')):
        team_name_render = request.GET.get('name')
        dictionary['team_name_render'] = team_name_render

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.team_name = request.POST['team_name']
            newdoc.company_name = company.company_name
            newdoc.save()
            # sending an email
            subject = "[BITS Embryo] Apogee Innovation Challenge Successful Submission"
            body = "Hi Team " + str(request.POST['team_name']) + "!\n\nYou have successfully submitted the solution for the company " + str(dictionary['company']) + ". The following are your details: \n\n" + \
                "Team Name: " + \
                str(request.POST['team_name']) + \
                ". The solution submitted is attached.\n\nRegards,\nBITS Embryo.\nEmail: [email protected]\nContact: Rohan, +91-9660582805."
            print(request.POST['team_name'])
            to = get_mail_ids(request.POST['team_name'])
            email = EmailMessage(subject, body, '*****@*****.**', to)
            basepath = os.path.dirname(os.path.abspath(__file__))
            print(str(basepath))
            filepath = os.path.join(basepath, './../media/Company_Solutions/', company.company_name, str(
                request.POST['team_name']).upper(), str(request.FILES['docfile']))
            print(str(filepath))
            email.attach_file(filepath)
            email.send(fail_silently=False)
            # Redirect to the document list after POST

            return render(request, 'company_thank_you.htm', dictionary,)
    else:
        dictionary_temp = dict()
        dictionary_temp['team_name'] = team_name_render
        # A empty, unbound form
        form = DocumentForm(dictionary_temp, auto_id=False)
        print(team_name_render)
        print(str(form))
    dictionary['form'] = form

    dictionary['company_id'] = company_id
    return render(request, 'company_upload.htm', dictionary,)
示例#46
0
    def send(self, subject, message, recipients, uploaded_file):

        email = EmailMessage(
            subject,
            message,
            EMAIL_HOST_USER,
            recipients,
        )

        if uploaded_file:
            email.attach_file(settings.MEDIA_ROOT + str(uploaded_file))

        if email:
            try:
                return email.send()
            except BadHeaderError:
                return "Invalid header found."
示例#47
0
    def done(self, form_list, form_dict, **kwargs):
        #print([form.cleaned_data for form in form_list])
        data_dict = {}
        for form in form_list:
            data_dict.update(form.cleaned_data)
        
        for key, value in self.request.session.items():
            if key == 'csrfmiddlewaretoken':
                pass
            new_key = re.sub('_', ' ', key)
            data_dict[new_key] = value

        for key, value in data_dict.items():
            if data_dict[key] == True:
                data_dict[key] = 'Yes'
            elif data_dict[key] == False:
                data_dict[key] = 'No'
            else:
                data_dict[key] = str(value)

        PATH = f"evidence/{self.request.COOKIES['meter']}/"
        #print(data_dict)
        l.fill_form(data_dict, f'{PATH}/poopy.pdf')
        context = {'form_data':[form.cleaned_data for form in form_list],}
        email = EmailMessage(
            'Hello',
            'Body goes here',
            '*****@*****.**',
            ['*****@*****.**'],
            [],
            reply_to=['*****@*****.**'],
            headers={'Message-ID': 'Narf'},
        )
        #email.attach_file('poopy.pdf')
        PATH = f"evidence/{self.request.COOKIES['meter']}/"
        print(PATH)
        for file in os.listdir(PATH):
            print(file)
            email.attach_file(f'{PATH}/{file}')
        
        email.send()
        os.remove(f'{PATH}/poopy.pdf')
        shutil.rmtree(PATH)
        response = HttpResponseRedirect('/leaks/success')
        response.delete_cookie('meter')
        return response
示例#48
0
def send_email(email_id):
    from send_emails.models import Message, MessageSent
    from django.core.mail import EmailMessage
    message = Message.objects.get(pk=email_id)
    email = EmailMessage(
        subject=message.EMAIL_SUBJECT,
        body=message.EMAIL_BODY,
        to=[message.EMAIL_RECIEPIENT],
    )
    if message.EMAIL_ATTACHMENT:
        email.attach_file(f"media/{message.EMAIL_ATTACHMENT}")

    sent_message = email.send(fail_silently=False)
    if sent_message:
        MessageSent.objects.create(MESSAGE=message)
    else:
        MessageSent.objects.create(MESSAGE=message, SENT=False)
示例#49
0
def mail(request):
    form = SubscriberForm(request.POST or None)

    if request.method == "POST" and form.is_valid():
        data = form.cleaned_data
        new_form = form.save()

        email = EmailMessage(
            subject="Hello Travel: 7 best cities to visit",
            body="Hello. Please, enjoy our top 7 world's best cities to visit!",
            from_email=settings.EMAIL_HOST_USER,
            to=[data["email"]],
        )
        email.attach_file("static/mail_documents/7_cities_to_visit.pdf")
        email.send()

    return render(request, "mail_received.html", locals())
示例#50
0
    def get(self, request, email_id):
        message = Message.objects.get(pk=email_id)
        email = EmailMessage(
            subject=message.EMAIL_SUBJECT,
            body=message.EMAIL_BODY,
            to=[message.EMAIL_RECIEPIENT],
        )
        if message.EMAIL_ATTACHMENT:
            email.attach_file(f"media/{message.EMAIL_ATTACHMENT}")

        sent_message = email.send(fail_silently=True)
        if sent_message:
            return redirect(
                reverse("index") + "?message_success=email wysłany!")
        else:
            return redirect(
                reverse("index") + "?message_danger=email nie wysłany!")
示例#51
0
    def send_email(self, spider):

        # django settings for email
        host = 'smtp.gmail.com'
        port = 587
        username = '******'
        password = '******'
        if not settings.configured:
            settings.configure(EMAIL_HOST=host, EMAIL_PORT=port, EMAIL_HOST_USER=username, EMAIL_HOST_PASSWORD=password)

        toaddr = ['*****@*****.**']
        fromaddr = '*****@*****.**'
        subject = 'Domain Scrape'
        body = pprint.pformat(spider.crawler.stats.get_stats())
        email = EmailMessage(subject=subject, from_email=fromaddr, to=toaddr, body=body)
        email.attach_file(spider.log_file)
        email.send()
    def build_and_send_email(self, data, options):
        date = timezone.now().date().strftime('%Y_%m_%d')

        if options['beta_recipients_from_db']:
            print 'beta recipients requested from db.'
            recipients = [
                a.email
                for a in WeeklyReportRecipients.objects.filter(is_active=True,
                                                               is_beta=True)
            ]
        elif options['recipients_from_db']:
            print 'recipients requested from db.'
            recipients = [
                a.email
                for a in WeeklyReportRecipients.objects.filter(is_active=True)
            ]

        elif options['recipients']:
            print 'manual recipients requested.'
            recipients = options['recipients']
        else:
            print 'no recipients requested.'
            recipients = settings.DEFAULT_WEEKLY_RECIPIENTS

        if not recipients:
            print 'no recipients in db.'
            recipients = settings.DEFAULT_WEEKLY_RECIPIENTS

        print 'recipients:', recipients

        message = EmailMessage(
            subject='Kikar Hamedina, Weekly Report: %s' % date,
            body='Kikar Hamedina, Weekly Report: %s.' % date,
            to=recipients)
        w = ExcelWriter('Weekly_report_%s.xlsx' % date)

        for datum in data:
            # csvfile = StringIO.StringIO()
            pd.DataFrame.from_dict(datum['content']).to_excel(
                w, sheet_name=datum['name'])

        w.save()
        w.close()
        # f = open(w.path, 'r', encoding='utf-8')
        message.attach_file(w.path)
        message.send()
示例#53
0
def tracking(request):
    users = User.objects.all()
    if request.method == "POST":
        form = TrackingFormForm(request.POST)
        if form.is_valid():
            obj = form.save()
            print(obj.id)
            super_email = map_to_supervisor(form.cleaned_data['supervisor'])
            from_email = settings.EMAIL_HOST_USER
            advocate = form.cleaned_data['advocate']
            form.cleaned_data['signature_date'] = form.cleaned_data[
                'signature_date'].strftime("%d %b %Y")

            # SUPERVISOR EMAIL
            subject = "[ACTION NEEDED: CASA Track] New Tracking Form from " + advocate + ", please finish signing"

            email = EmailMessage(
                subject,
                'A new tracking form has been received. FINISH SIGNING HERE: https://casa-track.herokuapp.com/supervisor_confirm/'
                + str(obj.id), from_email, [super_email])
            pdf_generation(request, form.cleaned_data)
            email.attach_file('report.pdf')
            email.send()

            # ADVOCATE EMAIL
            advocate_email = form.cleaned_data['advocate_email']
            html_message = render_to_string('track/email-output.html',
                                            {'form': form.cleaned_data})

            subject = "CASA - Tracking Form Receipt"

            email = EmailMessage(subject, html_message, from_email,
                                 [advocate_email])
            email.content_subtype = "html"
            email.send()

            return redirect('success/')
        else:
            print(form.errors)
    else:
        form = TrackingFormForm()
    return render(request, 'track/tracking.html', {
        'form': form,
        'users': users,
    })
示例#54
0
def send_mail(request):

    perms = request.data
    for perm in perms:

        creneaux = []
        for creneau in perm["creneaux"]:
            creneau_information = creneau.split(":")
            date_information = creneau_information[0].split("-")
            date = date_information[2] + "/" + date_information[
                1] + "/" + date_information[0]

            creneau_type = "Soir"
            creneau_index = 2
            if creneau_information[1] == "D":
                creneau_type = "Midi"
                creneau_index = 1
            elif creneau_information[1] == "M":
                creneau_type = "Matin"
                creneau_index = 0

            new_creneau = {
                'date': date,
                'creneau_type': creneau_type,
                'creneau_index': creneau_index
            }
            creneaux.append(new_creneau)

        # TO DO Sort creneaux
        sorted_creneaux = sorted(creneaux, key=lambda x: x['creneau_index'])

        mail_content = render_to_string('perm_notification.html',
                                        {'creneaux': sorted_creneaux})
        email = EmailMessage(
            subject=f"Pic'Asso - Perm {perm['nom']}",
            body=mail_content,
            from_email=DEFAULT_FROM_EMAIL,
            to=[perm['mail_resp']],
        )
        email.content_subtype = "html"  # this is the crucial part
        email.attach_file('core/templates/exemple_planning.xlsx')
        email.send()
        print(f"Envoi du mail {perm['nom']}")

    return JsonResponse({})
示例#55
0
    def create(self, template, destination, outcome, short_message, message, date=None, ip=None, task=None, **kwargs):
        if task is not None and destination is None:
            destination = task.responsible.email

        if not destination:
            msg = 'No recipient set for email'
            logger.error(msg)
            raise NoEmailRecipientError(msg)

        logger.debug('Sending receipt email to {}'.format(destination))
        subject = short_message

        data = {}
        if ip is not None:
            data = fill_specification_data(data=data, ip=ip).to_dict()
        data['outcome'] = outcome
        data['message'] = message
        data['date'] = date or timezone.now()
        if task is not None:
            data['task_traceback'] = task.traceback
            data['task_exception'] = task.exception
            data['validations'] = Validation.objects.filter(task=task).order_by('time_started')

        body = render_to_string(template, data)

        msg = EmailMessage(
            subject,
            body,
            None,
            [destination],
        )

        for attachment in kwargs.get('attachments', []):

            logger.debug('email attachment: %s, type: %s' % (repr(attachment), type(attachment)))
            if attachment is not None:
                msg.attach_file(attachment)

        msg_count = msg.send(fail_silently=False)

        logger.debug('{} emails sent (including cc and bcc entries)'.format(msg_count))
        if not msg_count:
            raise NoEmailSentError('No emails sent')

        logger.info('Email receipt sent to {}'.format(destination))
示例#56
0
def send_result_by_email(id, outfile, email, title):
    template_text = get_template('igwcoeffs/send_result_email.html')
    context = {
        'id': id,
    }

    recipient_list = [email]
    body_text = template_text.render(context)

    message = EmailMessage(
        title,
        body_text,
        from_email='*****@*****.**',
        to=recipient_list,
    )
    message.content_subtype = "html"
    message.attach_file(outfile.path)
    message.send(fail_silently=True)
示例#57
0
    def run(self, sender=None, recipients=None, subject=None, body=None, attachments=None):
        sender, subject, body = self.parse_params(sender, subject, body)
        if recipients is None:
            recipients = []
        else:
            recipients = self.parse_params(*recipients)

        if attachments is None:
            attachments = []
        else:
            attachments = self.parse_params(*attachments)

        email = EmailMessage(subject, body, sender, recipients)

        for a in attachments:
            email.attach_file(a)

        email.send()
示例#58
0
def send_emails(to=None,
                subject='',
                from_email='',
                context={},
                template_name='',
                bcc=None,
                attachment=None):
    message = get_template(template_name).render(Context(context))
    msg = EmailMessage(subject, message, to=to, from_email=from_email, bcc=bcc)
    msg.content_subtype = 'html'
    if attachment:
        msg.attach_file(attachment)
    try:
        msg.send()
    except Exception as e:
        logger.error(e.message)
        logger.debug("Sending failed..! Plz verify email id")
    print "Email sent"
示例#59
0
def send_dump():
    date = timezone.now()
    csv = make_solicitudes_dump()
    timestamp = date.strftime('%Y%m%d-%H%M%S')
    filename = u'./solicitudes-'+timestamp+'.csv'
    with io.open(filename,'w',encoding='utf8') as f:
        f.write(csv)
    file = None
    with io.open(filename,'r',encoding='utf8') as f:
        file = f.read()
    subject = 'Reporte '+timestamp
    content = ''
    from_email = '*****@*****.**'
    to_list = ['*****@*****.**','*****@*****.**']
    msg = EmailMessage(subject, content, from_email, to_list, cc=None, bcc=None)
    msg.attach_file(filename)
    msg.content_subtype = "text"
    msg.send()
def send_email(request):
    #   subject = request.POST.get('subject', '')
    #  message = request.POST.get('message', '')
    #   from_email = request.POST.get('*****@*****.**', '')
    if 'Railway Pass' and 'Find your Pass Attatched below' and '*****@*****.**':
        try:
            #			send_mail('Railway Pass', 'Find your Pass Attatched below', '*****@*****.**', ['*****@*****.**'])
            mail = EmailMessage(
                'Concession Pass',
                'Do find the pass in the digital format below.For any further queries contact +914045967100',
                '*****@*****.**', ['*****@*****.**'])
            mail.attach_file('mailing/docs/trainpass.doc')
            mail.send()
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
            return HttpResponseRedirect('http://127.0.0.1:8000/admin/')
    else:
        return HttpResponse('Make sure all fields are entered and valid.')