Exemplo n.º 1
0
def send_email(sender, recipient, subject, content, cc=()):
    """Send an email via SendGrid with the provided arguments.

    Args:
        sender (str): email address of the sender.
        recipient (str): email address of the recipient.
        subject (str): email's subject.
        content (str): email's body.
        cc (list): list of email addresses to put in cc.

    Return:
        None
    """
    api_key = current_app.config.get('SENDGRID_API_KEY')
    if not api_key:
        raise SendGridMissingAPIToken('Cannot authenticate to SendGrid. SENDGRID_API_KEY key not found.')

    message = Mail(
        from_email=sender,
        to_emails=recipient,
        subject=subject,
        html_content=content
    )
    for cc_emai_address in cc:
        message.add_cc(cc_emai_address)
    try:
        sg = SendGridAPIClient(api_key)
        response = sg.send(message)
        LOGGER.info('Mail sent successfully', response=response)
    except Exception:
        LOGGER.exception('An error occurred while sending a mail')
def send_email(from_address: str, to_addresses: list, subject: str, body_html: str,
                     cc_addresses: list=None, bcc_addresses: list=None, attachment_list: list=None):
    api_key = config.sendgrid['api_token']

    sg = SendGridAPIClient(api_key=api_key)

    email = Mail(from_email=from_address,
                 to_emails=to_addresses,
                 subject=subject,
                 html_content=body_html)

    for e in cc_addresses:
        email.add_cc(e)

    for e in bcc_addresses:
        email.add_bcc(e)

    for att_tuple in attachment_list:
        filename = att_tuple[0]
        column_names = att_tuple[1]
        data = att_tuple[2]

        att = create_attachment_csv(filename, column_names, data)
        email.add_attachment(att)

    try:
        resp = sg.send(email)
    except Exception as ex:
        logging.exception(ex)
Exemplo n.º 3
0
    def __send_email_message(self, sender_name, sender_email, recipient_name,
                             recipient_email, message_subject, message_body):

        # Create the plain-text and HTML version
        text_string = sender_name + " would like to connect with you on KinConnections, subject: " + \
            message_subject + " and message: " + message_body
        html_string = self.__write_html_message(sender_name, sender_email,
                                                message_subject, message_body)

        # construct mail object
        message = Mail(from_email=("*****@*****.**",
                                   "Kin Connections (Global Encounters)"),
                       to_emails=(recipient_email, recipient_name),
                       subject="New Connection from " + sender_name,
                       plain_text_content=text_string,
                       html_content=str(html_string))
        message.add_cc(("*****@*****.**", "Kin Connections"))
        message.reply_to = (sender_email, sender_name)

        # send mail
        try:
            sendgrid_client = SendGridAPIClient(os.getenv('SENDGRID_API_KEY'))
            response = sendgrid_client.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e)
            print(e.body)
            return False

        return True
Exemplo n.º 4
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:
         sys.stderr.write("SendGrid status code: " +
                          str(response.status_code) + "\n")
         sys.stderr.write("SendGrid response headers: " +
                          repr(response.headers) + "\n")
         try:
             sys.stderr.write(repr(response.body) + "\n")
         except:
             pass
         raise Exception("Failed to send e-mail message to SendGrid")
     email_dispatched.send(message, app=current_app._get_current_object())
Exemplo n.º 5
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)
Exemplo n.º 6
0
    def handle_request(self, request, user):
        """
        :param SubmitSupportEnquiryRequest request:
        :param User user:
        :rtype: bool
        """
        body = SUPPORT_ENQUIRY_EMAIL_TEMPLATE % {
            'sub': user.sub,
            'email': request.email,
            'name': user.name,
            'company': user.company,
            'link': request.link,
            'phone': request.phone,
            'message': request.message,
        }

        from_email = Email(EMAIL_FROM_ADDRESS, EMAIL_FROM_NAME)
        to_email = To(EMAIL_TO_ADDRESS)
        subject = f'{EMAIL_PREFIX}{request.subject_type} - {request.subject}'
        content = Content('text/plain', body)
        mail = Mail(from_email, to_email, subject, content)
        mail.reply_to = ReplyTo(request.email, user.name)

        # Recipe (CC) to sender)
        if request.recipe:
            mail.add_cc(To(request.email))

        # File attachment
        if request.file_name and request.file_source:
            mail.attachment = self.create_attachment(request.file_name,
                                                     request.file_source)

        client = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)
        response = client.client.mail.send.post(request_body=mail.get())

        return response.status_code in (200, 201, 202)
Exemplo n.º 7
0
def send_sendgrid_email(subject, content, to_emails, to_ccs=None):
    html_content = Content("text/html", content)

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

    if to_ccs:
        ccs = []
        for cc_person in to_ccs:
            ccs.append(Cc(cc_person, cc_person))

        message.add_cc(ccs)

    try:
        response = sg.send(message)
        # print(response.status_code)
        # print(response.body)
        # print(response.headers)
    except Exception as e:
        print(e.message)

    return response
                                rate_class=RATE_CLASSES[i],
                                out_path=preprocessed_output_path)
        else:
            preprocess_ts(cfg=cfg,
                          save_raw_df=True,
                          save_prepr_df=True,
                          rate_class=RATE_CLASSES[i],
                          out_path=preprocessed_output_path)
    except:
        error_email_msg += 'Error encountered in preprocessing new raw data:\n' + traceback.format_exc(
        ) + '\n\n'

# Send email containing error information to prespecified recipients and cancel subsequent execution
if len(error_email_msg) > 0:
    error_email_msg = 'Preprocessing step of training pipeline failed. See the below error.\n\n' + error_email_msg
    print(error_email_msg)
    cfg_private = yaml.full_load(open("./config-private.yml",
                                      'r'))  # Load private config data
    message = Mail(from_email='*****@*****.**',
                   to_emails=cfg_private['EMAIL']['TO_EMAILS_ERROR'],
                   subject='Water forecasting training pipeline failed',
                   html_content=error_email_msg)
    for email_address in cfg_private['EMAIL']['CC_EMAILS_ERROR']:
        message.add_cc(email_address)
    try:
        sg = SendGridAPIClient(cfg_private['EMAIL']['SENDGRID_API_KEY'])
        response = sg.send(message)
    except Exception as e:
        print(e)
    raise Exception(error_email_msg)  # Cancel remainder of pipeline
Exemplo n.º 9
0
def SendEmails(HubPullRequest, EmailContents, SendMethod):
    if SendMethod == 'SMTP':
        #
        # Send emails to SMTP Server
        #
        try:
            SmtpServer = smtplib.SMTP(SMTP_ADDRESS, SMTP_PORT_NUMBER)
            SmtpServer.starttls()
            SmtpServer.ehlo()
            SmtpServer.login(SMTP_USER_NAME, SMTP_PASSWORD)
            Index = 0
            for Email in EmailContents:
                Index = Index + 1
                EmailMessage = email.message_from_string(Email)
                print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                      '----> SMTP Email Start <----')
                print(Email)
                print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                      '----> SMTP Email End <----')
                if 'From' in EmailMessage:
                    try:
                        FromAddress, FromName = ParseEmailAddress(
                            EmailMessage['From'])
                    except:
                        print('Parsed From: Bad address:',
                              EmailMessage['From'])
                        FromAddress = '*****@*****.**'
                        FromName = 'From %s via TianoCore Webhook' % (
                            HubPullRequest.user.login)
                else:
                    print('Parsed From: Missing address:')
                    FromAddress = '*****@*****.**'
                    FromName = 'From %s via TianoCore Webhook' % (
                        HubPullRequest.user.login)
                ToList = []
                if 'To' in EmailMessage:
                    ToList = ToList + EmailMessage['To'].split(',')
                if 'Cc' in EmailMessage:
                    ToList = ToList + EmailMessage['Cc'].split(',')
                try:
                    SmtpServer.sendmail(FromAddress, ToList, Email)
                    print('SMTP send mail success')
                except:
                    print('ERROR: SMTP send mail failed')
            SmtpServer.quit()
        except:
            print(
                'SendEmails: error: can not connect or login or send messages.'
            )
    elif SendMethod == 'SendGrid':
        #
        # Send emails to SendGrid
        #
        Index = 0
        for Email in EmailContents:
            Index = Index + 1
            EmailMessage = email.message_from_string(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> SendGrid Email Start <----')
            print(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> SendGrid Email End   <----')
            message = Mail()
            if 'From' in EmailMessage:
                try:
                    EmailAddress, EmailName = ParseEmailAddress(
                        EmailMessage['From'])
                    message.from_email = From(EmailAddress, EmailName)
                except:
                    print('Parsed From: Bad address:', EmailMessage['From'])
                    message.from_email = From(
                        '*****@*****.**',
                        'From %s via TianoCore Webhook' %
                        (HubPullRequest.user.login))
            else:
                print('Parsed From: Missing address:')
                message.from_email = From(
                    '*****@*****.**', 'From %s via TianoCore Webhook' %
                    (HubPullRequest.user.login))
            UniqueAddressList = []
            if 'To' in EmailMessage:
                for Address in EmailMessage['To'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        message.add_to(To(EmailAddress, EmailName))
                    except:
                        print('Parsed To: Bad address:', Address)
                        continue
            if 'Cc' in EmailMessage:
                for Address in EmailMessage['Cc'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        message.add_cc(Cc(EmailAddress, EmailName))
                    except:
                        print('Parsed Cc: Bad address:', Address)
                        continue
            message.subject = Subject(EmailMessage['Subject'])
            for Field in ['Message-Id', 'In-Reply-To']:
                if Field in EmailMessage:
                    message.header = Header(Field, EmailMessage[Field])
            message.content = Content(MimeType.text,
                                      EmailMessage.get_payload())
            try:
                sendgrid_client = SendGridAPIClient(SENDGRID_API_KEY)
                response = sendgrid_client.send(message)
                print('SendGridAPIClient send success')
                time.sleep(1)
            except Exception as e:
                print('ERROR: SendGridAPIClient failed')
    else:
        Index = 0
        for Email in EmailContents:
            Index = Index + 1
            EmailMessage = email.message_from_string(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> Draft Email Start <----')
            if 'From' in EmailMessage:
                try:
                    EmailAddress, EmailName = ParseEmailAddress(
                        EmailMessage['From'])
                    print('Parsed From:', EmailAddress, EmailName)
                except:
                    print('Parsed From: Bad address:', EmailMessage['From'])
            else:
                print('Parsed From: Missing address:')
            UniqueAddressList = []
            if 'To' in EmailMessage:
                for Address in EmailMessage['To'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        print('Parsed To:', EmailAddress, EmailName)
                    except:
                        print('Parsed To: Bad address:', Address)
                        continue
            if 'Cc' in EmailMessage:
                for Address in EmailMessage['Cc'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        print('Parsed Cc:', EmailAddress, EmailName)
                    except:
                        print('Parsed Cc: Bad address:', Address)
                        continue
            print('--------------------')
            print(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> Draft Email End   <----')