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)
Пример #2
0
def send_cancel_mail_sendgrid(agenda: Agenda):
    curdir = os.getcwd()

    with open(
            f'{curdir}{os.sep}apps{os.sep}agenda{os.sep}email_templates{os.sep}appointment-cancellation.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('{{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 : Cancelamento de consulta',
                       html_content=body)
        try:
            message.add_bcc(agenda.therapist.email)
            message.add_bcc(os.getenv("EMAIL_SENDER"))

            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)
Пример #3
0
def email(alpha, fecha):
    #import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail, Email
    from python_http_client.exceptions import HTTPError

    sg = SendGridAPIClient(EMAIL_API_KEY)  #(os.environ['EMAIL_API_KEY'])

    html_content = "<p>ALERT - Meteo Station not transmiting data!</p>" + "<p>This email is to Alert for Meteo Station = " + str(
        alpha) + "</p>" + "<p>last received date = " + str(fecha) + "</p>"

    message = Mail(to_emails=[
        "*****@*****.**", "*****@*****.**",
        "*****@*****.**", "*****@*****.**",
        "*****@*****.**"
    ],
                   from_email=Email('*****@*****.**',
                                    "MyKau Monitor_Report"),
                   subject="Meteo Station [AUTO ALERT] - MyKau",
                   html_content=html_content)
    message.add_bcc("*****@*****.**", "*****@*****.**",
                    "*****@*****.**")

    try:
        response = sg.send(message)
        return f"email.status_code={response.status_code}"
        #expected 202 Accepted

    except HTTPError as e:
        return e.message
Пример #4
0
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)
Пример #5
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())
Пример #6
0
class EmailService(object):
    def __init__(self):
        default_sender = '*****@*****.**'
        try:
            config = EmailConfiguration.get_solo()
            default_sender = config.sender
        except:
            pass

        self._client = SendGridAPIClient(settings.SENDGRID_KEY)
        self._sender = default_sender
        self._message = None

    def create_message(self, recipients, subject):
        self._message = Mail(from_email=self._sender,
                             to_emails=recipients,
                             subject=subject)

    def set_template(self, template):
        self._message.template_id = template

    def set_bcc(self, bcc_email):
        self._message.add_bcc(bcc_email)

    def set_data(self, data):
        self._message.dynamic_template_data = data

    def add_attachment(self, data, file_name, file_type):
        encoded_file = base64.b64encode(data).decode()

        attached_file = Attachment(FileContent(encoded_file),
                                   FileName(file_name), FileType(file_type),
                                   Disposition('attachment'))
        self._message.attachment = attached_file

    def send_email(self):
        try:
            self._client.send(self._message)
            return True
        except Exception as e:
            logger.info('Sendgrid > ERROR > Send email ')
            logger.info(e)
            logger.info(self._message.get())
        return False
Пример #7
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)