Beispiel #1
0
def sendExperimentResults(config):
    try:
        from sendgrid import SendGridAPIClient
        from sendgrid.helpers.mail import (Mail, Attachment, FileContent,
                                           FileName, FileType, Disposition,
                                           ContentId)

        message = Mail(
            from_email='*****@*****.**',
            to_emails='*****@*****.**',
            subject=f'Experiment results: {config.configurationDirectory}',
            html_content=
            f'These are your results for {config.configurationDirectory}. Please see the attached charts.'
        )

        for file in config.listAllFilesInFolder("charts"):
            data = config.loadKwolaFileData("charts", file)
            encoded = base64.b64encode(data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_type = FileType('image/png')
            attachment.file_name = FileName(file)
            attachment.disposition = Disposition('attachment')
            attachment.content_id = ContentId(file)
            message.add_attachment(attachment)

        videoFiles = config.listAllFilesInFolder("debug_videos")
        videoFiles = sorted(
            videoFiles,
            key=lambda fileName: pathlib.Path(
                os.path.join(config.configurationDirectory, "debug_videos",
                             fileName)).stat().st_mtime,
            reverse=True)
        for file in videoFiles[:2]:
            data = config.loadKwolaFileData("debug_videos", file)
            encoded = base64.b64encode(data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_type = FileType('video/mpeg')
            attachment.file_name = FileName(file)
            attachment.disposition = Disposition('attachment')
            attachment.content_id = ContentId(file)
            message.add_attachment(attachment)

        if 'sendgrid_api_key' in config:
            apiKey = config['sendgrid_api_key']
        elif 'SENDGRID_API_KEY' in os.environ:
            apiKey = os.environ.get('SENDGRID_API_KEY')
        else:
            getLogger().error(
                "There was no API key provided for Sendgrid. Please set sendgrid_api_key within your config.json file."
            )
            return

        sg = SendGridAPIClient(apiKey)
        response = sg.send(message)
    except Exception:
        getLogger().error(traceback.format_exc())
Beispiel #2
0
def sendMailWithPdf(email):
    #mailMsg = '{
    #       "subject": "subject",
    #      "to": "*****@*****.**",
    #     "from": "*****@*****.**",
    #    "text": "Text",
    #   "html": "",
    #  "filename": "stats.xlsx",
    # "contentId": "stats"
    #}'
    #mailMsgJson = json.loads(mailMsg)
    message = Mail()
    message.to = To(email.data['to'])
    message.subject = Subject(email.data['subject'], p=0)
    message.from_email = From(email.data['from'], 'My Team Manager')

    message.template_id = TemplateId(email.data['templateId'])
    message.attachment = Attachment(FileContent(email.data['pdf']),
                                    FileName(email.data['filename']),
                                    FileType('application/pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.content = Content(MimeType.text, email.data['text'])
    message.content = Content(MimeType.html, email.data['html'])
    sg = SendGridAPIClient(mailApiKey)
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
Beispiel #3
0
    def sendgrid_attachments(self, bodyobj):
        to_emails = self.transform_to_emails()
        message = Mail(from_email=('<email_change>', '<name_change>'),
                       to_emails=to_emails,
                       subject=self.subject,
                       html_content=bodyobj['body'])

        # attachments
        attchments = []
        for fle in bodyobj['logfiles']:
            if fle == 'None':
                continue
            else:

                with open(fle, 'rb') as f:
                    dta = f.read()
                    fname = os.path.basename(f.name)
                encoded = base64.b64encode(dta).decode()
                attachment = Attachment()
                attachment.file_content = FileContent(encoded)
                # text/plain text/comma-separated-values
                attachment.file_type = FileType('text/plain')
                attachment.file_name = FileName(fname)
                attachment.disposition = Disposition('attachment')
                attachment.content_id = ContentId('Example Content ID')
                attchments.append(attachment)
        message.attachment = attchments
        try:
            sendgrid_client = SendGridAPIClient(self.apikey)
            response = sendgrid_client.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e)
Beispiel #4
0
def EmergencyMail(mail_subject, html_content, file_path):
    """This function utilizes SendGrid Api to send emergcency signals as email
    to the necessary agencies"""
    message = Mail(from_email=current_app.config['APP_EMAIL'],
                   to_emails=current_app.config['AGENT_EMAILS'].split(' '),
                   subject=mail_subject,
                   html_content=html_content)

    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()

    # encode file
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/xls')
    attachment.file_name = FileName('data.xls')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('PatientData')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        resp = sg.send(message)
        return True
    except HTTPError as e:
        #print(f"{resp.status_code}'\n'{resp.body}'\n'{resp.headers}")
        print(e.to_dict)
        return False
    else:
        print(e.to_dict)
        return False
Beispiel #5
0
def send_styled_email(to_email):
    load_dotenv(dotenv_path='sendgrid.env')

    message = Mail(
        from_email='*****@*****.**',
        to_emails=to_email,
        subject='Here is your Stylized image!',
        html_content=
        '<strong>and easy to do anywhere, even with Python</strong>')
    file_path = 'output.jpg'
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/jpg')
    attachment.file_name = FileName('output.jpg')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    try:
        sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sendgrid_client.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)
Beispiel #6
0
def send_email(email_to):
    message = Mail(
        from_email='*****@*****.**',
        to_emails=email_to,
        subject='Crypto Investment CSV File',
        html_content='<strong>Here is the file you requested.</strong>')

    file_path = os.path.join(os.getcwd(), "trades.csv")
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()

    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/csv')
    attachment.file_name = FileName('trades.csv')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient(
            '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'
        )
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
        return response.status_code
    except Exception as e:
        print(e.message)
Beispiel #7
0
def SendMail(ImgFileName):
    message = Mail(
        from_email='*****@*****.**',
        to_emails='*****@*****.**',
        subject='SURVEILLANCE ALERT: Unauthorized Access of MAIN GATE',
        html_content=
        '<strong>REPORT FOR INTRUSION DETECTION: Person has crossed the area, Here we attached a reference image </strong>'
    )

    data = cv2.imencode('.jpg', ImgFileName)[1].tostring()

    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/jpg')
    attachment.file_name = FileName('alert.jpg')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment

    try:
        sendgrid_client = SendGridAPIClient(
            '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'
        )
        response = sendgrid_client.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)

    except Exception as e:
        print(e)
Beispiel #8
0
def send_email(subject="Workout",
               html="<p>Today's Workout</p>",
               pdf="workout.pdf"):
    client = SendGridAPIClient(
        SENDGRID_API_KEY)  #> <class 'sendgrid.sendgrid.SendGridAPIClient>
    message = Mail(from_email=MY_EMAIL,
                   to_emails=MY_EMAIL,
                   subject=subject,
                   html_content=html)
    #attaches the PDF we generated earlier
    file_path = 'workout.pdf'
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/pdf')
    attachment.file_name = FileName('JuicyLiftWorkout.pdf')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    #send email
    try:
        response = client.send(message)
        return response
    except Exception as e:
        print("OOPS", e.message)
        return None
Beispiel #9
0
 def MailGrid(self,*args,**kwargs):
     mail_txt = Content('text/plain',emailbody)
     message = Mail(
         from_email=sendermail,
         to_emails=recivermail,
         subject=subject,
         html_content=htmlcontent
         )
     message.add_content(mail_txt)
     if attach is not None:
         if os.path.isfile(attach):
             head, tail = os.path.split(attach)
             with open(attach, 'rb') as f:
                 data = f.read()
                 f.close()
             encoded = base64.b64encode(data).decode()
         else:
             encoded = attach
         attachment = Attachment()
         attachment.file_content = FileContent(encoded)
         attachment.file_type = FileType('application/pdf')
         attachment.file_name = FileName(tail)
         attachment.disposition = Disposition('attachment')
         attachment.content_id = ContentId('Example Content ID')
         message.attachment = attachment
     SENDGRID_API_KEY = "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"
     sendgrid_client = sendgrid.SendGridAPIClient(SENDGRID_API_KEY )
     response = sendgrid_client.send(message)
     print(response.status_code)
     print(response.body)
     print(response.headers)
def send(filename, job, city, email_receiver, sendgrid_api_key,
         sendgrid_email_sender):
    try:
        sg = sendgrid.SendGridAPIClient(api_key=sendgrid_api_key)

        message = Mail(
            from_email=sendgrid_email_sender,
            to_emails=email_receiver.replace(',', ''),
            subject=f"LinkedIn: {job} jobs in {city} (Weekly).",
            html_content=
            f"Automated report for {job} jobs in {city} generated on {datetime.datetime.now()}."
        )

        with open(filename, 'rb') as f:
            data = f.read()
            f.close()
        encoded = base64.b64encode(data).decode()
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType('application/csv')
        attachment.file_name = FileName(filename)
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId('')
        message.attachment = attachment

        response = sg.client.mail.send.post(request_body=message.get())

        print(f"\n\033[1m📩 Email sent successfully to {email_receiver}\033[0m")

    except Exception as e:
        print("Error:", e)
        print(
            "\n\033[1m❌ An error occurred while trying to send the email!\033[0m"
        )
def send_email(email_to):
    message = Mail(
        from_email = '*****@*****.**',
        to_emails = email_to,
        subject='Mango Investment CSV File',
        html_content='<strong>Here is the file you requested.</strong>')

    file_path = os.path.join(os.getcwd(), "trades.csv")
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()
        
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/csv')
    attachment.file_name = FileName('trades.csv')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient('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')
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
        return response.status_code
    except Exception as e:
        print(e.message)
Beispiel #12
0
    def send_zip(self, file_name: str, data: bytes) -> bool:
        # create message
        message = Mail(self.from_email, self.to_email, self.subject,
                       self.content)

        # create attachment
        file_type = 'GED file'
        encoded = base64.b64encode(data).decode()
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType(file_type)
        attachment.file_name = file_name
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId('Example Content ID')
        message.attachment = attachment

        # This code is for testing purposes.
        # Allows to test the class above without sending mail.
        # If a value in "SENDGRID_TEST" environment equals to "True" this function will return boolean True
        # otherwise this function will return boolean False.
        if os.environ.get("SENDGRID_TEST") is not None:
            return os.environ.get("SENDGRID_TEST") == "True"

        # send
        try:
            sg = SendGridAPIClient(self.api_key)
            response = sg.send(message)
            logger.info(
                "Sent gedcom successfully with response code: {}".format(
                    response.status_code))
            return True
        except Exception:
            logger.exception("Failed to sent gedcom")
            return False
Beispiel #13
0
def send_simple_mail(subj='Sending with Twilio SendGrid is Fun'):
    message = Mail(
        from_email='*****@*****.**',
        to_emails='*****@*****.**',
        subject=subj,
        html_content=
        '<strong>and easy to do anywhere, even with Python</strong>')

    import os
    THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(THIS_FOLDER, 'bumblebees-flowers.jpg')
    # file_path = 'bumblebees-flowers.jpg'
    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/jpeg')
    attachment.file_name = FileName('bumblebees-flowers.jpg')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment

    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)
Beispiel #14
0
def sendMailWithAttachment(context):
    # print(context)
    html_version = 'email/email.html'
    message = Mail(
        from_email='*****@*****.**',
        to_emails=context['emails'],
        subject="Reg: Payment remittance for {} ${} {} Vendor : {}".format(
            context["clearing_date"], context["amount"], context["currency"],
            context["supplier"]),
        html_content=render_to_string(html_version, {'context': context}))
    with open(context['attachment'], 'rb') as f:
        data = f.read()
        f.close()
    print(data)
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('text/csv')
    attachment.file_name = FileName(context['attachment'])
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('REMITTANCE')
    message.add_attachment(attachment)
    try:
        sg = SendGridAPIClient(
            "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"
        )
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)


# sendMailWithAttachment()
Beispiel #15
0
def send_email(subject="Unemployment Data",
               html="<p>Unemployment Data</p>",
               png=image_name):
    client = SendGridAPIClient(
        SENDGRID_API_KEY)  #> <class 'sendgrid.sendgrid.SendGridAPIClient>
    message = Mail(from_email=MY_EMAIL,
                   to_emails=MY_EMAIL,
                   subject=subject,
                   html_content=html)

    #Attaches the PNG we Generated Earlier Using Selenium

    with open(image_name, 'rb') as f:
        image = f.read()
        f.close()

    image_encoded = base64.b64encode(image).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(image_encoded)
    attachment.file_type = FileType('image/png')
    attachment.file_name = FileName('unemployment_rate.png')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment

    #Send Email
    try:
        response = client.send(message)
        print(response.status_code)
        print(response.body)
        return response

    except Exception as e:
        print("OOPS", e.message)
        return None
Beispiel #16
0
    def email(self, to_email, template, data):
        # We always append on the destination url to help.
        data['url'] = secret.get()['url']

        # Build the mail object & send the email.

        # Attach the ics to the email
        c = generate_ics()

        message = Mail(from_email=self.from_email, to_emails=to_email)
        message.dynamic_template_data = data
        message.template_id = self.templates[template]

        encoded = base64.b64encode(str(c).encode('utf-8')).decode()
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType('text/calendar')
        attachment.file_name = FileName('shift.ics')
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId('Example Content ID')
        message.attachment = attachment

        try:
            sendgrid_client = SendGridAPIClient(api_key=self.api_key)
            response = sendgrid_client.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e)
    def send_email(self, email, pdf_path):
        message = Mail(
            from_email="Aditya Raman <*****@*****.**>",
            to_emails=email,
            subject="[MSP Testing] Testing for Attendee's Certificate",
            html_content=" Sending the attachment<br>",
        )

        file_path = pdf_path
        file_name = list(file_path.split("/"))[-1]
        with open(file_path, "rb") as f:
            data = f.read()
            f.close()
        encoded = base64.b64encode(data).decode()
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType(
            "application/pdf")  # FileType("image/png")
        attachment.file_name = FileName(file_name)
        attachment.disposition = Disposition("attachment")
        attachment.content_id = ContentId("Microsoft Student Partner")
        message.attachment = attachment
        try:
            sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
            response = sg.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
            return response
        except Exception as e:
            print(e)
            return e
Beispiel #18
0
def job():
    prices = []
    stars = []
    titles = []
    urlss = []

    pages_to_scrape = 10
    pages = [('http://books.toscrape.com/catalogue/page-{}.html').format(i)
             for i in range(1, pages_to_scrape + 1)]

    for item in pages:
        page = requests.get(item)
        soup = bs4(page.text, 'html.parser')
        for i in soup.findAll('h3'):
            titles.append(i.getText())
        for j in soup.findAll('p', class_='price_color'):
            prices.append(j.getText())
        for s in soup.findAll('p', class_='star-rating'):
            for k, v in s.attrs.items():
                stars.append(v[1])
        divs = soup.findAll('div', class_='image_container')
        for thumbs in divs:
            tgs = thumbs.find('img', class_='thumbnail')
            urls = 'http://books.toscrape.com/' + str(tgs['src'])
            newurls = urls.replace("../", "")
            urlss.append(newurls)
    data = {'Title': titles, 'Prices': prices, 'Stars': stars, "URLs": urlss}
    df = pd.DataFrame(data=data)
    df.index += 1
    directory = os.path.dirname(os.path.realpath(__file__))
    filename = "scrapedfile.csv"
    file_path = os.path.join(directory, 'csvfiles/', filename)
    df.to_csv(file_path)

    with open(file_path, 'rb') as f:
        data = f.read()
        f.close()

    encoded = base64.b64encode(data).decode()
    message = Mail(
        from_email=FROM_EMAIL,
        to_emails=TO_EMAIL,
        subject='Your File is Ready',
        html_content='<strong>Attached is Your Scraped File</strong>')
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('text/csv')
    attachment.file_name = FileName('scraped.csv')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)
def send_mail_sendgrid(description, agenda: Agenda):
    c = Calendar()
    e = Event()
    e.name = 'Atendimento Aset Terapias'

    str_begin = '-'.join(reversed(agenda.date.split('/')))
    str_begin = f'{str_begin} {agenda.time}'
    e.begin = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') +
               timedelta(hours=3))
    e.end = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') +
             timedelta(hours=4))

    e.attendees = [agenda.appointment.customer.email, agenda.therapist.email]
    e.description = description
    c.events.add(e)

    curdir = os.getcwd()

    with open(f'{curdir}{os.sep}go.ics', 'w') as f:
        f.writelines(c)

    with open(
            f'{curdir}{os.sep}apps{os.sep}agenda{os.sep}email_templates{os.sep}appointment-confirmation.html',
            encoding='utf-8') as templ:
        body = ''.join(templ.readlines())
        body = body.replace('{{nome}}', agenda.appointment.customer.name)
        body = body.replace('{{nome_terapia}}', agenda.appointment.specialty)
        body = body.replace('{{nome_terapeuta}}', agenda.therapist.name)
        body = body.replace('{{data}}', agenda.date)
        body = body.replace('{{hora}}', agenda.time)

        body = body.replace('{{api}}', os.getenv("API_ENDPOINT"))
        body = body.replace('{{calendar}}', agenda.calendar.name)
        body = body.replace('{{therapist_mail}}', agenda.therapist.email)
        body = body.replace('{{date}}', agenda.date.replace('/', '-'))
        body = body.replace('{{hour}}', agenda.time)
        body = body.replace('{{text}}', agenda.appointment.text)

        message = Mail(from_email=os.getenv("EMAIL_SENDER"),
                       to_emails=agenda.appointment.customer.email,
                       subject='Aset Terapias : Confirmação de consulta',
                       html_content=body)
        try:
            message.add_bcc(agenda.therapist.email)
            with open(f'{curdir}{os.sep}go.ics', 'rb') as f:
                data = f.read()
                f.close()
            encoded = base64.b64encode(data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_name = FileName('go.ics')
            attachment.disposition = Disposition('attachment')
            attachment.content_id = ContentId('Unique Content ID')
            message.attachment = attachment
            sg = SendGridAPIClient(api_key=os.getenv('EMAIL_TOKEN'))
            sg.send(message=message)
        except Exception as e:
            print('Erro no envio de e-mail')
            print(e)
Beispiel #20
0
def email_thread(queue: Queue, API: str, TESTER: str, EMAIL: str):
    status = ''
    running = True
    while running:
        data = queue.get()
        if data.message_type == 1:
            status = status + data.task_name + ': ' + data.message + '\n'
        elif data.message_type == 2:
            status = status + 'Warning: ' + data.task_name + ': ' + data.message + '\n'
        elif data.message_type == 3:
            status = status + 'Error: ' + data.task_name + ': ' + data.message + '\n'
        elif data.message_type == 4:
            status = status + 'Error: Test Failed: ' + data.task_name + '\n' + \
                str(data.exception[0]) + '\n' + str(data.exception[1]
                                                    ) + '\n' + traceback.format_tb(data.exception[2])[0]
            running = False
        elif data.message_type == 0:
            status = status + 'Test from unit: ' + TESTER + \
                ' has completed successfully, see results attached'
            running = False
            file_name = data.file_name
        print(data.task_name + ': ' + data.message)
        queue.task_done()
    print('sending email')
    zip_file = '{}.zip'.format(file_name)
    with ZipFile(zip_file, 'w') as zip:
        zip.write('{}.jpg'.format(file_name))
        zip.write('{}_hist.png'.format(file_name))
        zip.write('{}_hist.json'.format(file_name))

    message = Mail(from_email=TESTER + '@example.com',
                   to_emails=EMAIL,
                   subject='Test Results for Tester: ' + TESTER +
                   ' at time: x',
                   html_content='<p>' + status + '<p>')
    with open(zip_file, 'rb') as f:
        data = f.read()
        f.close()
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/zip')
    attachment.file_name = FileName('{}.zip'.format(file_name))
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Test Results')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient(API)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(str(type(e)) + ' ' + str(e))
    # code for sending email
    print('finished sending email')
    print(status)
Beispiel #21
0
def final_s():
    directory = os.path.dirname(os.path.realpath(__file__))
    filename2 = "results.csv"
    final_r = "virtual.csv"
    filename = "scrapedfile.csv"
    file_path = os.path.join(directory, 'clean/', filename)
    file_path3 = os.path.join(directory, 'clean/', final_r)
    file_path2 = os.path.join(directory, 'clean/', filename2)
    f = pd.read_csv(file_path)
    h = pd.read_csv(file_path2)
    df_merge_col = pd.merge(f, h, on='Match No')
    del df_merge_col['HomeTeam_y']
    del df_merge_col['AwayTeam_y']

    df_merge_col = df_merge_col.rename(columns={
        'HomeTeam_x': 'HomeTeam',
        'AwayTeam_x': 'AwayTeam'
    })

    df_merge_col.to_csv(file_path3, index=False)

    file_data = pd.read_csv(file_path3)
    dr = file_data.drop_duplicates(subset=['Match No'], keep='first')
    dr.to_csv(file_path3, index=False)
    insert()
    with open(file_path3, 'rb') as file:
        data_ = file.read()
        file.close()

    encoded = base64.b64encode(data_).decode()
    message = Mail(
        from_email=FROM_EMAIL,
        to_emails=TO_EMAIL,
        subject='Your File is Ready',
        html_content='<strong>Attached is Your Scraped File</strong>')
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('text/csv')
    x = datetime.datetime.now()
    w = x.strftime("%d_%b_%Y")
    filename = 'virtuals_' + str(w) + '.csv'
    attachment.file_name = FileName(filename)
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)
    os.remove(file_path)
    print(
        'combined the two csv files and created the final virtuals dataframe\nAnd then deleted the scrapedfile'
    )
def sendgrid_mailer_main() -> None:
    """Main module entry point"""
    log.info(" --- Started sendgrid_mailer module --- ")
    log.info(" Trying to open email_body_txt_m4.txt for email body content ")
    with open('email_body_txt_m4.txt') as file_object:
        file_content = file_object.readlines()

    log.info("Creating email body content from email_body_txt_m4.txt file ")
    email_body_content = ''.join([i for i in file_content[1:]])

    # Creates Mail object instance
    message = Mail(
        from_email=(os.environ.get('SRC_EMAIL')),
        to_emails=(os.environ.get('DEST_EMAIL')),
        subject='Ogre Apartments for sale from ss.lv webscraper v1.4.5',
        plain_text_content=email_body_content)

    report_file_exists = os.path.exists('Ogre_city_report.pdf')
    log.info(
        "Checking if file Ogre_city_report.pdf exists and reading as binary ")
    if report_file_exists:
        # Binary read pdf file
        file_path = 'Ogre_city_report.pdf'
        with open(file_path, 'rb') as file_object:
            data = file_object.read()
            file_object.close()

        # Encodes data with base64 for email attachment
        encoded_file = base64.b64encode(data).decode()

        # Creates instance of Attachment object
        log.info("Attaching  encoded Ogre_city_report.pdf to email object")
        attached_file = Attachment(file_content=FileContent(encoded_file),
                                   file_type=FileType('application/pdf'),
                                   file_name=FileName('Ogre_city_report.pdf'),
                                   disposition=Disposition('attachment'),
                                   content_id=ContentId('Example Content ID'))

        # Calls attachment method for message instance
        message.attachment = attached_file

    try:
        log.info("Attempting to send email via Sendgrid API")
        sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sendgrid_client.send(message)
        log.info(f"Email sent with response code: {response.status_code}")
        log.info(f" --- Email response body --- ")
        #log.info(f" {response.body} ")
        log.info(f" --- Email response headers --- ")
        #log.info(f" {response.headers}")
    except Exception as e:
        log.info(f"{e.message}")
        print(e.message)
    remove_tmp_files()
    log.info(" --- Ended sendgrid_mailer module --- ")
Beispiel #23
0
def build_attachment(file_path, disposition="attachment", content_id="Ebook"):
    filename, file_type, content = file_info(file_path)

    attachment = Attachment()
    attachment.file_content = FileContent(content)
    attachment.file_type = FileType(file_type)
    attachment.file_name = FileName(filename)
    attachment.disposition = Disposition(disposition)
    attachment.content_id = ContentId(content_id)

    return attachment
Beispiel #24
0
def _attachment(b64data,
                mime_type,
                filename,
                content_id,
                disposition='attachment'):
    attachment = Attachment()
    attachment.file_content = FileContent(b64data)
    attachment.file_type = FileType(mime_type)
    attachment.file_name = FileName(filename)
    attachment.disposition = Disposition(disposition)
    attachment.content_id = ContentId(content_id)
    return attachment
def set_email_attachment(filename, encoded):
    try:
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType('text/csv')
        attachment.file_name = FileName(filename)
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId(filename)

        return attachment
    except:
        return None
 def test_attachment(self):
     from sendgrid.helpers.mail import (FileContent, FileType, FileName,
                                        Disposition, ContentId)
     a1 = Attachment(FileContent('Base64EncodedString'),
                     FileName('example.pdf'), FileType('application/pdf'),
                     Disposition('attachment'), ContentId('123'))
     a2 = Attachment('Base64EncodedString', 'example.pdf',
                     'application/pdf', 'attachment', '123')
     self.assertEqual(a1.file_content.get(), a2.file_content.get())
     self.assertEqual(a1.file_name.get(), a2.file_name.get())
     self.assertEqual(a1.file_type.get(), a2.file_type.get())
     self.assertEqual(a1.disposition.get(), a2.disposition.get())
     self.assertEqual(a1.content_id.get(), a2.content_id.get())
Beispiel #27
0
def push_email(email_content, user_email):
    message = Mail(from_email='*****@*****.**',
                   to_emails=user_email,
                   subject='Bahi Khata Report',
                   html_content=email_content)
    file_path = './static/images/bahi_khata.png'
    with open(file_path, 'rb') as f:
        data = f.read()
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('image/png')
    attachment.file_name = FileName('bahi_khata.png')
    attachment.disposition = Disposition('inline')
    attachment.content_id = ContentId('bahikhatalogo')
    message.attachment = attachment
    file_path = './data/report.png'
    with open(file_path, 'rb') as f:
        data = f.read()
    encoded = base64.b64encode(data).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('image/png')
    attachment.file_name = FileName('report.png')
    attachment.disposition = Disposition('inline')
    attachment.content_id = ContentId('report')
    message.attachment = attachment
    with open('data/sendgrid.json') as f:
        SG_API_KEY = f.readline()
    try:
        sg = SendGridAPIClient(SG_API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.to_dict)
    return "sent email"
Beispiel #28
0
def build_attachment(attachmentFileName, mimetype):
    """Build attachment mock."""
    if not os.path.exists(attachmentFileName):
        logger.error("cannot open attachment %s", attachmentFileName)
        return None
    _, name = os.path.split(attachmentFileName)
    attachment = Attachment()
    attachment.file_content = FileContent(
        base64.b64encode(open(attachmentFileName, "rb").read()).decode())
    attachment.file_type = FileType(mimetype)
    attachment.file_name = FileName(name)
    attachment.disposition = Disposition("attachment")
    attachment.content_id = ContentId("Custom Report")
    return attachment
Beispiel #29
0
    def email_log(self,
                  sender,
                  receiver1,
                  receivers,
                  subject_,
                  body,
                  file_path,
                  attached=True):

        sender = '*****@*****.**'
        from_email = (sender, "")
        to_emails = [(receiver1, "")]
        if receivers != None:
            for i in receivers:
                to_emails.append((i, ""))

        subject = self.hostname + ':' + subject_

        if len(body) == 1:
            content_ = 'Dear Admin Team,\n ' + body[0] + ' has started at ' + str(
                datetime.now()
            ) + '. We will send you a log file as soon as processing is completed. Please review the log file as soon as you receive them for exceptions and take appropriate actions.\n \n Best regards,\n FLIPT Integration Team'
        else:
            content_ = 'Dear Admin Team,\n ' + body[0] + ' is completed at ' + str(
                datetime.now()
            ) + '. Please review the attached log file for exceptions and take appropriate actions. Also run Couchbase ' + body[
                1] + ' SQL to find more information.\n \n Best regards,\n FLIPT Integration Team'

        content = Content("text/plain", content_)
        mail = Mail(from_email=from_email,
                    to_emails=to_emails,
                    subject=subject,
                    plain_text_content=content)

        data = None
        if attached == True:
            with open(file_path, 'rb') as f:
                data = f.read()
                f.close()
            encoded = base64.b64encode(data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_type = FileType("application/pdf")
            attachment.file_name = FileName(file_path.split('/')[-1])
            attachment.disposition = Disposition("attachment")
            attachment.content_id = ContentId("Example Content ID")
            mail.attachment = attachment

        response = self.sg.send(mail)
Beispiel #30
0
def send_email(
    to_emails: Union[str, List[str]], 
    subject: str, 
    body: str = None, 
    file_name: str = None, 
    file_type: str = None, 
    template_id: str = None
):
    from_email = sendgrid_from_email
    sg = sendgrid.SendGridAPIClient(sendgrid_api_key)
    content = Content(
        'text/plain',
        body
    )
    
    if file_type == 'xlsx':
        file_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    elif file_type == 'pptx':
        file_type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
    elif file_type == 'docx':
        file_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    elif file_type == 'pdf':
        file_type = 'application/pdf'

    mail = Mail(from_email, to_emails, subject, content) 

    if file_name:
        # encode binary file so it can be JSON serialised for SendGrid call
        with open(file_name, 'rb') as f:
            data = f.read()
            f.close()
        encoded = base64.b64encode(data).decode()

        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType(file_type)
        attachment.file_name = FileName(file_name)
        attachment.disposition = Disposition("attachment")
        attachment.content_id = ContentId("Example Content ID")

        mail.attachment = attachment

    if template_id:
        mail.template_id = template_id

    response = sg.send(mail) 

    return response