コード例 #1
11
ファイル: mail.py プロジェクト: erickgnavar/eolo
 def send_email_attach(*args, **kwargs):
     email = EmailMessage()
     email.subject = kwargs['subject']
     email.body = kwargs['body']
     email.from_email = settings.DEFAULT_FROM_EMAIL
     email.to = [kwargs['email']]
     email.attach_file(kwargs['path'])
     email.send()
コード例 #2
0
ファイル: models.py プロジェクト: dimagi/email-reports
 def send_pdf_to_user(self, user):
     report = self.report.get_path_to_pdf(user, self.view_args)
     title = self.report.email_subject(user, self.view_args)
     email = EmailMessage(title, 'See attachment',
                          settings.EMAIL_LOGIN, [user.email])
     email.attach_file(report)
     email.send(fail_silently=False)
コード例 #3
0
def custom_email(label, to, cc=None, attachments=None, context=None):
    if not isinstance(to, (list, tuple)):
        to = [to]

    if not isinstance(cc, (list, tuple)):
        cc = [cc]

    full_context = dict()
    full_context.update({} or context)
    mail_obj = EmailMessage()
    mail_obj.to = to
    mail_obj.cc = cc
    mail_obj.subject = render_to_string('email/{}/subject.txt'.format(label),
                                        context=full_context)
    mail_obj.from_email = settings.EMAIL_HOST_USER
    mail_obj.body = render_to_string('email/{}/message.html'.format(label),
                                     context=full_context)
    if attachments:
        for file_name in attachments:
            if os.path.exists(file_name):
                mail_obj.attach_file(file_name)
            else:
                logging.debug(
                    "file is not available in specified location: {}".format(
                        file_name))
    mail_obj.content_subtype = "html"

    try:
        return mail_obj.send()
    except Exception as e:
        msg = u"sending email failed\n"
        msg += unicode(e)
        print >> sys.stderr, e
コード例 #4
0
def send_email(subject, message, receivers, **kwargs):
    receivers = get_receivers(receivers)
    sender = kwargs.get('sender', settings.EMAIL_HOST_USER)
    category = kwargs.get('category')
    attachments = kwargs.get('attachments', [])

    email_kwargs = {}
    for arg in ['bcc', 'cc', 'reply_to', 'headers']:
        email_kwargs[arg] = kwargs.get(arg)

    email = EmailMessage(subject=subject,
                         body=message,
                         from_email=sender,
                         to=receivers,
                         **email_kwargs)
    email.content_subtype = FORMAT_HTML

    # As 'NoneType' object is not iterable.
    if attachments:
        for file_path in attachments:
            email.attach_file(file_path)

    email_result = email.send()

    email_kwargs.update({
        'category': category,
        'result': email_result,
        'receivers': receivers,
        'attachments': attachments,
        'sender': sender,
        'subject': subject,
        'message': message
    })

    return email_kwargs
コード例 #5
0
def send_mail(subject, message, from_email, recipient_list, priority="medium",
              fail_silently=False, auth_user=None, auth_password=None, attach_files=[]):
    from django.utils.encoding import force_unicode
    from mailer.models import make_message
    from django.core.mail.message import EmailMessage

    priority = PRIORITY_MAPPING[priority]

    # need to do this in case subject used lazy version of ugettext
    subject = force_unicode(subject)
    message = force_unicode(message)

    msg = make_message(subject=subject,
                 body=message,
                 from_email=from_email,
                 to=recipient_list,
                 priority=priority)
    email = msg.email
    email = EmailMessage(email.subject, email.body, email.from_email, email.to)

    for f in attach_files:
        if isinstance(f, str):
            email.attach_file(f)
        elif isinstance(f, (tuple, list)):
            n, fi, mime = f + (None,) * (3 - len(f))
            email.attach(n, fi, mime)

    msg.email = email
    msg.save()
    return 1
コード例 #6
0
ファイル: capture_homepage_screen.py プロジェクト: pdflu/CPDB
    def handle(self, *args, **options):
        xvfb = Xvfb(width=1600, height=720)
        xvfb.start()
        browser = WebDriver()
        browser.get(settings.DOMAIN)
        sleep(1)
        browser.find_element_by_css_selector("#disclaimer button").click()
        sleep(0.7)
        browser.find_elements_by_css_selector(".officer .checkmark")[4].click()
        sleep(2)
        browser.find_element_by_css_selector(
            ".complaint-row .col-md-3").click()
        sleep(1)
        content = browser.get_screenshot_as_png()
        now = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        file_name = "{now}.png".format(now=now)
        file_path = os.path.join(settings.BASE_DIR, 'static', file_name)
        with open(file_path, "wb") as f:
            f.write(content)
        browser.quit()

        email = EmailMessage(subject='CPDB Homepage screenshot %s' % now,
                             body='FYI',
                             to=['*****@*****.**'])
        email.attach_file(file_path)
        email.send()
        xvfb.stop()
コード例 #7
0
ファイル: mails.py プロジェクト: jamieconnelly/scane
def send_chunked_txt_files(data):
    logger.info('Sending chunked txt file email')

    email = EmailMessage()
    email.subject = 'Multiple uploads required'
    email.body = ('Hi there 👋,\n\n'
                  'Unfortunately we can only process 450 urls per day.'
                  ' We have began processing the first 450 urls and have'
                  ' split the remaining urls into seperate txt files each'
                  ' containing 450 urls or less. Please come back in 24'
                  ' hours and upload the next file.\n\n'
                  'Best,\n'
                  'Scane')
    email.from_email = settings.DEFAULT_EMAIL_SENDER
    email.reply_to = settings.REPLY_TO_EMAIL
    email.to = [settings.DEFAULT_EMAIL_RECIEVER]

    file_names = []
    for file_name, urls in data:
        with open(file_name, 'w') as writer:
            for url in urls:
                writer.write(f'{url}\n')
            file_names.append(file_name)

    for f_n in file_names:
        filepath = os.path.join(settings.PROJECT_ROOT_DIR, f_n)
        email.attach_file(filepath)

    email.send()
コード例 #8
0
 def send_mail_adnabu(self, email_id, file=None, body=""):
     # from django.courllib.requestmail import EmailMessage
     print("Sending email")
     print(email_id, file)
     email = EmailMessage("title", body, to=[email_id])
     email.attach_file(file)
     email.send()
コード例 #9
0
ファイル: tasks.py プロジェクト: tanveerahmad1517/accounting
def send_bulk_payment_csv():
    """ Generate a bulk payment CSV, send it to the designated TransferWise Bulk Payment sender via e-mail,
    and upload it to Google Drive. """
    # Make the new bulk payment for the sender.
    bulk_payment = models.TransferWiseBulkPayment.objects.create()
    bulk_payment.create_payments()
    bulk_payment_csv = bulk_payment.to_bulk_payment_csv()

    # Make the email, attach the CSV and send.
    email = EmailMessage(
        subject='TransferWise Bulk Payment CSV',
        body='TransferWise Bulk Payment CSV is attached.',
        to=[bulk_payment.sender.user.email],
    )
    email.attach_file(bulk_payment_csv.name)
    email.send()

    # Upload to GDrive.
    file = bulk_payment.upload_to_google_drive(
        file_path=bulk_payment.csv_path,
        target_path=[
            bulk_payment.date.strftime('%Y'), 'invoices-in',
            bulk_payment.date.strftime('%m')
        ],
        title=bulk_payment.csv_filename,
    )
    bulk_payment.csv_path = file['alternateLink']
    bulk_payment.save()
コード例 #10
0
def mail_ics_file(file_name, to):

    message = EmailMessage()
    message.from_email = settings.EMAIL_HOST_USER
    message.to = [to]
    message.subject = 'Add this event to you Calendar'
    message.attach_file(file_name)
    message.send()
コード例 #11
0
def send_e_mail(to_email, Subject, message, attachment):

    email = EmailMessage()
    email.subject = Subject
    email.body = message
    email.from_email = 'PaymentRequests'
    email.to = to_email
    if attachment:
        email.attach_file(attachment)

    email.send()
コード例 #12
0
 def send_mail(self, subject, message, *args, **kwargs):
     with TemporaryDirectory() as temp_dir:
         html_file = pathlib.Path(temp_dir).joinpath('report.html')
         with html_file.open('w') as f:
             f.write(kwargs.get('html_message'))
         zip_file = pathlib.Path(temp_dir).joinpath('dst.zip')
         pyminizip.compress(str(html_file), None, str(zip_file), 'pass', 0)
         msg = EmailMessage('my subject', 'My Body',
                            settings.REAL_MAIL_FROM, settings.REAL_MAIL_TO)
         msg.attach_file(zip_file)
         msg.send()
コード例 #13
0
ファイル: email.py プロジェクト: kaiser0906/tests
 def test_attachment(self):
     if getattr(settings, 'TEST_EMAIL_AWS_SES', False):
         settings.EMAIL_BACKEND = 'e_mail.backends.aws_ses.EmailBackend'
         # Prepare email message
         subject, to = 'hello', '*****@*****.**'
         body = '<h1>This is an important message.</h1>'
         from django.core.mail.message import EmailMessage
         email = EmailMessage(subject=subject, body=body, to=[to])
         email.content_subtype = 'html'
         email.attach_file('/path/to/file.ext')
         email.send()
コード例 #14
0
ファイル: email.py プロジェクト: kaiser0906/tests
 def test_attachment(self):
     if getattr(settings, 'TEST_EMAIL_AWS_SES', False):
         settings.EMAIL_BACKEND = 'e_mail.backends.aws_ses.EmailBackend'
         # Prepare email message
         subject, to = 'hello', '*****@*****.**'
         body = '<h1>This is an important message.</h1>'
         from django.core.mail.message import EmailMessage
         email = EmailMessage(subject=subject, body=body, to=[to])
         email.content_subtype = 'html'
         email.attach_file('/path/to/file.ext')
         email.send()
コード例 #15
0
 def send_file(self):
     mail = EmailMessage()
     mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + \
                 " Anbei die Liste zum Dienstplan der Freiwilligen. Dies ist ein Service von volunteer-planner.org"
     mail.subject = "Dienstplan fuer den " + self.needs[0].time_period_from.date_time.strftime("%d.%m.%Y") + \
                    " der Freiwilligen in der Unterkunft " + self.needs[0].location.name
     mail.from_email = "Volunteer-Planner.org <*****@*****.**>"
     mail.to = [str(self.mailer.email)]
     attachment = self.generate_excel()
     mail.attach_file(path=attachment, mimetype='application/octet-stream')
     mail.send()
コード例 #16
0
 def send_file(self):
     mail = EmailMessage()
     mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + \
                 " Anbei die Liste zum Dienstplan der Freiwilligen. Dies ist ein Service von volunteer-planner.org"
     mail.subject = "Dienstplan fuer den " + self.needs[0].time_period_from.date_time.strftime("%d.%m.%Y") + \
                    " der Freiwilligen in der Unterkunft " + self.needs[0].location.name
     mail.from_email = "Volunteer-Planner.org <*****@*****.**>"
     mail.to = [str(self.mailer.email)]
     attachment = self.generate_excel()
     mail.attach_file(path=attachment, mimetype='application/octet-stream')
     # import ipdb
     # ipdb.set_trace()
     mail.send()
コード例 #17
0
ファイル: tasks.py プロジェクト: andile2012/logistics
def email_report(location_code, to):
    urlbase = Site.objects.get_current().domain
    full_url='%(base)s%(path)s?place=%(loc)s&magic_token=%(token)s' % \
         {"base": urlbase, "path": reverse("tz_pdf_reports"), 
          "loc": location_code, "token": settings.MAGIC_TOKEN}
    fd, tmpfilepath = tempfile.mkstemp(suffix=".pdf", prefix="report-%s" % location_code)
    os.close(fd)
    command = 'wkhtmltopdf "%(url)s" %(file)s' % {"url": full_url, "file": tmpfilepath}
    p = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
    p.communicate()
    email = EmailMessage('%s Report' % location_code, 'See attachment', 
                         settings.EMAIL_LOGIN, to)
    email.attach_file(tmpfilepath)
    email.send(fail_silently=False)
コード例 #18
0
ファイル: views.py プロジェクト: SonofLight/GlobalManageLLC
def PropertyListingDetails(request, id=None): 
	gallery = PropertyImageGallery.objects.filter(property_location = id)
	real_property = RealProperty.objects.get(id=id)
	address = "%s, %s, %s, %s" % (real_property.address, real_property.city, real_property.state, real_property.zip_code)
	features = real_property.features.all()
	surrounding = real_property.surrounding_areas.all()
	image_limit = PropertyImageGallery.objects.filter(property_location=id).count()
	application_form = RentalApplicationForm(request.POST or None)
	if application_form.is_valid():
		instance = application_form.save(commit=False)
		instance.property_location_id = real_property.id
		instance.save()
		app_first_name = application_form.cleaned_data.get('first_name')
		app_last_name = application_form.cleaned_data.get('last_name')
		app_email = application_form.cleaned_data.get('email')
		app_phone = application_form.cleaned_data.get('phone')
		subject = 'You applied for %s %s, %s' % (real_property.address, real_property.city, real_property.state)
		message = """
		Thank you for your application for %s %s, %s. One of our property managers will contact your shortly. 
		However, you can help speed up the process. Attached to this email is our rental application.
		Please take a few minutes and fill out the application. 

		You can send it back via a reply to this email or fax it to 866-275-9080.

		Sincerely,
		The Global Management Team
		Fax: 866-275-9080 
		""" % (real_property.address, real_property.city, real_property.state)
		email = EmailMessage(
			subject = subject, 
			body = message, 
			from_email = settings.DEFAULT_FROM_EMAIL, 
			to=[app_email],
			reply_to=['*****@*****.**'],
			headers={'Message-ID': real_property.address})
		email.attach_file('static/files/rental_application/Global_Manage_Rental_App.pdf', 'application/pdf')
		email.send()

	context = {
		'images' : gallery,  
		'property' : real_property,
		'features': features,
		'surrounding': surrounding,
		'image_limit': image_limit,
		'application_form' : application_form,
		'address' : address,
	}
	return render(request, "property_listing_details.html", context)
コード例 #19
0
def send_form_single_attachment():
    try:
        os.remove('forms_single.zip')
    except:
        pass
    survey = Survey.objects.filter(active=2)
    with zipfile.ZipFile('forms_single.zip','w') as forms_zip:
        for i in survey:
            forms_zip.write("forms_and_choices/"+str(i)+"_"+str(i.id)+".csv")
    email = EmailMessage()
    email.subject = "Forms and choices zip file"
    email.body = "PFA for forms and choices in single file inside zip file"
    email.from_email = "*****@*****.**"
    email.to = [ "*****@*****.**", ]
    email.attach_file('forms_single.zip')
    email.send()
コード例 #20
0
ファイル: views.py プロジェクト: Jarlometoc/trydjango
def EmailResults(request):
    if request.method == 'POST':  # when send results button pushed....
    
        #onoff toggle for only showing jsmol when pressing load or rerun (not input entries)
        onoroff = {'results' : 'on'}
       
        from django.conf import settings
        from django.core.mail.message import EmailMessage
        from django.contrib.auth.models import User
        # get user email from auth_user db
        query = 'SELECT * FROM auth_user WHERE username = "******" ORDER BY id DESC LIMIT 1'
        Qobject8 = User.objects.raw(query)[0]  # db called User in Django, auth_user in SQL
        userEmail = str(Qobject8.email)
        #get current run number
        #query2 = 'SELECT * FROM Results_dbresults WHERE username = "******" ORDER BY mostRes DESC LIMIT 1'
       #Qobject6 = dbResults.objects.raw(query2)[0]
        #runNum = str(Qobject9.runNum)
        # get user run info
        #query3 = 'SELECT * FROM Results_dbresults WHERE username = "******" AND id =' + \
                    # str(runNum)
        #Qobject6 = dbResults.objects.raw(query3)[0]
        bodytext = 'Here are your requested results' #for Run Number ' + str(Qobject6.mostRes) + ' carried out on ' + str(
            #Qobject6.timestamp)
        emailResults = EmailMessage(subject='Results of FAT analysis',
                                    body=bodytext,
                                    from_email=settings.EMAIL_HOST_USER,
                                    to=[userEmail]
                                    )
        
        #path to zipfile
        Path=PathMaker(request.user.username, 'results.zip')
        
        #make the zipfile
        #Path = ZipIt(request, Qobject6)
        # attach results.zip
        emailResults.attach_file(Path)  # attach the zip file
        emailResults.send()  # need to .send()

        #also include ToBeRun dictionary from inputs
        ToBeRunDict = getRunDict(request.user.username)

        #get loaded Results data, if any, for the Testing Refresh, otherwise it will blank
        rerun = getLoadDict(request.user.username)

        
        #RENDER
        return render(request, 'main.html',{'ToBeRunHTML' : ToBeRunDict, 'resultsHTML': rerun, 'showresults' : onoroff})
コード例 #21
0
def send_mail_msg__file(to, subject='', body='', files=None) -> int:
    """ 发送带文件的邮件 """
    if not IS_PROD_ENV:
        subject = f'{ENV_PREFIX} {subject}'
    assert isinstance(to, list), to
    msg = EmailMessage(
        subject=subject,
        body=body,
        to=to,
        reply_to='*****@*****.**',
    )
    files = files if isinstance(files, list) else []
    for one in files:
        msg.attach_file(one)
    num_sent = msg.send()
    logger.info(f'send_mail_msg__file__num_sent {num_sent}')
    return num_sent
コード例 #22
0
    def to_native(self, value):
        obj = super(ConnectUserSerializer, self).to_native(value)
        value.connection = Professional.objects.get(pk=obj.get('professional_id'))
        value.connected_on = now()
        obj['user_connected'] = True
        value.save()
        notify.send(value, recipient=value.connection, verb=u'has connected to you!', target=value)
        notify.send(value.connection, recipient=value, verb=u'connected!', target=value.connection)

        email = EmailMessage()
        email.subject = "Connected To New Trainer"
        email.body = 'Complete attached document and send back to your Trainer'
        email.from_email = value.connection.email
        email.to = [ value.email, ]
        email.attach_file("email/Client Questionarre-ReleaseEverFIT.docx")
        email.send()

        return obj
コード例 #23
0
 def post(self, request, *args, **kwargs):
     form = self.get_form()
     if form.is_valid():
         from django.core.mail.message import EmailMessage
         filepath = str(models.Photo.objects.get(id=self.kwargs.get("pk")))
         email = EmailMessage(subject='Check out your photo:' + self.kwargs.get("pk"),
                              body='Your photo ID:' + self.kwargs.get("pk") + ' is attached in this mail.',
                              from_email='*****@*****.**',#settings.EMAIL_HOST_USER,
                              to=[form.cleaned_data['to_email']]
                             )
         email.attach_file(settings.BASE_DIR + filepath)
         try:
             email.send(fail_silently=not(settings.DEBUG))
         except BadHeaderError:
             return HttpResponse('Invalid header found.')
         return redirect('capture:home')
     else:
         return self.form_invalid(form)
コード例 #24
0
ファイル: mails.py プロジェクト: jamieconnelly/scane
def send_export_email():
    logger.info('Sending exports email')

    email = EmailMessage()
    email.subject = 'Here is your export!'
    email.body = (
        'Hi there 👋,\n\n'
        'We have attached your backlink export results to this email.\n\n'
        'Best,\n'
        'Scane')
    email.from_email = settings.DEFAULT_EMAIL_SENDER
    email.reply_to = settings.REPLY_TO_EMAIL
    email.to = [settings.DEFAULT_EMAIL_RECIEVER]

    exports = shutil.make_archive('exports', 'zip', settings.EXPORTS_DIR)
    email.attach_file(exports)
    email.send()
    shutil.rmtree(settings.EXPORTS_DIR)
コード例 #25
0
ファイル: tasks.py プロジェクト: dslowikowski/logistics
def email_report(location_code, to):
    urlbase = Site.objects.get_current().domain
    full_url='%(base)s%(path)s?place=%(loc)s&magic_token=%(token)s' % \
         {"base": urlbase, "path": reverse("tz_pdf_reports"),
          "loc": location_code, "token": settings.MAGIC_TOKEN}
    fd, tmpfilepath = tempfile.mkstemp(suffix=".pdf",
                                       prefix="report-%s" % location_code)
    os.close(fd)
    command = 'wkhtmltopdf "%(url)s" %(file)s' % {
        "url": full_url,
        "file": tmpfilepath
    }
    p = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
    p.communicate()
    email = EmailMessage('%s Report' % location_code, 'See attachment',
                         settings.EMAIL_LOGIN, to)
    email.attach_file(tmpfilepath)
    email.send(fail_silently=False)
コード例 #26
0
    def send_file(self):
        attachment = self.generate_excel()

        if not self.mailer:
            log.error(u'Cannot create and send email without mailer information')
            return

        mail = EmailMessage()
        mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + "\n\n"\
                    "Anbei die Liste zum Dienstplan der Freiwilligen.\nDies ist ein Service von volunteer-planner.org"
        mail.subject = "Dienstplan fuer den " + self.shifts[0].starting_time.strftime("%d.%m.%Y") + \
                       " der Freiwilligen in der Unterkunft " + self.shifts[0].facility.name
        mail.from_email = settings.DEFAULT_FROM_EMAIL
        mail.to = [str(self.mailer.email)]
        if attachment is not None:
            mail.attach_file(path=attachment, mimetype='application/vnd.ms-excel')
            mail.send()
        else:
            log.warn(u'No attachment, not mail.')
コード例 #27
0
    def send_file(self):
        attachment = self.generate_excel()

        if not self.mailer:
            log.error(
                u'Cannot create and send email without mailer information')
            return

        mail = EmailMessage()
        mail.body = "Hallo " + self.mailer.first_name + " " + self.mailer.last_name + "\n\n"\
                    "Anbei die Liste zum Dienstplan der Freiwilligen.\nDies ist ein Service von volunteer-planner.org"
        mail.subject = "Dienstplan fuer den " + self.shifts[0].starting_time.strftime("%d.%m.%Y") + \
                       " der Freiwilligen in der Unterkunft " + self.shifts[0].facility.name
        mail.from_email = "Volunteer-Planner.org <*****@*****.**>"
        mail.to = [str(self.mailer.email)]
        if attachment is not None:
            mail.attach_file(path=attachment,
                             mimetype='application/vnd.ms-excel')
            mail.send()
        else:
            log.warn(u'No attachment, not mail.')
コード例 #28
0
 def send_message(self,
                  subject,
                  body,
                  from_email=None,
                  to=None,
                  cc=None,
                  bcc=None,
                  headers=None,
                  path=''):
     if to == None:
         to = self.email
     email = EmailMessage(subject=subject,
                          body=body,
                          from_email=from_email,
                          to=to,
                          cc=cc,
                          bcc=bcc,
                          headers=headers)
     if path:
         email.attach_file(path)
     email.message()
     email.send()
コード例 #29
0
ファイル: views.py プロジェクト: kamiljaved98/parkinglot
def record_email_send(request):

    email_invalid = False
    email_sent = False

    if request.method == 'POST':
        pk = int(request.POST['recid'])
        record = DailyRecord.objects.get(pk=pk)
        to_email = request.POST['email']

        # check validity of email
        if validateEmail(to_email):
            email_invalid = False

            # genarate email
            email = EmailMessage()

            email.subject = "Parking Lot Record: " + str(record.date)
            email.body = "PDF Attachment for Customer Record on " + \
                str(record.date) + "."
            email.from_email = "Parking Lot Records <*****@*****.**>"
            email.to = [
                to_email,
            ]

            # generate and attach pdf
            email.attach_file(record_pdf_file(record.pk))
            clear_media()

            # send email
            email.send()
            email_sent = True
        else:
            email_invalid = True

    data = {'email_invalid': email_invalid, 'email_sent': email_sent}
    return JsonResponse(data)
コード例 #30
0
ファイル: views.py プロジェクト: beam018/atproject-server
    def post(self, request, *args, **kwargs):
        p = request.POST

        user_data = {}
        try:
            user_data['name'] = p['name']
            user_data['surname'] = p['surname']
            user_data['phone'] = p['phone']
            user_data['email'] = p['email']
#            user_data['attachment'] = p['attachment']
            user_data['attachment_link'] = p['attachment-link']
        except KeyError:
            return HttpResponse('Data was broken.')

        try:
            user_data['test_link'] = p['test']
            user_data['extra'] = p['extra']
        except KeyError:
            user_data['extra'] = ''
            user_data['test_link'] = ''

        try:
            p['job_id']
        except KeyError:
            return HttpResponse('Data was broken.')

        if not self.validate_request(request):
            return HttpResponse('Data was broken.')

        job = Job.objects.get(pk=p['job_id'])

        msg, created = Mail.objects.get_or_create(
            type=MAIL_TYPE_CLIENT,
            defaults={
                'title': u"Allods team",
                'template': self.get_fixture_data('mail_user.txt'),
            }
        )
        if created:
            msg.save()

        # https://docs.djangoproject.com/en/dev/topics/email/#django.core.mail.EmailMessage
        message = EmailMessage(
            msg.title.format(job=job),
            msg.template.format(job=job),
            MAILER_EMAIL_FROM,
            [user_data['email'],]
        )
        message.send()

        staff_msg, created = Mail.objects.get_or_create(
            type=MAIL_TYPE_STAFF,
            defaults={
                'title': u'Заявка на вакансию {job.name} - {job.project} - {job.city}',
                'template': self.get_fixture_data('mail_staff.txt'),
            }
        )
        if created:
            staff_msg.save()

        staff_message = EmailMessage()
        staff_message.subject = staff_msg.title.format(job=job)

        staff_message.body = staff_msg.template.format(
            job = job,

            name = user_data['name'],
            surname = user_data['surname'],
            phone = user_data['phone'],
            email = user_data['email'],
            attachment_link = user_data['attachment_link'],

            test_link = user_data['test_link'],
            extra = user_data['extra'],
        )
        staff_message.from_email = MAILER_EMAIL_FROM

        tmp_file = None
        try:
            data = request.FILES['attachment']

            path = default_storage.save(
                'mail/%s' % request.FILES['attachment'],
                ContentFile(data.read())
            )
            tmp_file = os.path.join(settings.MEDIA_ROOT, path)
        except Exception:
            pass

        if tmp_file:
            staff_message.attach_file(
                os.path.join(settings.MEDIA_ROOT, 'mail', unicode(tmp_file))
            )

        to_list = []
        if job.user:
            to_list.append(job.user.email)
        if job.mailer:
            to_list += job.mailer.split(', ')

        for to in to_list:
            try:
                validate_email(to)
                staff_message.to = [to, ]
                staff_message.send()
            except ValidationError:
                logging.warning('wrong mail - %s' % to)

        return HttpResponse('Data was transferred.')
コード例 #31
0
def apply_conference(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ConferenceApplicationForm(request.POST, request.FILES) # A form bound to the POST data
        if form.is_valid(): # All validation rules passes
            try:
                user = User.objects.filter(email=form.cleaned_data['email'])[0]
            except :
                user = User.objects.create(username=form.cleaned_data['email'][:28],first_name=form.cleaned_data['name'], 
                                           email=form.cleaned_data['email'])    
            
            #A dirty hack till we support logins and sessions in our system. @author: srihari
            #To avoid corrupting the person's data of someone else by entering their email id
            try:
                person = Person.objects.get(user=user)
                person.billing_address = person.billing_address + str(form.cleaned_data)
                person.save()
            except Person.DoesNotExist:
                person = Person.objects.create(user=user, contact_number=form.cleaned_data['contact_number'],
                                               is_nitw_alumni=True, course=form.cleaned_data['course'],
                                               department=form.cleaned_data['department'],
                                               year_of_passing=form.cleaned_data['year_of_passing'])
            ca = ConferenceApplication.objects.create(date_of_submission=date.today(), 
                                                 year_of_submission=date.today().year,
                                                 applicant=person,
                                                 conference_name=form.cleaned_data['conference_name'],
                                                 conference_dates=form.cleaned_data['conference_dates'],
                                                 conference_city=form.cleaned_data['conference_city'],
                                                 conference_country=form.cleaned_data['conference_country'],
                                                 conference_url=form.cleaned_data['conference_url'],                                                 
                                                 expected_expenditure=form.cleaned_data['expected_expenditure'],
                                                 paper_title=form.cleaned_data['paper_title'],
                                                 research_paper=form.cleaned_data['research_paper'],
                                                 sop=form.cleaned_data['sop'],
                                                 acceptance_email=form.cleaned_data['acceptance_email'],)
            
            for panelist in Panelist.objects.filter(branch=form.cleaned_data['department'], active=True):  
                content = """
Dear %s,

We have received the following application for the Research Facilitator Program - request for funding for conference. Please review the application and kindly give us your feedback based on which we will decide on the funding to be extended to the applicant.

The relevant documents for the conference are attached with the mail. Basic details are given below:

Conference Name: %s
Dates: %s
Conference website: %s
Paper Title: %s
Expected Expenditure: %s
Online feedback Link: %s

Thanks,
The Lakshya Team
""" % (panelist.name, ca.conference_name, ca.conference_dates, 
       ca.conference_url, ca.paper_title, ca.expected_expenditure,   
       "%s/research/feedback-conference-funding?application_id=%d&panelist_id=%d" % (settings.SITE_URL, ca.id, panelist.id))
                msg = EmailMessage("Lakshya: Feedback on conference funding application", content, "*****@*****.**", 
                               [panelist.email,],)
                msg.attach_file(settings.MEDIA_ROOT +"/"+ ca.research_paper.name)
                msg.attach_file(settings.MEDIA_ROOT +"/"+ ca.sop.name)
                msg.attach_file(settings.MEDIA_ROOT +"/"+ ca.acceptance_email.name)
                msg.send()                            
                
                
#                 Django Notification doesn't support attachments             
#                user = User(first_name="Srihari", last_name="", 
#                       email="*****@*****.**", id=1)
#                
#                to_users = [user, ]
#                context = {"panelist_name": panelist.name,
#                           "conference_name": ca.conference_name,
#                           "conference_dates": ca.conference_dates,
#                           "conference_url": ca.conference_url,
#                           "paper_title": ca.paper_title,
#                           "expenditure": ca.expected_expenditure,
#                           "feedback_url": "%s/research/feedback-conference-funding?application_id=%d&panelist_id=%d" \
#                                            % (settings.SITE_URL, ca.id, panelist.id),
#                           }
#                
#                attachments = []
#                attachments.append(settings.MEDIA_ROOT +"/"+ ca.research_paper.name)
#                attachments.append(settings.MEDIA_ROOT +"/"+ ca.acceptance_email.name)
#                notification.send(to_users, "feedback_conference_funding", context, attachments=attachments)        
            
            return render_to_response("apply_research_success.html", RequestContext(request, {}))
    else:
        form = ConferenceApplicationForm() # An unbound form

    return render(request, 'apply_conference.html', {
        'form': form,
    })
コード例 #32
0
ファイル: views.py プロジェクト: hkilicer/forecast
def invoice_report(request):
    forecast = Forecast.objects.all()
    if request.method == 'POST':
        post = request.POST
        ay = post.get("fatura_ayi")
        yil = post.get("fatura_yili")
        eposta = post.get("eposta")

        if ay != None and ay != "":
            forecast = forecast.filter(fatura_ayi=int(ay))

        if yil != None and yil != "":
            forecast = forecast.filter(fatura_yili=int(yil))

        if eposta != None and eposta != "":
            book = xlwt.Workbook(encoding='utf8')
            sheet = book.add_sheet('IT Forecast Report_' + str(ay) + '_Ay')

            # Adding style for cell
            # Create Alignment
            alignment = xlwt.Alignment()
            # horz May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT,
            # HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL,
            # HORZ_DISTRIBUTED
            alignment.horz = xlwt.Alignment.HORZ_LEFT
            # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED,
            # VERT_DISTRIBUTED
            alignment.vert = xlwt.Alignment.VERT_TOP
            style = xlwt.XFStyle() # Create Style
            style.alignment = alignment # Add Alignment to Style

            default_style = xlwt.Style.default_style
            datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
            date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')
            values_list = forecast.filter(fatura_ayi=int(ay)).values_list()

            header = ['ID', 'Fatura Ayı', 'Fatura Yılı', 'Tutar', 'Para Cinsi', 'Tipi', 'Gider Tipi', 'Ödeme Şekli' 'Açıklama', 'Firma', 'Kayıt Tarihi']
            for hcol, hcol_data in enumerate(header):
                sheet.write(0, hcol, hcol_data, style=xlwt.Style.default_style)

            for row, rowdata in enumerate(values_list, start=1):
                for col, val in enumerate(rowdata):
                    if isinstance(val, datetime):
                        style = datetime_style
                    elif isinstance(val, date):
                        style = date_style
                    else:
                        style = default_style

                    sheet.write(row, col, val, style=style)

            response = HttpResponse(mimetype='application/vnd.ms-excel')
            book.save('/downloads/IT_Forecast' + '_' + str(yil) + '_' + str(ay) + '_Ay Raporu' + '.xls')
            filename = ('/downloads/IT_Forecast' + '_' + str(yil) + '_' + str(ay) + '_Ay Raporu' + '.xls')

            smtpserver = 'localhost'
            html_message = "Bu mesaj sistem tarafından otomatik olarak gönderilmiştir."
            email = EmailMessage()
            email.subject = "Aylık IT Forecast Tablosu"
            email.body = html_message
            email.from_email = "IT Forecast <*****@*****.**>"
            email.to = [ eposta, ]
            email.attach_file(filename)
            email.send()

    return render(request, 'welcome/verigoruntuleme.html', {"forecast":forecast})
コード例 #33
0
def apply_conference(request):
    if request.method == 'POST':  # If the form has been submitted...
        form = ConferenceApplicationForm(
            request.POST, request.FILES)  # A form bound to the POST data
        if form.is_valid():  # All validation rules passes
            try:
                user = User.objects.filter(email=form.cleaned_data['email'])[0]
            except:
                user = User.objects.create(
                    username=form.cleaned_data['email'][:28],
                    first_name=form.cleaned_data['name'],
                    email=form.cleaned_data['email'])

            #A dirty hack till we support logins and sessions in our system. @author: srihari
            #To avoid corrupting the person's data of someone else by entering their email id
            try:
                person = Person.objects.get(user=user)
                person.billing_address = person.billing_address + str(
                    form.cleaned_data)
                person.save()
            except Person.DoesNotExist:
                person = Person.objects.create(
                    user=user,
                    contact_number=form.cleaned_data['contact_number'],
                    is_nitw_alumni=True,
                    course=form.cleaned_data['course'],
                    department=form.cleaned_data['department'],
                    year_of_passing=form.cleaned_data['year_of_passing'])
            ca = ConferenceApplication.objects.create(
                date_of_submission=date.today(),
                year_of_submission=date.today().year,
                applicant=person,
                conference_name=form.cleaned_data['conference_name'],
                conference_dates=form.cleaned_data['conference_dates'],
                conference_city=form.cleaned_data['conference_city'],
                conference_country=form.cleaned_data['conference_country'],
                conference_url=form.cleaned_data['conference_url'],
                expected_expenditure=form.cleaned_data['expected_expenditure'],
                paper_title=form.cleaned_data['paper_title'],
                research_paper=form.cleaned_data['research_paper'],
                sop=form.cleaned_data['sop'],
                acceptance_email=form.cleaned_data['acceptance_email'],
            )

            for panelist in Panelist.objects.filter(
                    branch=form.cleaned_data['department'], active=True):
                content = """
Dear %s,

We have received the following application for the Research Facilitator Program - request for funding for conference. Please review the application and kindly give us your feedback based on which we will decide on the funding to be extended to the applicant.

The relevant documents for the conference are attached with the mail. Basic details are given below:

Conference Name: %s
Dates: %s
Conference website: %s
Paper Title: %s
Expected Expenditure: %s
Online feedback Link: %s

Thanks,
The Lakshya Team
""" % (panelist.name, ca.conference_name, ca.conference_dates,
                ca.conference_url, ca.paper_title, ca.expected_expenditure,
                "%s/research/feedback-conference-funding?application_id=%d&panelist_id=%d"
                % (settings.SITE_URL, ca.id, panelist.id))
                msg = EmailMessage(
                    "Lakshya: Feedback on conference funding application",
                    content,
                    "*****@*****.**",
                    [
                        panelist.email,
                    ],
                )
                msg.attach_file(settings.MEDIA_ROOT + "/" +
                                ca.research_paper.name)
                msg.attach_file(settings.MEDIA_ROOT + "/" + ca.sop.name)
                msg.attach_file(settings.MEDIA_ROOT + "/" +
                                ca.acceptance_email.name)
                msg.send()


#                 Django Notification doesn't support attachments
#                user = User(first_name="Srihari", last_name="",
#                       email="*****@*****.**", id=1)
#
#                to_users = [user, ]
#                context = {"panelist_name": panelist.name,
#                           "conference_name": ca.conference_name,
#                           "conference_dates": ca.conference_dates,
#                           "conference_url": ca.conference_url,
#                           "paper_title": ca.paper_title,
#                           "expenditure": ca.expected_expenditure,
#                           "feedback_url": "%s/research/feedback-conference-funding?application_id=%d&panelist_id=%d" \
#                                            % (settings.SITE_URL, ca.id, panelist.id),
#                           }
#
#                attachments = []
#                attachments.append(settings.MEDIA_ROOT +"/"+ ca.research_paper.name)
#                attachments.append(settings.MEDIA_ROOT +"/"+ ca.acceptance_email.name)
#                notification.send(to_users, "feedback_conference_funding", context, attachments=attachments)

            return render_to_response("apply_research_success.html",
                                      RequestContext(request, {}))
    else:
        form = ConferenceApplicationForm()  # An unbound form

    return render(request, 'apply_conference.html', {
        'form': form,
    })
コード例 #34
0
def email(name, subject, mailid, file_path):
    email = EmailMessage("Respected, {}!!".format(name), subject, to=[mailid])
    email.attach_file(file_path)
    email.send()
    print("Email Sent")
コード例 #35
0
ファイル: EmailServices.py プロジェクト: lupulin/arabdicator
 def sendEmailWithAttachment(self, send_from, send_to, subject, body, files=[]):
     msg = EmailMessage(subject, body, send_from, [send_to])
     for f in files:
         msg.attach_file(f)
     msg.send()
コード例 #36
0
ファイル: utils.py プロジェクト: tanveerahmad1517/accounting
def send_email_with_invoice(template,
                            subject,
                            extra_email_context=None,
                            client_usernames=settings.BILLING_CYCLE_USERS,
                            create_invoice=False,
                            draft_invoice=False,
                            fill_line_items_from_jira=False,
                            upload_to_google_drive=False,
                            auto_approve=False):
    """
    Send an email with an invoice attached, and potentially perform peripheral actions.

    TODO: This function's pretty beefy; break it up by encapsulating logic into more utility functions or a new class.

    :param template: The email template.
    :param subject: The email subject.
    :param extra_email_context: Extra kwargs to update the email context with.
    :param client_usernames: The list of billing cycle users' usernames.
    :param create_invoice: Whether to create a new invoice based off of a past one.
    :param draft_invoice: Whether this is a draft invoice or not.
    :param fill_line_items_from_jira: Whether to fill up the invoice's line items from JIRA worklogs.
    :param upload_to_google_drive: Whether to upload the resulting invoice PDF to Google Drive.
                                   If using a draft invoice, it gets uploaded into `invoices-in/draft/{month}`.
    """
    if extra_email_context is None:
        extra_email_context = {}
    now = datetime.datetime.now()
    past = get_last_day_past_month()
    past_month_formatted = past.strftime('%B')
    template = get_template(template)
    for client_username in client_usernames:
        client = Account.objects.get(user__username=client_username)
        providers = [
            rate.provider
            for rate in client.client_hourly_rates.filter(active=True)
        ]
        for provider in providers:
            try:
                invoice = models.Invoice.objects.filter(
                    provider=provider,
                    client=client,
                    date__month=past.month if draft_invoice else now.month,
                ).latest('date')
            except models.Invoice.DoesNotExist:
                # This may be the provider's first invoice.
                invoice = None

            if create_invoice or not invoice:
                invoice = models.Invoice.objects.create(
                    number=choices.InvoiceNumberingScheme.increment_value(
                        invoice.template.numbering_scheme, invoice.number) if
                    invoice else choices.InvoiceNumberingScheme.default_value(
                        provider.invoice_template.numbering_scheme),
                    provider=provider,
                    client=client,
                    template=provider.invoice_template,
                )
            if fill_line_items_from_jira:
                invoice.fill_line_items_from_jira()

            # Make the email, attach the invoice, and send it.
            message_context = {
                'month': past_month_formatted,
                'contact_email': client.user.email
            }
            message_context.update(
                **resolve_dict_callables(extra_email_context, invoice))
            message = template.render(message_context)
            email = EmailMessage(
                subject=subject.format(month=past_month_formatted),
                body=message,
                to=[provider.user.email],
                cc=[client.user.email],
            )
            email.attach_file(invoice.to_pdf())
            email.send()

            # Upload the invoice to a directory in GDrive.
            if upload_to_google_drive:
                upload_invoice_to_google_drive(invoice,
                                               draft_invoice=draft_invoice)
            if auto_approve and not invoice.is_approved:
                invoice.approved = choices.InvoiceApproval.automatically
            invoice.save()
コード例 #37
0
ファイル: certificates.py プロジェクト: ISEAGE-ISU/cdc-signup
    def handle(self, *args, **options):
        if options['resend']:
            self.stdout.write("Resending for {}".format(options['resend']))
            checked_in = [base_models.Participant.objects.get(user__username=options['resend'])]
        else:
            self.stdout.write("Sending certifications to checked-in blue team participants")
            checked_in = base_models.Participant.objects.filter(checked_in=True, is_red=False, is_green=False,
                                                                team__isnull=False)

        cert_file = base_actions.get_global_setting('certificate_template')
        if not cert_file:
            self.stderr.write(self.style.ERROR('You need to specify a certificate template'))
            raise CommandError("Certificate not sepcified")
        cert_file = os.path.join(settings.MEDIA_ROOT, cert_file.name)
        self.stdout.write("Using certificate: {}".format(cert_file), self.style.MIGRATE_HEADING)

        cdc_name = base_actions.get_global_setting('competition_name')
        cdc_date = base_actions.get_global_setting('competition_date').strftime('%B %-d, %Y')
        emails = []

        tmp = tempfile.mkdtemp(prefix="signup-certs")

        num = 0
        for participant in checked_in:
            fields = [
                ('participant_name', participant.user.get_full_name()),
                ('cdc_name', cdc_name),
                ('issue_date', cdc_date),
            ]

            outfile = slugify(participant.user.username) + '.pdf'

            # Forge FDF
            fdf = forge_fdf("", fields, [], [], [])
            with open(os.path.join(tmp, 'data.fdf'), 'w') as fp:
                fp.write(fdf)

            # Fill PDF
            subprocess.check_call(["pdftk", cert_file, 'fill_form', 'data.fdf', 'output', outfile, 'flatten'], cwd=tmp)

            subject = "[CDC] {} Certificate".format(cdc_name)
            body = CERTIFICATE.format(fname=participant.user.first_name, lname=participant.user.last_name,
                                      support=settings.SUPPORT_EMAIL)

            message = EmailMessage(subject, body, settings.SUPPORT_EMAIL, [participant.user.email],
                                   reply_to=[settings.SUPPORT_EMAIL])
            message.attach_file(os.path.join(tmp, outfile))
            emails.append(message)
            if options['names']:
                self.stdout.write(" -> Generated Email for {}".format(participant))

            if not options['dry_run']:
                self.stdout.write(" -> Sending mail for {}".format(participant), self.style.MIGRATE_SUCCESS)
                message.send()
                num += 1

                if num > options['batch']:
                    time.sleep(BATCH_TIMER)
                    num = 0

        if not options['no_clean']:
            shutil.rmtree(tmp)