Esempio n. 1
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.sg_client = SendGridAPIClient(self.conn_info["API_KEY"])
Esempio n. 2
0
                            fixed_test_set=True)

    # Produce a water consumption forecast and save it
    forecast(FORECAST_DAYS, cfg=cfg, model=model, save=True)

    # Keep a copy of preprocessed data in persistent blob storage for this run and update the historical preprocessed dataset for this rate class
    shutil.copy(cfg['PATHS']['PREPROCESSED_DATA'], rc_preprocessed_dir)
    shutil.move(cfg['PATHS']['PREPROCESSED_DATA'], rc_destination_dir)

    # Copy all outputs to latest outputs directory
    copy_tree(DESTINATION_DIR, LATEST_OUTPUTS_DIR)

    # Send an email to relevant parties indicating completion of training
    email_content = 'Hello,\n\nThe water demand forecasting model has successfully trained.'
    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_COMPLETION'],
        subject='Water demand forecasting training pipeline complete',
        html_content=email_content)
    for email_address in cfg_private['EMAIL']['CC_EMAILS_COMPLETION']:
        message.add_cc(email_address)
    try:
        sg = SendGridAPIClient(cfg_private['EMAIL']['SENDGRID_API_KEY'])
        response = sg.send(message)
    except Exception as e:
        print(
            'Could not send email indicating training completion. Encountered the following error:\n\n',
            e)
Esempio n. 3
0
 def __init__(self, config: AbstractConfiguration):
     super().__init__()
     self.config = config
     self.sg_client = SendGridAPIClient(api_key=self.config.sendgrid_api_key)
Esempio n. 4
0
 def __init__(self, *args, **kwargs):
     self.sg = SendGridAPIClient(settings.SENDGRID_APIKEY)
     super().__init__(*args, **kwargs)
Esempio n. 5
0
load_dotenv()

SENDGRID_API_KEY = os.environ.get(
    "SENDGRID_API_KEY", "OOPS, please set env var called 'SENDGRID_API_KEY'")
SENDGRID_TEMPLATE_ID = os.environ.get(
    "SENDGRID_TEMPLATE_ID",
    "OOPS, please set env var called 'SENDGRID_TEMPLATE_ID'")
MY_ADDRESS = os.environ.get(
    "MY_EMAIL_ADDRESS", "OOPS, please set env var called 'MY_EMAIL_ADDRESS'")

#print("API KEY:", SENDGRID_API_KEY)
#print("TEMPLATE ID:", SENDGRID_TEMPLATE_ID)
#print("EMAIL ADDRESS:", MY_ADDRESS)

client = SendGridAPIClient(
    SENDGRID_API_KEY)  #> <class 'sendgrid.sendgrid.SendGridAPIClient>
print("CLIENT:", type(client))

subject = "Your Receipt from the GREEN FOODS GROCERY"

template_data = {
    "total_price_usd": grand_total,
    "human_friendly_timestamp": date_time,
    "products": [product_name]
}  # or construct this dictionary dynamically based on the results of some other process :-D

client = SendGridAPIClient(SENDGRID_API_KEY)
print("CLIENT:", type(client))

message = Mail(from_email=MY_ADDRESS, to_emails=MY_ADDRESS, subject=subject)
Esempio n. 6
0
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from secrets import APIKEY
message = Mail(
    from_email='*****@*****.**',
    to_emails='*****@*****.**',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
try:
    sg = SendGridAPIClient(APIKEY)
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)

print("Hello rwils83")
Esempio n. 7
0
    def post(self, request):
        serializer = self.serializer_class(data=request.data)

        email = request.data.get('email')
        user = User.objects.filter(email=email).first()
        if user:
            print(user.status)
            if user.status == 'Blocked' or user.status == 'Deleted':
                message = "Your Account is {}".format(user.status)
                response = {
                    'message': message,
                    'error': 'Request not allowed.',
                    'status': HTTP_400_BAD_REQUEST
                }
                return Response(response, status=HTTP_400_BAD_REQUEST)

            uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
            token = PasswordResetTokenGenerator().make_token(user)

            current_site = CustomConstants.EMAIL_DOMAIN + "/forget-password-reset"
            mail_subject = '[noreply] Reset your Password'
            msg = 'You will be redirected to the password reset page.'

            message = render_to_string(
                'password_reset_link.html', {
                    'user': user,
                    'domain': current_site,
                    'msg': msg,
                    'uid': uidb64,
                    'token': token,
                })

            to_email = [user.email]
            from_email = settings.SENDER_EMAIL

            email = Mail(
                from_email=from_email,
                to_emails=to_email,
                subject=mail_subject,
                html_content=message,
            )
            try:
                sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
                response = sg.send(email)
            except Exception as e:
                response = {
                    'message': 'User Registration failed',
                    'error': e,
                    'status': HTTP_400_BAD_REQUEST
                }
                return Response(response, status=HTTP_400_BAD_REQUEST)

            response = {
                "message": "Password reset link sent on your mail.",
                "status": HTTP_200_OK
            }
            return Response(response, status=HTTP_200_OK)

        else:
            response = {
                "message": "Enter Correct email",
                "status": HTTP_400_BAD_REQUEST
            }

        return Response(response, status=HTTP_400_BAD_REQUEST)
def changeemail():
    Current_Password = request.form['C_Password']
    #compare if Current_Password hash exists for the current_user and only if True, then allow for update
    with sqlite3.connect('users.db') as con:
        cur = con.cursor()
        cur.execute('SELECT userPassword FROM EnrolledUsers where id=?',
                    (current_user.id, ))
        hashPass = cur.fetchall()[0][0]
        if check_password_hash(hashPass, Current_Password):
            #allow change
            New_Email = request.form['N_Email']
            Prev_Email = current_user.email
            if New_Email == current_user.email:
                #user seems to try to perform a redundant task, so need to invalidate the operation
                flash(
                    'New email should not match with current email. Please Try Again.',
                    'danger')
                return redirect(url_for('settings'))

            cur.execute('UPDATE EnrolledUsers SET userEmail =? where id=? ', (
                New_Email,
                current_user.id,
            ))
            con.commit()
            #we can send mails to user on both previous and current user email informing change of email for securtiy reasons

            #mail alert to previous email ID
            message = Mail(
                from_email=str(app.config.get("FROM_EMAIL")),
                to_emails=Prev_Email,
                subject='Email Change Notification Alert!',
                html_content='Dear ' + current_user.name.split()[0] +
                ". We have recieved a request to change your primary Email that is required for login and communication purposes. This mail is just an alert for the same. You have chosen to set your new email address as : "
                + New_Email +
                ". If you have not initiated this change, you may consider the possibility that your account has been compromised and we would advise you to change your password and secure your account!"
            )
            sg = SendGridAPIClient(str(app.config.get("SENDGRID_API_KEY")))
            response = sg.send(message)

            #mail alert to new email ID
            message = Mail(
                from_email=str(app.config.get("FROM_EMAIL")),
                to_emails=New_Email,
                subject='Email Change Notification Alert!',
                html_content='Dear ' + current_user.name.split()[0] +
                ". We have recieved a request to change your primary Email that is required for login and communication purposes. This mail is just an alert for the same. You have chosen to set your new email address as : "
                + New_Email +
                ". If you have not initiated this change, you may consider the possibility that your account has been compromised and we would advise you to change your password and secure your account!"
            )
            sg = SendGridAPIClient(str(app.config.get("SENDGRID_API_KEY")))
            response = sg.send(message)

            flash(
                'Email changed successfully. Please Login again to continue.',
                'success')
            logout_user()
            return redirect(url_for('login'))
        else:
            #user seems to have entered a wrong password : so flash error message and reload current PAGE
            flash('Please re-enter correct current password.', 'danger')
            return redirect(url_for('changeEmail'))
Esempio n. 9
0
def main(msg: func.ServiceBusMessage):

    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    msg, subject = None, None

    # TODO: Get connection to database
    conn = psycopg2.connect(host=os.environ["POSTGRES_URL"],
                            database=os.environ["POSTGRES_DB"],
                            user=os.environ["POSTGRES_USER"],
                            password=os.environ["POSTGRES_PW"])

    try:
        # TODO: Get notification message and subject from database using the notification_id
        cursor = conn.cursor()
        cmd = f"SELECT message, subject FROM notification WHERE id={notification_id}"
        cursor.execute(cmd)
        msgs = cursor.fetchall()

        for row in msgs:
            msg = row[0]
            subject = row[1]

        if not msg or not subject:
            logging.error("No msg or subject")
            raise Exception("No msg or subject")

        # TODO: Get attendees email and name
        # TODO: Loop through each attendee and send an email with a personalized subject
        cmd = f"SELECT first_name, email FROM attendee"
        cursor.execute(cmd)
        attendees = cursor.fetchall()

        attendee_count = 0

        for row in attendees:
            fname = row[0]
            email = row[1]

            message = Mail(from_email=os.environ['ADMIN_EMAIL_ADDRESS'],
                           to_emails=email,
                           subject=fname + " " + subject,
                           plain_text_content=msg)

            sg = SendGridAPIClient(os.environ['SENDGRID_API_KEY'])
            sg.send(message)

            attendee_count += 1

        # TODO: Update the notification table by setting the completed date
        # and updating the status with the total number of attendees notified
        status_msg = f"Notified {str(attendee_count)} attendees"
        curr_date = datetime.now()

        cmd = """UPDATE notification
                    SET status = %s
                    WHERE id = %s"""
        cursor.execute(cmd, (status_msg, notification_id))

        cmd = """UPDATE notification
                    SET completed_date = %s
                    WHERE id = %s"""
        cursor.execute(cmd, (curr_date, notification_id))
        conn.commit()

    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
    finally:
        # TODO: Close connection
        conn.close()
Esempio n. 10
0
 def __init__(self):
     KEY = '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'
     self.sg = SendGridAPIClient(KEY)
def addContact():
    Name = request.form['Name']
    Email = request.form['Email']
    Phone = request.form['Phone']
    Occasion = request.form['Occasion']
    Interval = request.form['Interval']
    AlertText = request.form['AlertText']
    ContactDesc = request.form['ContactDesc']
    userID = current_user.id
    #let's set our basic validations

    #if email or phone already exist, then invalid entry
    with sqlite3.connect('users.db') as con:
        cur = con.cursor()
        try:
            cur.execute('''SELECT userID FROM UserContacts where conEmail=?''',
                        (Email, ))
            rows1 = cur.fetchall()
            rows1_id = rows1[0][0]
        except:
            rows1_id = current_user.id
            rows1 = []
        try:
            cur.execute('''SELECT userID FROM UserContacts where conPhone=?''',
                        (Phone, ))
            rows2 = cur.fetchall()
            rows2_id = rows2[0][0]
        except:
            rows2_id = current_user.id
            rows2 = []

        if rows1 != [] or rows2 != []:
            #this means email or phone already exists
            print("This condition is active")
            print
            #at this point send a mail to the current user congratulating them for discovering a design flaw
            if int(rows1_id) != int(current_user.id) or int(rows2_id) != int(
                    current_user.id):
                print("Sending mail")
                print(current_user.id, "current_user_id")
                print(rows1, "rows1")
                print(rows2, "rows2")
                message = Mail(
                    from_email=str(app.config.get("FROM_EMAIL")),
                    to_emails=current_user.email,
                    subject='You are one step closer to finding the flag',
                    html_content='Hey ' + current_user.name +
                    ". You've stumbled upon a major vulnerability in this system's design. Here's your cookie : IEEECTF{Could_This_Be_The_Flag_Though}. Also, take a hint : When I'm at home, it takes me forever to find the grays with the darks of life, but when I do; I get the keys to the chest with all the treasures that I seek."
                )
                sg = SendGridAPIClient(str(app.config.get("SENDGRID_API_KEY")))
                response = sg.send(message)
                flash(
                    "Contact already exists! Please add a different contact. Check your mail though.",
                    'danger')
                return redirect(url_for('askContactDetails'))
            else:
                print("Still not discovered the flaw")
                flash(
                    'Contact already exists! Please add a different contact.',
                    'danger')
                return redirect(url_for('askContactDetails'))
    try:
        s = int(Interval)
        if s < 1 or s > 365:
            flash(
                'Please keep your interval between 1 day and 365 days and try again!',
                'danger')
            return redirect(url_for('askContactDetails'))
    except:
        flash(
            'You seem to have entered an invalid interval of days. Please try again!',
            'danger')
        return redirect(url_for('askContactDetails'))

    #now to add the above fields in the UserContacts db
    with sqlite3.connect('users.db') as con:
        cur = con.cursor()
        cur.execute(
            '''INSERT INTO UserContacts(userID, conEmail, conName, conOccasion, conInterval,conPhone, conDescription, conAlertText) VALUES(?,?,?,?,?,?,?,?)''',
            (userID, Email, Name, Occasion, Interval, Phone, ContactDesc,
             AlertText))
        con.commit()
    flash('We have added your contact!', 'success')
    return redirect(url_for('askContactDetails'))
Esempio n. 12
0
def sender_alert_new_cmd(order, user):
    """
    Send the email to the owner for the new order.
    """

    date_cmd = str(order.created).split(' ')[0].split('-')
    data = {
        "cmd": {
            "ref": order.reference,
            "nameclient": f"{user.last_name.upper()} {user.first_name}",
            "email": user.email,
            "adress": user.adress,
            "postalcode": str(user.postal_code),
            "city": user.city.upper(),
            "phonenumber": f"0{str(user.phone_number)}",
            "anotheradress": {},
            "note": order.note,
            "date": f"{date_cmd[2]}/{date_cmd[1]}/{date_cmd[0]}",
            "subtotalprice": str(order.total_price - order.shipping_costs),
            "totalprice": str(order.total_price),
            "shippingcosts": str(order.shipping_costs),
            "products": []
        }
    }

    if order.another_delivery_adress:
        data['cmd']['anotheradress'] = {
            "ifyes": True,
            "nameclient": f"{order.last_name.upper()} {order.first_name}",
            "adress": order.adress,
            "postalcode": str(order.postal_code),
            "city": order.city.upper(),
            "phonenumber": f"0{str(order.phone_number)}",
        }

    else:
        data['cmd']['anotheradress'] = {
            "ifyes": False,
            "nameclient": "none",
            "adress": "none",
            "postalcode": "none",
            "city": "none",
            "phonenumber": "none",
        }

    for product in OrderProductQuantity.objects.filter(id_order=order):
        data['cmd']['products'].append({
            "name": product.id_product.name,
            "priceunit": str(product.price),
            "totalprice": str(product.get_price()),
            "quantity": str(product.quantity)
        })

    mail = Mail()
    mail.from_email = Email(
        os.environ.get('FROM_EMAIL'),
        os.environ.get('FROM_NAME_EMAIL')
    )
    mail.template_id = os.environ.get('ID_TEMPLATE_NEW_CMD')
    mail.subject = "NOUVELLE COMMANDE WEB"
    p = Personalization()
    p.add_to(Email(
        os.environ.get('OWNER_EMAIL'),
        os.environ.get('OWNER_NAME_EMAIL')
    ))
    p.dynamic_template_data = data
    mail.add_personalization(p)
    sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
    response = sg.client.mail.send.post(request_body=mail.get())

    return response
Esempio n. 13
0
            increase_ten.append(stock)

        if history[-1] / history[-2] < 0.9:
            decrease_ten.append(stock)

message = Mail(
    from_email='*****@*****.**',
    to_emails='*****@*****.**',
    subject='Stock prices updates:',
    html_content="""
    <strong>Stock updates for %s</strong>
    <p>Stocks that crossed running average: %s</p>
    <p>Stocks that dropped below bottom envelope: %s</p>
    <p>Stocks that increased 10 percent or more: %s</p>
    <p>Stocks that decreased 10 percent or more: %s</p>
    """ % (datetime.today(), running_avg_crossed, under_avg_crossed, increase_ten, decrease_ten))
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.message)

#print(name_to_history)
#print(name_to_price)
#print(len(name_to_price))

# My API code
# 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
Esempio n. 14
0
 def __init__(self, api_key):
     self.client = SendGridAPIClient(api_key)
Esempio n. 15
0
 def __init__(self, config):
     self.config = config
     self.client = SendGridAPIClient(apikey=self.config['SENDGRID_API_KEY'])
Esempio n. 16
0
        #     }
        # ],
        'subject': 'Sending with Twilio SendGrid is Fun'
    }],
    'from': {
        'email': '*****@*****.**'
    },
    'content': [{
        'type': 'text/plain',
        'value': 'and easy to do anywhere, even with Python'
    }]
}
try:
    # print(os.environ.get('SENDGRID_API_KEY'))
    sg = SendGridAPIClient(
        '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'
    )
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
    # result = {"success": True}

    # response_headers = {
    #     "Access-Control-Allow-Origin": "*",
    #     "Access-Control-Allow-Methods": "PUT, GET, POST, DELETE, OPTIONS",
    #     "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept,X-Requested-With, X-CSRF-Token,Authorization,"
    # }

    # return {'statusCode': 200, 'body': json.dumps(result), "headers": response_headers, "isBase64Encoded": False}
except Exception as e:
Esempio n. 17
0
import os
import sys
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

receiver = sys.argv[1]
msg = sys.argv[2]

msg = msg + " check the portal at http://placemet.bitmesra.ac.in. All the best!"
message = Mail(from_email='<registered-email-id>',
               to_emails=receiver,
               subject='Urgent T&P updates',
               html_content=msg)
try:
    sg = SendGridAPIClient('API Key')
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
Esempio n. 18
0
 def __init__(self, sender, apikey):
     self.sender = sender
     self.sg = SendGridAPIClient(apikey)
     pass
Esempio n. 19
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from sendgrid import SendGridAPIClient
from flaskBlog.config import Config


db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = "users.login"
login_manager.login_message_category = "info"

SGmail = SendGridAPIClient(Config.MAIL_PASSWORD)

def splitChars(string):
    return [st for st in string]


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    app.jinja_env.filters['splitChars'] = splitChars

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)

    from flaskBlog.users.routes import users
 def __init__(self):
    """Initalize the connector class with config and client instance"""
    self.config = conector_config.get('sendgrid', {})
    self.sg = SendGridAPIClient(self.config['API_KEY'])
    logger.info("Initalize EPSendGridConnector Connector")
Esempio n. 21
0
def register_user(request):
    if request.method == 'POST':
        email = request.data.get('email').lower()
        username = request.data.get('username')
        if username == email:
            response = {
                'message': 'SignUp failed !!',
                'error': "Username" + str("can't") + " be the same as email",
                'status': HTTP_400_BAD_REQUEST
            }

        check_user = User.objects.filter(email=email).first()
        check_username = User.objects.filter(username__iexact=username).first()

        if check_user and not check_user.is_active:
            check_user.delete()
            check_username = ''

        filtered_user_by_email = User.objects.filter(email=email)
        if filtered_user_by_email.exists(
        ) and filtered_user_by_email[0].auth_provider != 'email':
            response = {
                "message":
                "Login failed",
                "error":
                'Please continue your login using ' +
                filtered_user_by_email[0].auth_provider,
                'status':
                HTTP_401_UNAUTHORIZED
            }
            return Response(response, status=HTTP_401_UNAUTHORIZED)

        if check_username:
            response = {
                'message': 'SignUp failed !!',
                'error': 'Username is already taken',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        if len(username.strip().split(" ")) > 1:
            response = {
                'message': 'SignUp failed !!',
                'error': 'Username cannot contain spaces.',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)
        print(request.data)
        serializer = RegistrationSerializer(data=request.data)
        if serializer.is_valid():
            account = serializer.save()

            full_name = request.data.get('full_name')
            country = request.data.get('country').lower()
            city = request.data.get('city').lower()
            gender = request.data.get('gender')

            Profile.objects.create(user=account,
                                   country=country,
                                   city=city,
                                   full_name=full_name,
                                   gender=gender)

            current_site = CustomConstants.EMAIL_DOMAIN + "/account-activation"
            mail_subject = '[noreply] Activate your Account'
            msg = 'Thanks for Signing up with Bditto.'

            message = render_to_string(
                'acc_email_active.html', {
                    'user': account,
                    'domain': current_site,
                    'msg': msg,
                    'uid': urlsafe_base64_encode(force_bytes(account.pk)),
                    'token': account_activation_token.make_token(account),
                })

            to_email = [account.email]
            from_email = settings.SENDER_EMAIL

            email = Mail(
                from_email=from_email,
                to_emails=to_email,
                subject=mail_subject,
                html_content=message,
            )
            try:
                sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
                response = sg.send(email)
            except Exception as e:
                response = {
                    'message': 'User Registration failed',
                    'error': "Mail not sent",
                    'status': HTTP_400_BAD_REQUEST
                }
                return Response(response, status=HTTP_400_BAD_REQUEST)

            response = {
                'message':
                'User registered successfully, Please verify your accoumt using the link sent via email',
                'body': [],
                'status': HTTP_200_OK
            }
            return Response(response, status=HTTP_200_OK)

        else:
            response = {
                'message': 'User Registration failed',
                'error': serializer.errors,
                'status': HTTP_401_UNAUTHORIZED
            }
        return Response(response, status=HTTP_401_UNAUTHORIZED)
Esempio n. 22
0
#%%
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

#%%

message = Mail(
    from_email='*****@*****.**',
    to_emails='*****@*****.**',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
try:
    sg = SendGridAPIClient("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")
    response = sg.send(message)
    print("SUCCESS")
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print("ERROR")
    print(e.message)


#%%
from src.app import Session
from src.models import Baby


db = Session()
Esempio n. 23
0
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='',
    to_emails='',
    subject='email attachment',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

file_path = 'IET.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('File_notice.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Example Content ID')
message.attachment = attachment
try:
    sendgrid_client = SendGridAPIClient('')
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
Esempio n. 24
0
def send_pdf_email_using_SendGrid(sender,
                                  receiver,
                                  mail_subject,
                                  mail_content,
                                  pdf_attachment,
                                  txt_attachment=None,
                                  cc_email=None):

    # Where it was uploaded Path.
    file_path = pdf_attachment

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

    # Encode contents of file as Base 64
    encoded = base64.b64encode(data).decode()
    """Build PDF attachment"""
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('application/pdf')
    attachment.file_name = FileName('your_quote.pdf')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Example Content ID')
    """ Add txt file """
    if txt_attachment:
        file_path = txt_attachment

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

        # Encode contents of file as Base 64
        encoded = base64.b64encode(data).decode()
        """Build txt attachment"""
        attachment2 = Attachment()
        attachment2.file_content = FileContent(encoded)
        attachment2.file_type = FileType('text/html')
        attachment2.file_name = FileName('quote.txt')
        attachment2.disposition = Disposition('attachment')
        attachment2.content_id = ContentId('Text Example Content ID')

    message = Mail(
        from_email=sender,
        #to_emails = receiver,			# Removed since it generates an extra email with SendGrid
        subject=mail_subject,
        html_content=mail_content)
    message.attachment = attachment

    if cc_email:
        cc = Email(cc_email)
        to = Email(receiver)
        p = Personalization()
        p.add_to(to)
        p.add_cc(cc)
        message.add_personalization(p)
    else:  # no cc
        to = Email(receiver)
        p = Personalization()
        p.add_to(to)
        message.add_personalization(p)
    if txt_attachment:
        message.add_attachment(attachment2)

    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(e.message)

    return
Esempio n. 25
0
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), 'sendgrid.env')
load_dotenv(dotenv_path)
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')

from sendgrid import SendGridAPIClient
sg = SendGridAPIClient(SENDGRID_API_KEY)

if __name__ == '__main__':
    data = {
        "address": "3-9-3",
        "address_2": "Meguro",
        "city": "Meguroeguro",
        "country": "Japan",
        "from": {
            "email": "*****@*****.**",
            "name": "s.maeda.kobe"
        },
        "nickname": "kobe address",
        "reply_to": {
            "email": "*****@*****.**",
            "name": "s.maeda.kobe"
        },
        "state": "Tokyo",
        "zip": "1530063"
    }
Esempio n. 26
0
 def mailer(self, api_token):
     return SendGridAPIClient(api_token)
Esempio n. 27
0
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python

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

message = Mail(
    from_email='*****@*****.**',
    to_emails='*****@*****.**',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
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('error!')
    print(e.message)
Esempio n. 28
0
def send_mail(from_email, to_email, subject, content):
    sg = SendGridAPIClient()
    content = Content('text/html', content)
    mail = Mail(Email(from_email), subject, Email(to_email), content)
    return sg.client.mail.send.post(request_body=mail.get())
Esempio n. 29
0
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

from settings import MAIL_LIST, SENDGRID_API_KEY, TEMPLATE_ID

sg = SendGridAPIClient(api_key=SENDGRID_API_KEY)


def send_mail(data: dict):
    """
    {"country":"Bangladesh","cases":13770,"todayCases":636,"deaths":214,"todayDeaths":8,"recovered":2414,"active":11142,
    "critical":1,"casesPerOneMillion":84,"deathsPerOneMillion":1,"totalTests":116919,"testsPerOneMillion":710}
    :param data:
    :return:
    """
    try:
        dynamic = {
            "total_cases": data.get("cases", 0),
            "total_deaths": data.get("deaths", 0),
            "total_recovered": data.get("recovered", 0),
            "today_deaths": data.get("todayDeaths", 0),
            "affected": data.get("todayCases", 0)
        }
        for mail in MAIL_LIST:
            message = Mail(
                from_email='*****@*****.**',
                to_emails=mail,
            )
            message.template_id = TEMPLATE_ID
            message.dynamic_template_data = dynamic
            res = sg.send(message)
Esempio n. 30
0
    to_emails=to_address,
    subject=subject,
    plain_text_content=text,
    html_content=html)

if cc_addresses is not None:
  ccs = []

  for cc_address in cc_addresses:
    ccs.append(Cc(cc_address))
    
  message.cc = ccs

if bcc_addresses is not None:
  bccs = []

  for bcc_address in bcc_addresses:
    bccs.append(Bcc(bcc_address))

  message.bcc = bccs

try:
    sg = SendGridAPIClient(api_key)
    response = sg.send(message)
    to_address_string = ', '.join(to_address)

    print(f'Your email titled "{subject}" was sent successfully to: {to_address_string}' )
except Exception as e:
    print(str(e))
    exit(1)