Beispiel #1
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 #2
0
 def send(self, message, envelope_from=None):
     assert message.send_to, "No recipients have been added"
     assert message.sender, (
         "The message does not specify a sender and a default sender "
         "has not been configured")
     if message.has_bad_headers():
         raise BadHeaderError
     if message.date is None:
         message.date = time.time()
     if not message.subject:
         message.subject = word("(no subject)")
     sgmessage = SGMail(
         from_email=Email(message.sender),
         to_emails=[
             To(addressee)
             for addressee in sanitize_addresses(message.recipients)
         ],
         subject=message.subject,
         plain_text_content=message.body,
         html_content=message.html)
     if message.reply_to:
         sgmessage.reply_to = ReplyTo(message.reply_to)
     if message.cc:
         for recipient in list(sanitize_addresses(message.cc)):
             sgmessage.add_cc(recipient)
     if message.bcc:
         for recipient in list(sanitize_addresses(message.bcc)):
             sgmessage.add_bcc(recipient)
     if message.attachments:
         for flask_attachment in message.attachments:
             attachment = Attachment()
             attachment.file_content = FileContent(
                 base64.b64encode(flask_attachment.data).decode())
             attachment.file_type = FileType(flask_attachment.content_type)
             attachment.file_name = FileName(flask_attachment.filename)
             attachment.disposition = Disposition(
                 flask_attachment.disposition)
             sgmessage.add_attachment(attachment)
     sg = SendGridAPIClient(self.mail.api_key)
     response = sg.send(sgmessage)
     if response.status_code >= 400:
         logmessage("SendGrid status code: " + str(response.status_code))
         logmessage("SendGrid response headers: " + repr(response.headers))
         try:
             logmessage(repr(response.body))
         except:
             pass
         raise Exception("Failed to send e-mail message to SendGrid")
     email_dispatched.send(message, app=current_app._get_current_object())
Beispiel #3
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 #4
0
def email_transaction():
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    #To obtain the email of the user
    cursor.execute('SELECT email FROM user WHERE id=%s', (session['id'], ))
    em = cursor.fetchone()
    #To obtain a detailed list of all the expenses as per the chosen time frame.
    cursor.execute(
        'SELECT amount,category,date,description FROM expense_a WHERE id =%s AND monthname(date)=%s AND YEAR(date)=%s ',
        (session['id'], session['s_m'][5:], session['s_m'][0:4]))
    result = cursor.fetchall()

    df = pd.DataFrame(result)
    df_update = df.rename(
        columns={
            'amount': 'Amount(in $)',
            'category': 'Category',
            'date': 'Date',
            'description': 'Description'
        })

    df_update.to_csv(r'transaction.csv', index=False)

    with open('transaction.csv', 'rb') as f:
        data = f.read()
        f.close()
    message = Mail(
        from_email='*****@*****.**',
        to_emails=em['email'],
        subject='Transaction Report For The Month Of' + '-' + session['s_m'],
        html_content=
        'Below you will find attached a detailed copy of your transactions for the month of'
        + ' ' + session['s_m'])

    encoded_file = base64.b64encode(data).decode()

    attachedFile = Attachment(
        FileContent(encoded_file),
        FileName('transaction' + '_' + session['s_m'] + '.csv'),
        FileType('transaction/csv'), Disposition('attachment'))
    message.attachment = attachedFile

    sg = SendGridAPIClient(
        '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'
    )
    response = sg.send(message)
    print(response.status_code, response.body, response.headers)
    flash(u"E-mail has been sent", "success")
    return redirect(url_for('dashboard'))
Beispiel #5
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
Beispiel #6
0
def add_results_attachment(email, filename=None):
    my_attachment = Attachment()
    attachment_type = filename.split(".")[1]
    if attachment_type == "csv":
        my_attachment.file_type = FileType(
            "application/{}".format(attachment_type))
    else:
        my_attachment.file_type = FileType("application/text")
    my_attachment.file_name = FileName("results.{}".format(attachment_type))
    my_attachment.disposition = Disposition("attachment")
    my_attachment.content_id = ContentId("results file")
    with open(filename, 'rb') as f:
        data = f.read()
    my_attachment.file_content = FileContent(base64.b64encode(data).decode())
    email.add_attachment(my_attachment)
    return email
Beispiel #7
0
def email_transaction():
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute('SELECT email FROM user WHERE id=%s', (session['id'], ))
    em = cursor.fetchone()
    cursor.execute(
        'SELECT ex_id,amount,category,date,description FROM expense_a WHERE id =%s AND monthname(date)=%s ',
        (
            session['id'],
            session['s_m'],
        ))
    result = cursor.fetchall()
    df = pd.DataFrame(result)
    df_update = df.rename(
        columns={
            'ex_id': 'EX_ID',
            'amount': 'Amount',
            'category': 'Category',
            'date': 'Date',
            'description': 'Description'
        })
    #header=['EX_ID','Amount','Category','Date','Description']
    df_update.to_csv(r'transaction.csv', index=False)

    with open('transaction.csv', 'rb') as f:
        data = f.read()
        f.close()
    message = Mail(
        from_email='*****@*****.**',
        to_emails=em['email'],
        subject='Transaction Report For The Month Of' + '-' + session['s_m'],
        html_content=
        'Below you will find attached a detailed copy of your transactions for the month of'
        + ' ' + session['s_m'])

    encoded_file = base64.b64encode(data).decode()

    attachedFile = Attachment(
        FileContent(encoded_file),
        FileName('transaction' + '_' + session['s_m'] + '.csv'),
        FileType('transaction/csv'), Disposition('attachment'))
    message.attachment = attachedFile

    sg = SendGridAPIClient(SENDGRID_API_KEY)
    response = sg.send(message)
    print(response.status_code, response.body, response.headers)
    flash(u"E-mail has been sent", "success")
    return redirect(url_for('dashboard'))
Beispiel #8
0
def send_email_task_sendgrid(payload):
    message = Mail(
        from_email=From(payload['from'], payload['fromname']),
        to_emails=payload['to'],
        subject=payload['subject'],
        html_content=payload["html"],
    )

    if payload['bcc'] is not None:
        message.bcc = payload['bcc']

    if payload['reply_to'] is not None:
        message.reply_to = payload['reply_to']

    if payload['attachments'] is not None:
        for filename in payload['attachments']:
            with open(filename, 'rb') as f:
                file_data = f.read()
                f.close()
            encoded = base64.b64encode(file_data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.disposition = Disposition('attachment')
            if filename.endswith('.pdf'):
                attachment.file_type = FileType('application/pdf')
                attachment.file_name = FileName(filename)
            elif filename.endswith('.ics'):
                attachment.file_type = FileType('text/calendar')
                attachment.file_name = FileName('ical.ics')
            message.add_attachment(attachment)
    sendgrid_client = SendGridAPIClient(get_settings()['sendgrid_key'])
    logging.info(
        'Sending an email to {} regarding "{}" on behalf of {}'.format(
            payload['to'], payload["subject"], payload["from"]
        )
    )
    try:
        sendgrid_client.send(message)
        logging.info('Email sent successfully')
    except urllib.error.HTTPError as e:
        if e.code == 429:
            logging.warning("Sendgrid quota has exceeded")
            send_email_task_smtp.delay(payload)
        elif e.code == 554:
            empty_attachments_send(sendgrid_client, message)
        else:
            logging.exception(f"The following error has occurred with sendgrid-{str(e)}")
def send_mail():
    API_KEY = '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'

    import base64
    import os
    import json
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName,
                                       FileType, Disposition, ContentId)
    try:
        # Python 3
        import urllib.request as urllib
    except ImportError:
        # Python 2
        import urllib2 as urllib

    import os
    import json
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail

    message = Mail(from_email='*****@*****.**',
                   to_emails='*****@*****.**',
                   subject='Helmet Found',
                   html_content='<strong>Pass</strong>')
    file_path = 'C:/Tensorflow/models/research/object_detection/zresult/imagepdf.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('Helmet Found.pdf')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    message.attachment = attachment
    try:
        #for environ on computer
        #sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sendgrid_client = SendGridAPIClient(API_KEY)
        response = sendgrid_client.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)
Beispiel #10
0
    def create_email(
        self,
        to_list: List["str"],
        subject: str,
        html_content: str,
        image: bytes = None,
        content_type: str = None,
        send_at: datetime = None,
    ) -> Mail:
        """
        Create a new sendgrid email object.

        Params:
        ------
        to_list: List[str] - The recipients list.
        subject: str - The email subject.
        html_contentet: str - HTML text to fill the email.
        image: bytes - A optional image to attachment in email.
        content_type: str - The content type of the image.
        send_at: datetime - The datetime when the email must be sended.

        Return:
        ------
        message: Mail - The sendgrid email object.
        """
        message = Mail()
        message.from_email = From(self.from_email)
        message.subject = Subject(subject)

        _users_list = []
        for _to in to_list:
            _users_list.append(To(_to))
        message.to = _users_list

        if image:
            ext = str(content_type).split("/")[1]
            timestamp = datetime.utcnow().strftime("%Y-%m-%d-%H%M%S")
            message.attachment = Attachment(
                FileContent(image), FileName(f'event_image-{timestamp}.{ext}'),
                FileType(str(content_type)), Disposition('attachment'))

        if send_at:
            message.send_at = SendAt(self.get_unix_time(send_at), p=0)

        message.content = Content(MimeType.html, html_content)
        return message
    def send(self):
        if self.send_mail == 0:
            return

        if len(self.to_emails) > 1:
            is_multiple = True
        else:
            is_multiple = False
      
        message = Mail(
            from_email=self.from_email,
            to_emails=self.to_emails,
            subject=self.subject,
            html_content=self.html_content,
            is_multiple=is_multiple)

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

        encoded_file = base64.b64encode(data).decode()
        
        if platform.system() == "Windows":
            divider = "\\"
        else:
            divider = "/"
        parts = self.filename.split(divider)
        actual_filename = parts[len(parts) - 1]
        print(actual_filename)

        attachedFile = Attachment(
            FileContent(encoded_file),
            FileName(actual_filename),
            FileType(
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
            Disposition('attachment')
        )
        message.attachment = attachedFile

        try:
            SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            response = sg.send(message)

        except Exception as e:
            print(e.message)
Beispiel #12
0
 def sendfile(self, to=[], subject="test", content="", filename=""):
     message = Mail(from_email=self.sender,
                    to_emails=to,
                    subject=subject,
                    html_content='<strong> ' + content + ' </strong>')
     with open(filename, 'rb') as f:
         data = f.read()
         f.close()
     encoded_file = base64.b64encode(data).decode()
     attachedFile = Attachment(
         FileContent(encoded_file), FileName(filename.rsplit("/", 1)[1]),
         FileType('application/' + filename.rsplit(".", 1)[1]),
         Disposition('attachment'))
     message.attachment = attachedFile
     self.response = response = self.sg.send(message)
     print(response.status_code, response.body, response.headers)
     return response.status_code
Beispiel #13
0
def _send_email_with_sendgrid(email_server, to, subject, body, attachments=[]):
    '''
    email_server: dict
    to: string | string[]
    subject: string
    body: string | MIMEMultipart
    attachments: string[] - paths to text files to attach to the email

    Send an email.
    '''
    from_address = email_server['fromAddress']
    api_key = email_server['apiKey']

    if None in [from_address, api_key]:
        log.warning('Required environment variables for sending emails do not exist. No emails sent. See README.md for more details.')

        return

    message = Mail(
        from_email=from_address,
        to_emails=to,
        subject=subject,
        html_content=body)

    for location in attachments:
        path = Path(location)

        encoded_log = _gzip(path)

        if encoded_log is None:
            continue

        content = b64encode(encoded_log).decode()

        message.attachment = Attachment(
            FileContent(content), FileName(f'{path.name}.gz'), FileType('x-gzip'), Disposition('attachment')
        )

    try:
        client = SendGridAPIClient(api_key)

        return client.send(message)
    except Exception as e:
        log.error(f'Error sending email with SendGrid: {e}')

        return e
    def SendGrid(self,Tcases,TDeaths,Recovered):
         # # Add body to email
        body = """ <html>
                   <body>
                        <u><strong>COVID19<strong></u><br><br>
                            <b>Total Cases: {Tcases}  </b><br>
                            <b style="color:red">Total Deaths : {TDeaths}  </b><br>
                            <b>Recovered : {Recovered}  </b><br>
                            <a href="https://www.worldometers.info/coronavirus/" >Check the link: click here </a>
                    </body>
                    </html>
                """.format(Tcases=Tcases,TDeaths=TDeaths,Recovered=Recovered)


        message = Mail(
        from_email= (self.sender,'John Doe'),
        to_emails= self.receiver,
        subject='Corona Virus Update [ Covid19] [Local]',
        html_content=body,
        is_multiple= True)

        for filename in self.attachments:
            with open(filename, 'rb') as f:
                data = f.read()
                f.close()
                encoded_file = base64.b64encode(data).decode()

                attachedFile = Attachment(
                    FileContent(encoded_file),
                    FileName(filename),
                    FileType(mimetypes.guess_type(filename)[0]),
                    Disposition('attachment')
                )
                print("filename =%s " % filename)
                print(mimetypes.guess_type(filename))
                message.attachment = attachedFile

        try:
            sg = SendGridAPIClient(self.api)
            response = sg.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e)
Beispiel #15
0
def send_notification_by_sendgrid(
    s_subject="",
    s_message="",
):
    """
    Send notification using SendGrid services (free tier - 100 requests).
    :param s_subject:
    :param s_message:
    :return:
    """

    message = Mail(from_email='*****@*****.**',
                   to_emails='<USER>@gmail.com',
                   subject=s_subject,
                   plain_text_content=s_message)

    try:
        file_path = './out_classif.log'
        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('out_classif.txt')
        attachment.disposition = Disposition('attachment')
        message.attachment = attachment
    except Exception as e:
        print(
            "Warning: file - out_classif.log - was not located to attach to the notification message."
        )

    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(
            "Warning: you don't seem to have (or not correctly) configured your "
            "Sendgrid API Key (for details check the readme.md at project root dir), "
            "you will not receive a notification by email.")
Beispiel #16
0
def send_email(string):
    input_string = string.split("&")
    hashset = {}

    for substring in input_string:
        key, val = substring.split("=")
        hashset[key] = val.replace("'", "")
    sys.stdout.write(str(hashset))
    message = Mail()

    for key in hashset:
        if key == "to_emails":
            personalization = Personalization()
            for emails in hashset[key].split(";"):
                personalization.add_to(Email(emails))
            message.add_personalization(personalization)
        elif key == "content":
            message.add_content(Content(hashset['content_type'], hashset[key]))
        elif key == "cc_email":
            for emails in hashset[key].split(";"):
                message.add_cc(Cc(emails))
        elif key == "bcc_email":
            for emails in hashset[key].split(";"):
                message.add_bcc(Bcc(emails))
        elif "attachment" in key and "_type" not in key:
            attached_file = Attachment()
            with open(hashset[key], 'rb') as f:
                data = f.read()
                f.close()
            encoded_file = base64.b64encode(data).decode()
            attached_file.file_content = FileContent(encoded_file)
            attached_file.file_name = FileName(
                hashset[key][hashset[key].rfind("/") + 1:])
            attached_file.file_type = FileType(hashset[key + "_type"])
            attached_file.disposition = Disposition('attachment')
            message.add_attachment(attached_file)
        else:
            setattr(message, key, hashset[key])

    #Use own API Key
    sg = SendGridAPIClient("")
    response = sg.send(message)
    sys.stdout.write("REQUEST BODY : " + str(message.get()))
    print(response.status_code, response.body, response.headers)
Beispiel #17
0
def send_email(subject,
               sender,
               recipients,
               text_body,
               html_body,
               file_path=None):
    # construct message
    message = Mail(from_email=sender,
                   to_emails=recipients,
                   subject=subject,
                   html_content=Content('text/html', html_body))
    txt_content = Content('text/txt', text_body)
    message.add_content(txt_content)

    # if there is an attachment add it
    if file_path is not None:
        try:
            with open(file_path, 'rb') as f:
                data = f.read()
                f.close()

            encoded = base64.b64encode(data).decode()
            # build attachment
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_type = FileType('text/plain')
            attachment.file_name = FileName('report.txt')
            attachment.disposition = Disposition('attachment')
            attachment.content_id = ContentId('txt file')
            # add attachment to message
            message.attachment = attachment
        except IOError as e:
            print(e)
            return False

    try:
        sg = SendGridAPIClient(current_app.config['SENDGRID_API_KEY'])
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
        return True
    except Exception as e:
        return False
Beispiel #18
0
def sendMail(totalfilecount, totalerrorcount):

    # log mail send to separate lof file

    logging.basicConfig(
        filename='/var/www/crra.andornot.com/logs/sendmail.log',
        format='%(asctime)s: %(levelname)s: %(message)s',
        filemode='w',
        level=logging.DEBUG)

    #to_emails = [('*****@*****.**', 'Jonathan Jacobsen')]
    to_emails = [('*****@*****.**', 'Jonathan Jacobsen'),
                 ('*****@*****.**', 'Steve Lapommeray')]

    message = Mail(
        from_email='*****@*****.**',
        to_emails=to_emails,
        subject='CRRA VuFind Data Import Log',
        html_content=
        '<p>Attached is the most recent data import log for CRRA VuFind.</p><p>Total files processed: '
        + str(totalfilecount) + "</p><p>Errors: " + str(totalerrorcount) +
        " or more (see attached log.)</p>")
    file_path = '/var/www/crra.andornot.com/logs/import-data.log'
    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/text')
    attachment.file_name = FileName('import-data.log.txt')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Log ID')
    message.attachment = attachment
    try:
        sg = SendGridAPIClient(os.getenv('SENDGRID_API_KEY'))
        response = sg.send(message)
        logging.info("Email sent")
        logging.info(response.status_code)
        logging.info(response.body)
        logging.info(response.headers)
    except Exception as e:
        logging.error(e)
Beispiel #19
0
    def email_log_custom(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_

        content_ = 'Dear Admin Team,\n\n' + \
            body[0] + ' \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 #20
0
def send_mail_with_attachment(recipients_array, email_body, pdf):
    encoded_file = base64.b64encode(pdf).decode()

    attachedFile = Attachment(FileContent(encoded_file),
                              FileName('prueba.pdf'),
                              FileType('application/pdf'),
                              Disposition('attachment'))

    message = Mail(from_email='*****@*****.**',
                   to_emails=recipients_array,
                   subject='Resumen Semanal',
                   html_content=email_body)

    message.attachment = attachedFile

    sg = SendGridAPIClient(api_key=os.getenv("SENDGRID_API_KEY"))

    response = sg.send(message)

    print(response.status_code)
Beispiel #21
0
def send_mail(sender, recipient, subject, content, image_attachment=None):
    '''
    return true if success, false if failed
    '''
    message = Mail(from_email=sender,
                   to_emails=recipient,
                   subject=subject,
                   html_content=content)
    if image_attachment:
        attachment = Attachment()
        # image_attachment is in base64
        attachment.file_content = FileContent(image_attachment)
        attachment.file_type = FileType('image/jpeg')
        attachment.file_name = FileName('captured.jpg')
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId('defaultcid')
        message.attachment = attachment
    sg = SendGridAPIClient(SENDGRID_API_KEY)
    response = sg.send(message)
    return response.status_code == 202
Beispiel #22
0
def _send_mail(send_to, subject, body, attachments=None):
    logging.info(f'Will send email with title: {subject} to {send_to}')
    message = Mail(from_email='*****@*****.**',
                   to_emails=f'{send_to}',
                   subject=subject,
                   html_content=body)
    for attachment in attachments or []:
        with open(attachment, "rb") as f:
            data = f.read()
            f.close()
            encoded_file = base64.b64encode(data).decode()
            attached_file = Attachment(FileContent(encoded_file),
                                       FileName(basename(attachment)), None,
                                       Disposition('attachment'))
        message.add_attachment(attached_file)
    sg = SendGridAPIClient(
        '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'
    )
    response = sg.send(message)
    logging.warning(f'Result: {response.status_code}')
Beispiel #23
0
def send_users_control_email(request):
    users = get_users(request)
    stream = create_users_control_xlsx(users)

    to_email = ['*****@*****.**','*****@*****.**', '*****@*****.**']
    subject = "Auditech user control - approve"
    content = Content("text/html charset=UTF-8",
                      "Attached the Users review control")
    encoded_file = base64.b64encode(stream).decode()
    
    attachment = Attachment(
        FileContent(encoded_file),
        FileName('ActiveDirectory-Control-report.xlsx'),
        FileType('application/xlsx'),
        Disposition('attachment'),
    )

    res = sendgird_send_email(to_email, subject, content, attachment)

    return res
Beispiel #24
0
def send_report_out(content: FileContent) -> None:
    '''Processes the email content and sends it to recipients thru SendGrid'''
    try:
        # format env variable like: '[email protected],[email protected]'
        email_list = os.environ.get('THEMIS_EMAIL_RECIPIENTS')
        to_emails = []
        for email in email_list.split(','):
            to_emails.append(email)
    except Exception as e:
        logger.error('Missing THEMIS_EMAIL_RECIPIENTS Variables {}'.format(e))

    message = Mail(from_email='*****@*****.**',
                   to_emails=email_list,
                   subject='LOOKER Instance Themis report for {}'.format(
                       date.today().strftime("%d-%m-%Y")),
                   html_content=content)

    file_path = './modules/rendering/final_attachment.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')
    filename = "themis_details_{}".format(date.today().strftime("%Y%m%d"))
    attachment.file_name = FileName(filename)
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Themis Report')
    message.attachment = attachment

    try:
        sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sendgrid_client.send(message)
        # https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html
        if response.status_code not in (200, 201, 202):
            print(response.status_code)
            print(response.body)
            print(response.headers)
    except Exception as e:
        logger.error('Error sending the SendGrid email: {}'.format(e))
def create_attachment_csv(filename:str, headers: list, data: list):
    csv_buffer = io.StringIO()

    writer = csv.writer(csv_buffer, delimiter=",", lineterminator="\n")

    writer.writerow(headers)
    for row in data:
        writer.writerow(row)

    # Convert CSV data to base64 string required by SendGrid
    content_str = csv_buffer.getvalue()
    content_bytes = bytes(content_str, encoding='utf-8')
    content_64 = base64.b64encode(content_bytes).decode()

    att = Attachment()
    att.file_content = FileContent(content_64)
    att.file_type = FileType('text/csv')
    att.file_name = FileName(filename)
    att.disposition = Disposition('attachment')

    return att
Beispiel #26
0
def send_email(subject,
               content,
               email=default_email,
               file=None,
               dev_recipients=False,
               from_email='*****@*****.**'):
    if email and type(email) == str:
        email = [email]

    if dev_recipients:
        developer_emails = ['*****@*****.**']
        if email:
            email = list(email) + developer_emails
        else:
            email = developer_emails

    email = list(set(email))
    message = Mail(from_email=from_email,
                   to_emails=email,
                   subject=subject,
                   html_content=content)
    if file:
        if type(file) == dict:
            file = [file]
        for f in file:
            encoded = base64.b64encode(f['data']).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_type = FileType(f['type'])
            attachment.file_name = FileName(f['name'])
            attachment.disposition = Disposition('attachment')
            message.attachment = attachment
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sg.send(message)
    except Exception as e:
        print(str(e))
        print(str(e.body))
        print('Subject  ', subject)
        print('CONTENT  ', content)
Beispiel #27
0
    def send_zip_to_user(self, file_name: str, data: bytes,
                         to_email: str) -> bool:

        # create message
        message = Mail(self.from_email,
                       to_email,
                       send_zip_to_user_subject_he if self.language == "he"
                       else send_zip_to_user_subject_en,
                       html_content=send_zip_to_user_body_he
                       if self.language == "he" else send_zip_to_user_body_en)

        # 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 #28
0
    def add_picturs(self, message: Mail):
        """
        Adding the pictures to the email.
        """
        path = join(os.getcwd(), 'static', 'cypress', 'screenshots', '*',
                    '*.png')
        files = glob(path)

        for file in files:
            with open(file, 'rb') as f:
                data = f.read()
                f.close()
            filename = file.split('/', )[-1]
            encoded = base64.b64encode(data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_type = FileType('image/png')
            attachment.file_name = FileName(filename)
            attachment.disposition = Disposition('attachment')
            attachment.content_id = ContentId('Example Content ID')

            message.add_attachment(attachment)
Beispiel #29
0
def digicam_sender(file, toemail):
    msg = Mail(
        from_email="*****@*****.**",
        to_emails=toemail,
        subject="Here is your photo!",
        content="The photo is in attachments! Enjoy!",
    )
    handle = open(file)
    datatosend = handle.read()
    encoded_file = binascii.b2a_base64(datatosend, newline=True).decode()
    msg.attachment = Attachment(
        FileContent(encoded_file),
        FileName("image.jpg"),
        FileType("image/jpeg"),
        Disposition("attachment"),
    )
    response = SendGridAPIClient(config.sendgrid_key).send(msg)
    return (
        response.status_code,
        response.body,
        response.headers,
    )
Beispiel #30
0
def send_email(to_emails,
               from_email,
               subject,
               html_content=None,
               content=None,
               attachments=[],
               bcc=None):

    message = Mail(from_email=from_email,
                   to_emails=to_emails,
                   subject=subject,
                   html_content=html_content,
                   plain_text_content=content)

    if bcc is not None:
        message.bcc = Bcc(bcc)

    for data, filename, filetype in attachments:
        encoded = base64.b64encode(data).decode()
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType(filetype)
        attachment.file_name = FileName(filename)
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId('Example Content ID')
        message.add_attachment(attachment)

    try:
        apikey = os.environ.get('SENDGRID_API_KEY')
        sg = SendGridAPIClient(apikey)
        response = sg.send(message)

        if response.status_code == 202:
            return True, None
        else:
            return False, "Failed: status code is {}".format(
                response.status_code)
    except Exception as e:
        return False, "Failed: {}".format(e)