def gdpr_removal_send_email(removal_request_email, shop_url, referringpage, country): request_date = datetime.date.today().strftime('%B %d %Y') # Create and Activate session for API calls ShopDeatzInst = ShopDeatz.objects.get(shop_url=shop_url) session = shopify.Session(shop_url, ShopDeatzInst.auth_token) shopify.ShopifyResource.activate_session(session) # Gets an object that contains all the shop info eqvalent to GET endpoint /admin/shop.json shop_info = shopify.Shop.current() # Make customer instance to check if customer email exists customer deatails (returns a list so use the first one) search_query = 'email:' + str(removal_request_email) CustomerInst = shopify.Customer.search(q=search_query) if len(CustomerInst) <= 0: # ############################################################## # Log INVALID Data Removal in Audit Table (All times are in UTC) # ############################################################## current_datetime = datetime.datetime.now() action = 'Invalid Data Removal Request' method = 'Data Removal Form' comment = 'Email does not correspond to any record in the database. No data removed.' customer_id = 'Unregistered Customer' marketing_consent = '-' status = 'Completed' legal_basis = '-' purpose = '-' # Create AuditLog Instance AuditLogInst = DataEventLogger(shop_url) # Add Data Removal Entry line AuditLogInst.insert_data_processing_event(current_datetime, action, method, referringpage, comment,\ customer_id, purpose, status, legal_basis) return 0 else: pass # Generate 101 character random string confirmation code confirmation_code = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(101)) # Check if removal_email exists in RemovalConfirmationCodes in the database for this user # (because user might have clciked multiple times on the delete link by mistake which would generate new entries in the DB) # if it exists then just change the confirmation code, otherwise write a new entry for the user email try: ConfirmationCodesInst = RemovalConfirmationCodes.objects.get(removal_request_email=removal_request_email) ConfirmationCodesInst.confirmation_code = confirmation_code ConfirmationCodesInst.save() except ObjectDoesNotExist: ConfirmationCodesInst = RemovalConfirmationCodes() ConfirmationCodesInst.confirmation_code = confirmation_code ConfirmationCodesInst.removal_request_email = removal_request_email ConfirmationCodesInst.save() removal_link = "https://cdn1.gdprinsider.ovh/dataevent/?" + "requesttype=confirmremoval" + "&shopurl=" + shop_url \ + "&email=" + removal_request_email + "&country=" + country + "&confirm=" + confirmation_code SENDER = str(shop_info.name) + "<*****@*****.**>" # Replace [email protected] with a "To" address. If your account RECIPIENT = str(removal_request_email) # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES. AWS_REGION = "eu-west-1" # The email body for recipients with non-HTML email clients. BODY_TEXT = ( "Hi there,\r\n" "In response to your subject data removal request received on %s, please click the following link to " "complete your data removal process.\r\n" "%s \r\n" "Please note that your data will be purged from our store's system and that we will no longer have any trace of " "your customer details and purchase history. As such, you will no longer be entitled to any refunds or product exchanges.\r\n" "Thank you for your inquiry.\r\n" "Regards,\r\n" "%s" ) %( request_date, removal_link, str(shop_info.name) ) # print BODY_TEXT ############################################### # The HTML body of the email. ############################################### # FRENCH EMAIL TEMPLATE if country == 'France': # The subject line for the email. SUBJECT = str(shop_info.name) + " - GDPR Demande de Suppression de Données" # Create French format request_date request_date = datetime.date.today().strftime('%d/%m/%Y') # Get content of html template template_relative_location = 'templates/emailtemplates/data_del_FR.html' filelocation = os.path.join(settings.BASE_DIR, template_relative_location) BODY_HTML = "" for line in open(filelocation): new_line = unicode(line.decode("utf-8")) new_line = new_line.rstrip('\n') # print new_line BODY_HTML = BODY_HTML + new_line # ALL OTHER (ENGLISH EMAIL TEMPLATE) else: # The subject line for the email. SUBJECT = str(shop_info.name) + " - GDPR Data Removal Request" # Get content of html template template_relative_location = 'templates/emailtemplates/data_del.html' filelocation = os.path.join(settings.BASE_DIR, template_relative_location) BODY_HTML = "" for line in open(filelocation): new_line = line.rstrip('\n') # print new_line BODY_HTML = BODY_HTML + new_line # Replace content BODY_HTML = BODY_HTML.replace('#STORENAME#', str(shop_info.name)) BODY_HTML = BODY_HTML.replace('#REQUESTDATE#', request_date) BODY_HTML = BODY_HTML.replace('#DATAREMOVELINK#', removal_link) # print '\n' # print '#####################################################################' # print BODY_HTML # The character encoding for the email. CHARSET = "UTF-8" ########################################################### # EMAIL SENDING CODE BLOCK ########################################################### # Try to send the email. try: # Select the email sending service to use SendGrid or Amazon depending on value of settings.ACTIVE_TRANSACTIONALEMAIL_SERVICE if settings.ACTIVE_TRANSACTIONALEMAIL_SERVICE == 'AMAZON': # Create a new SES resource and specify a region. client = boto3.client( 'ses', region_name=AWS_REGION, aws_access_key_id=settings.aws_id, aws_secret_access_key=settings.aws_secret ) #Provide the contents of the email. response = client.send_email( Destination={ 'ToAddresses': [ RECIPIENT, ], }, Message={ 'Body': { 'Html': { 'Charset': CHARSET, 'Data': BODY_HTML, }, 'Text': { 'Charset': CHARSET, 'Data': BODY_TEXT, }, }, 'Subject': { 'Charset': CHARSET, 'Data': SUBJECT, }, }, Source=SENDER, # If you are not using a configuration set, comment or delete the # following line #ConfigurationSetName=CONFIGURATION_SET, ) elif settings.ACTIVE_TRANSACTIONALEMAIL_SERVICE == 'SENDGRID': sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(email="*****@*****.**", name=str(shop_info.name)) to_email = Email(RECIPIENT) subject = SUBJECT content = Content("text/html", BODY_HTML) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) # Display an error if something goes wrong. except ClientError as e: print ("ERROR - Failed to send email to %s") %(RECIPIENT) print(e.response.status_code) else: print("Email sent! Message ID:") print(response.status_code) # ####################################################### # Log Data Removal in Audit Table (All times are in UTC) # ####################################################### current_datetime = datetime.datetime.now() action = 'Data Removal Request' method = 'Data Removal Form' comment = 'Confirmation link sent via email to the address on record.' customer_id = CustomerInst[0].id marketing_consent = CustomerInst[0].accepts_marketing status = 'Completed' if marketing_consent is True: legal_basis = 'Preparing or Performing a Contract (Product Sales) and Consent (Granted for Marketing)' purpose = 'Ecommerce - Processing Customer Purchases and Marketing' else: legal_basis = 'Preparing or Performing a Contract (Product Sales)' purpose = 'Ecommerce - Processing Customer Purchases' # Create AuditLog Instance AuditLogInst = DataEventLogger(shop_url) # Add Data Removal Entry line AuditLogInst.insert_data_processing_event(current_datetime, action, method, referringpage, comment,\ customer_id, purpose, status, legal_basis) return 0
def __init__(self, config, logger): self.config = config self.logger = logger self.sendgrid_client = sendgrid.SendGridAPIClient( apikey=self.config['sendgrid_api_key'])
def visit(self): """visit the queue. return 3 if too early, 2 if already sent, 1 if random not met, 0 if sent (in that order of precedence)""" starttime = datetime.time(hour=self.starthour, minute=self.startminute, tzinfo=timezone(self.timezone)) now = datetime.datetime.now(timezone(self.timezone)) # assemble the hour/minute for the starttime for today start = datetime.datetime.combine(now.date(), starttime) if now < start: logger.info( '[{2}] now: [{0}] < start: [{1}] so we wont bother yet.'. format(now, start, self.collectionname)) return {'val': 3, 'msg': 'tooearly'} timestamp = self.timestampfunction() for item in self.collection.find({'sent': timestamp}): logger.info( '[{1}]: A message already exists with timestamp [{0}]'.format( timestamp, self.collectionname)) return {'val': 2, 'msg': 'alreadysent'} randomtest = randint(0, self.randomlevel) if randomtest != 0: logger.info('[{1}]: Random requirement NOT met: [{0}] != 0'.format( randomtest, self.collectionname)) return {'val': 1, 'msg': 'randomnotmet'} # all the pre-reqs are satisfied. gather a message and send it for item in self.collection.find({ 'sent': { '$exists': False } }).sort('orderid'): logger.info('Random requirement met. Sending message') logger.info('Item: [{0}]'.format(repr(item))) if self.deliverymethod == 'txt': txtclient = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) for recipient in self.target.split(','): logger.info('[{0}]: Sending txt message to [{1}]'.format( self.collectionname, recipient)) if item['mediaurl']: txtclient.messages.create(to=recipient, from_=TWILIO_FROM, body=item['text'], media_url=item['mediaurl']) else: txtclient.messages.create(to=recipient, from_=TWILIO_FROM, body=item['text']) if self.deliverymethod == 'email': subject = (item['text'] or 'picture enclosed')[:72] toaddresses = [{'email': x} for x in self.target.split(',')] #mail = Mail(Email("*****@*****.**"), subject, Email(self.target), Content("text/html", "<html><body><img src='"+item['mediaurl']+"' /></body></html>")) data = { 'personalizations': [{ 'to': toaddresses, 'subject': subject }], 'from': { 'email': '*****@*****.**' }, 'content': [{ 'type': 'text/html', 'value': "<html><body><img src='" + item['mediaurl'] + "' /></body></html>" }] } logger.info('[{0}]: Sending email message: {1}'.format( self.collectionname, data)) response = sendgrid.SendGridAPIClient( apikey=SENDGRID_API_KEY).client.mail.send.post( request_body=data) logger.info(response.status_code) logger.info(response.body) logger.info('Updating mongodb') self.collection.update_one({'id': item['id']}, {'$set': { 'sent': timestamp }}) return {'val': 0, 'msg': 'OK'}
session = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) session.resource("s3").Bucket("tcf-accounts-key").download_file( "key.json", "key.json") cred = credentials.Certificate("key.json") try: firebase_admin.initialize_app(cred) except Exception as e: print(e) db = firestore.client() sg = sendgrid.SendGridAPIClient(apikey=os.getenv("SENDGRID_API_KEY")) # ------------ API EXTENSION ------------ # @application.route("/api/verify-token", methods=["POST"]) def api_verify_token(): token = request.form.get("token") if not token: return jsonify({ "statusCode": 406, "message": "missing id token: " + str(e) }) try: decoded_token: dict = auth.verify_id_token(token) except Exception as e:
API is part of library that defines how it will interact with external code. Every library has API, API is sum of all public/exported stuff. Nowadays meaning of API is widened. we might call the way web site/service interact with code as API also. You can also tell that some device has API - the set of commands you can call. Sometimes this terms can be mixed together. For example you have some server app. It has API with it, and this API is implemented as a library. But this library is just a middle layer you and not the one who executes your calls. But if library itself contains all action code then we can't say that this library is API. ''' #question5 import sendgrid import os from sendgrid.helpers.mail import * sg = sendgrid.SendGridAPIClient(apikey='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') from_email = Email("*****@*****.**") to_email = Email("*****@*****.**") subject = "Sending with SendGrid is Fun" content = Content("text/plain", "and easy to do anywhere, even with Python") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print("response.status_code",response.status_code) print("response.body",response.body) print("response.headers",response.headers)
#!/usr/bin/env python import os import random import string import argparse import psycopg2 import sendgrid import sendgrid.helpers.mail as mail sendgrid_client = sendgrid.SendGridAPIClient( api_key=os.environ.get("SENDGRID_API_KEY")) argparser = argparse.ArgumentParser() argparser.add_argument("newsletter_id") args = argparser.parse_args() newsletter_id = args.newsletter_id def slurp(path): with open(path) as file: return file.read() def spit(path, content): with open(path, "w") as file: file.write(content)
def __init__(self): self.logger.info("sendgrid email provider created") self._sg = sendgrid.SendGridAPIClient( api_key=config.email.sendgrid.key)
from importlib import import_module from django.template.loader import render_to_string from django.conf import settings if settings.MAIL["SEND"]: # pragma: no cover if settings.MAIL["SEND_MODE"] == "AWS": # pragma: no cover client = import_module("boto3").client("ses") elif settings.MAIL["SEND_MODE"] == "SENDGRID": # pragma: no cover import sendgrid sg = sendgrid.SendGridAPIClient(settings.MAIL["SENDGRID_API_KEY"]) def send_email(send_to, subject_line, template_name, **template_details): if settings.MAIL["SEND"]: # pragma: no cover if settings.MAIL["SEND_MODE"] == "AWS": # pragma: no cover template_details[ "url"] = settings.FRONTEND_URL + template_details["url"] client.send_email( Destination={"ToAddresses": [send_to]}, Message={ "Body": { "Html": { "Charset": "UTF-8", "Data": render_to_string(template_name + ".html", template_details) }, "Text": { "Charset":
ACCESS_TOKEN_SECRET = os.environ.get("TWITTER_ACCESS_TOKEN_SECRET") SENDGRID_API_KEY = os.environ.get( "SENDGRID_API_KEY", "OOPS, please set env var called 'SENDGRID_API_KEY'") MY_ADDRESS = os.environ.get( "MY_EMAIL_ADDRESS", "OOPS, please set env var called 'MY_EMAIL_ADDRESS'") SENDGRID_TEMPLATE_ID = os.environ.get( "SENDGRID_TEMPLATE_ID", "OOPS, please set env var called 'SENDGRID_TEMPLATE_ID") # AUTHENTICATE sgclient = SendGridAPIClient( SENDGRID_API_KEY) #> <class 'sendgrid.sendgrid.SendGridAPIClient> auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY) # INITIALIZE API CLIENT client = tweepy.API(auth) # ISSUE REQUEST(S) user = client.me() # get information about the currently authenticated user data = client.user_timeline('NYCTSubway', exclude_replies=True, include_rts=False) #timezone fix utc = pytz.timezone('UTC')
import sendgrid import os from sendgrid.helpers.mail import Mail, Email, To, Content Hello="message" sg = sendgrid.SendGridAPIClient('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') from_email = Email("*****@*****.**") # Change to your verified sender to_email = To("*****@*****.**") # Change to your recipient subject = "Sending with SendGrid is Fun" content = Content("text/plain",Hello) mail = Mail(from_email, to_email, subject, content) # Get a JSON-ready representation of the Mail object mail_json = mail.get() # Send an HTTP POST request to /mail/send response = sg.client.mail.send.post(request_body=mail_json) print(response.status_code) print(response.headers)
from pynliner import fromString as emailFormat import pytz import requests import sendgrid import sendgrid.helpers.mail as sg_helpers from server import constants logger = logging.getLogger(__name__) # ID hashing configuration. # DO NOT CHANGE ONCE THE APP IS PUBLICLY AVAILABLE. You will break every # link with an ID in it. hashids = Hashids(min_length=6) sg = sendgrid.SendGridAPIClient(apikey=os.getenv('SENDGRID_KEY')) def encode_id(id_number): return hashids.encode(id_number) def decode_id(value): numbers = hashids.decode(value) if len(numbers) != 1: raise ValueError('Could not decode hash {0} into ID'.format(value)) return numbers[0] def convert_markdown(text): # https://pythonadventures.wordpress.com/tag/markdown/ allowed_tags = [
_EMAIL_BODY = """Hello {},\n You are getting this email because you have been accepted to jacobsHack! Fall 2016 that is happening on 15th - 16th October at Jacobs University in Bremen, Germany. We will be using Slack as our primary mode of communication before, during, and after the event. Please join our Slack team at https://jacobshack.skillflow.io/ to talk with other hackers and mentors attending the event. We would like you to let us know if you can make it to the event or not. If you haven't done so already, please RSVP: https://jacobshack.typeform.com/to/b8Lagp You can also join the event on facebook for more updates https://www.facebook.com/events/277473712613843/ Event Schedule: Registration opens at 9 AM on 15th October (Saturday) and the opening ceremony starts at 10.30 AM. A more detailed schedule can be found on https://2016f.jacobshack.com/#schedule If you have any questions, feel free to Email us at [email protected] or message us on Facebook and Twitter. Looking forward to see you in Bremen! Cheers,\n The jacobsHack! team""" _SENDGRID = sendgrid.SendGridAPIClient(apikey="SENDGRID_API_KEY") def email_body(recepient_name): return _EMAIL_BODY.format(recepient_name) def send_email(sender, recepient, recepient_name): mail = Mail(sender, _SUBJECT, recepient, Content("text/plain", _EMAIL_BODY.format(recepient_name))) resoponse = _SENDGRID.client.mail.send.post(request_body=mail.get()) return resoponse if __name__ == '__main__': import os
sender = mail_to_send['sender'] sender_name = mail_to_send['sender_name'] receiver = mail_to_send['receiver'] receiver_name = mail_to_send['receiver_name'] subject = mail_to_send['subject'] emsg = mail_to_send['message'] # mdata = mail_to_send['data'] id_msg = mail_to_send['id'] try: mdata = json.loads(mdata) except: mdata = {} sg = sendgrid.SendGridAPIClient(apikey=__res['sg_key']) from sendgrid.helpers.mail import * message = Mail() personal = Personalization() message.set_from(Email(sender, sender_name)) personal.add_to(Email(receiver, receiver_name)) message.add_personalization(personal) message.set_subject(subject) message.add_content(Content("text/html", emsg)) m_data = message.get() response = sg.client.mail.send.post(request_body=m_data) print(response, type(response)) m_id = response.headers.get('X-Message-Id') if m_id:
def gdpr_copy(copy_request_email, shop_url, referringpage, country): request_date = datetime.date.today().strftime('%B %d %Y') # Create and Activate session for API calls ShopDeatzInst = ShopDeatz.objects.get(shop_url=shop_url) session = shopify.Session(shop_url, ShopDeatzInst.auth_token) shopify.ShopifyResource.activate_session(session) # Gets an object that contains all the shop info eqvalent to GET endpoint /admin/shop.json shop_info = shopify.Shop.current() # Make customer instance to extract customer deatails (returns a list so use the first one) # .find() will not work on Customers using params, Search queries are only available on the Customer resource as a separate .search() method # This is because to search, you need to access a different endpont not /admin/customers.json but rather /admin/customers/search.json search_query = 'email:' + str(copy_request_email) CustomerInst = shopify.Customer.search(q=search_query) if len(CustomerInst) <= 0: # ############################################################## # Log INVALID Data Access in Audit Table (All times are in UTC) # ############################################################## current_datetime = datetime.datetime.now() action = 'Invalid Data Access Request' method = 'Data Access Form' comment = 'Email does not correspond to any record in the database. No data transmitted.' customer_id = 'Unregistered Customer' marketing_consent = '-' status = 'Completed' legal_basis = '-' purpose = '-' # Create AuditLog Instance AuditLogInst = DataEventLogger(shop_url) # Add Data Removal Entry line AuditLogInst.insert_data_processing_event(current_datetime, action, method, referringpage, comment,\ customer_id, purpose, status, legal_basis) return 0 else: pass SENDER = str(shop_info.name) + "<*****@*****.**>" # Replace [email protected] with a "To" address. If your account RECIPIENT = str(copy_request_email) # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES. AWS_REGION = "eu-west-1" # The email body for recipients with non-HTML email clients. BODY_TEXT = ("Hi there,\r\n" "In response to your subject data access request received on %s, " "please find below the requested copy of your personal data.\r\n" '---------------------------------------------\r\n' 'Email: %s\r\n' 'First Name: %s\r\n' 'Last Name: %s\r\n' 'Phone: %s\r\n' 'Company: %s\r\n' 'Address: %s\r\n' 'Address: %s\r\n' 'City: %s\r\n' 'Province: %s\r\n' 'Country: %s\r\n' '---------------------------------------------\r\n' "As per European General Data Protection Regulation, you may rectify this data at any time by " "loging in to your shop account. Alternatively, you can request data removal by clicking the data " "icon at the bottom of the store's pages.\r\n" "Thank you for your inquiry.\r\n" "Regards,\r\n" "%s" ) %( request_date, str(CustomerInst[0].email), str(CustomerInst[0].first_name), str(CustomerInst[0].last_name), str(CustomerInst[0].phone), str(CustomerInst[0].addresses[0].company), str(CustomerInst[0].addresses[0].address1), str(CustomerInst[0].addresses[0].address2), str(CustomerInst[0].addresses[0].city), str(CustomerInst[0].addresses[0].province), str(CustomerInst[0].addresses[0].country), str(shop_info.name) ) # print BODY_TEXT ############################################# # The HTML body of the email. ############################################# # FRENCH EMAIL TEMPLATE if country == 'France': # The subject line for the email. SUBJECT = str(shop_info.name) + " - GDPR Demande de Copie de Données" # Create French format request_date request_date = datetime.date.today().strftime('%d/%m/%Y') # Get content of html template template_relative_location = 'templates/emailtemplates/data_copy_FR.html' filelocation = os.path.join(settings.BASE_DIR, template_relative_location) BODY_HTML = "" for line in open(filelocation): new_line = unicode(line.decode("utf-8")) new_line = new_line.rstrip('\n') # print unicodedata.normalize('NFKD', new_line).encode('utf-8','ignore') BODY_HTML = BODY_HTML + new_line # ALL OTHERS (ENGLISH EMAIL TEMPLATE) else: # The subject line for the email. SUBJECT = str(shop_info.name) + " - GDPR Data Access Request" template_relative_location = 'templates/emailtemplates/data_copy.html' filelocation = os.path.join(settings.BASE_DIR, template_relative_location) BODY_HTML = "" for line in open(filelocation): new_line = line.rstrip('\n') BODY_HTML = BODY_HTML + new_line # replace content of template BODY_HTML = BODY_HTML.replace('#STORENAME#', str(shop_info.name)) BODY_HTML = BODY_HTML.replace('#REQUESTDATE#', request_date) BODY_HTML = BODY_HTML.replace('#EMAIL#', str(CustomerInst[0].email)) BODY_HTML = BODY_HTML.replace('#FNAME#', str(CustomerInst[0].first_name)) BODY_HTML = BODY_HTML.replace('#LNAME#', str(CustomerInst[0].last_name)) BODY_HTML = BODY_HTML.replace('#PHONE#', str(CustomerInst[0].phone)) BODY_HTML = BODY_HTML.replace('#COMPANY#', str(CustomerInst[0].addresses[0].company)) BODY_HTML = BODY_HTML.replace('#ADDRESS1#', str(CustomerInst[0].addresses[0].address1)) BODY_HTML = BODY_HTML.replace('#ADDRESS2#', str(CustomerInst[0].addresses[0].address2)) BODY_HTML = BODY_HTML.replace('#CITY#', str(CustomerInst[0].addresses[0].city)) BODY_HTML = BODY_HTML.replace('#PROVINCE#', str(CustomerInst[0].addresses[0].province)) BODY_HTML = BODY_HTML.replace('#COUNTRY#', str(CustomerInst[0].addresses[0].country)) BODY_HTML = BODY_HTML.replace('#ZIP#', str(CustomerInst[0].addresses[0].zip)) # print '\n' # print '#####################################################################' # print BODY_HTML # The character encoding for the email. CHARSET = "UTF-8" ########################################################### # EMAIL SENDING CODE BLOCK ########################################################### # Try to send the email. try: # Select the email sending service to use SendGrid or Amazon depending on value of settings.ACTIVE_TRANSACTIONALEMAIL_SERVICE if settings.ACTIVE_TRANSACTIONALEMAIL_SERVICE == 'AMAZON': # Create a new SES resource and specify a region. client = boto3.client( 'ses', region_name=AWS_REGION, aws_access_key_id=settings.aws_id, aws_secret_access_key=settings.aws_secret ) #Provide the contents of the email. response = client.send_email( Destination={ 'ToAddresses': [ RECIPIENT, ], }, Message={ 'Body': { 'Html': { 'Charset': CHARSET, 'Data': BODY_HTML, }, 'Text': { 'Charset': CHARSET, 'Data': BODY_TEXT, }, }, 'Subject': { 'Charset': CHARSET, 'Data': SUBJECT, }, }, Source=SENDER, # If you are not using a configuration set, comment or delete the # following line #ConfigurationSetName=CONFIGURATION_SET, ) elif settings.ACTIVE_TRANSACTIONALEMAIL_SERVICE == 'SENDGRID': sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(email="*****@*****.**", name=str(shop_info.name)) to_email = Email(RECIPIENT) subject = SUBJECT content = Content("text/html", BODY_HTML) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) # Display an error if something goes wrong. except ClientError as e: print ("ERROR - Failed to send email to %s") %(RECIPIENT) print(e.response.status_code) else: print("Email sent! Message ID:"), print(response.status_code) # ####################################################### # Log Data Access in Audit Table (All times are in UTC) # ####################################################### current_datetime = datetime.datetime.now() action = 'Data Access Request' method = 'Data Access Form' comment = 'Requested data transmitted via email to the address on record.' customer_id = CustomerInst[0].id marketing_consent = CustomerInst[0].accepts_marketing status = 'Completed' if marketing_consent is True: legal_basis = 'Preparing or Performing a Contract (Product Sales) and Consent (Granted for Marketing)' purpose = 'Ecommerce - Processing Customer Purchases and Marketing' else: legal_basis = 'Preparing or Performing a Contract (Product Sales)' purpose = 'Ecommerce - Processing Customer Purchases' # Create AuditLog Instance AuditLogInst = DataEventLogger(shop_url) # Add Data Removal Entry line AuditLogInst.insert_data_processing_event(current_datetime, action, method, referringpage, comment,\ customer_id, purpose, status, legal_basis) return 0
currentUpdatePeriod += UPDATE_PERIOD_SECS currentUpdatePeriod = UPDATE_PERIOD_SECS if BALANCE_REPORTING: print("I have", balanceETH, " ETH") print("I have", balanceBTC, " BTC") print("I have", balanceUSDT, " USDT") if len(tradehistory) >= 1: nicetradehistory = pprint.pformat(tradehistory) print(nicetradehistory) if NOTIFY_METHOD == 'email': print("Trades / Send email") sg = sendgrid.SendGridAPIClient( apikey='add_your_sendgrid_api_key_here') from_email = Email(EMAIL_FROM) subject = "Poloniex Status / Order Update" to_email = Email(EMAIL_TO) if BALANCE_REPORTING: content = "BTC: " + balanceBTC + "\n\nETH: " + balanceETH + "\n\nUSDT " + balanceUSDT + "\n\n" + nicetradehistory else: content = nicetradehistory email_content = Content("text/plain", content) #content = Content("text/plain", "BTC: ") mail = Mail(from_email, subject, to_email, email_content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers)
# # # send_email('*****@*****.**', 'oduvan') # send_email('*****@*****.**', 'Some Body') # # END_DESC import sendgrid from sendgrid.helpers.mail import Mail API_KEY = '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' SUBJECT = 'Welcome' BODY = 'Hi {}' FROM_EMAIL = '*****@*****.**' sg = sendgrid.SendGridAPIClient(API_KEY) def send_email(email, name): message = Mail(from_email=FROM_EMAIL, to_emails=email, subject=SUBJECT, plain_text_content=BODY.format(name)) try: response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message)
from decouple import config from django.conf import settings import sendgrid from sendgrid.helpers.mail import To, From, Mail FROM_EMAIL = config('FROM_EMAIL') PYBITES = 'PyBites' sg = sendgrid.SendGridAPIClient(api_key=config('SENDGRID_API_KEY')) def send_email(to_email, subject, body, from_email=FROM_EMAIL, html=True): from_email = From(email=from_email, name=PYBITES) to_email = To(to_email) # if local no emails if settings.LOCAL: body = body.replace('<br>', '\n') print('local env - no email, only print send_email args:') print(f'to_email: {to_email.email}') print(f'subject: {subject}') print(f'body: {body}') print(f'from_email: {from_email.email}') print(f'html: {html}') print() return # newlines get wrapped in email, use html body = body.replace('\n', '<br>') message = Mail(from_email=from_email,
return fetchall(q, batch) def get_unread_batches(userid): q = 'SELECT batch from batchunread where voter=%s' return set(x.batch for x in fetchall(q, userid)) def mark_batch_read(batch, user): l('mark_batch_read', gid=batch, uid=user) q = 'DELETE FROM batchunread WHERE batch=%s AND voter=%s' execute(q, batch, user) """ Discussion """ _USER_FB_ITSD = itsdangerous.URLSafeSerializer(os.environ['ITSD_KEY']) _SENDGRID = sendgrid.SendGridAPIClient(apikey=os.environ['SENDGRID_API_KEY']) _EMAIL_FROM = os.environ['EMAIL_FROM'] _WEB_HOST = os.environ['WEB_HOST'] _TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') _JINJA = Environment(loader=FileSystemLoader(_TEMPLATE_PATH)) def get_discussion(proposal): q = '''SELECT discussion.*, users.display_name FROM discussion LEFT JOIN users ON (users.id=discussion.frm) WHERE proposal=%s ORDER BY created ASC''' return fetchall(q, proposal) def add_to_discussion(userid, proposal, body, feedback=False, name=None): l('add_to_discussion', uid=userid, id=proposal, body=body, feedback=feedback, name=name)
elif o in ("-k", "--key"): efrom = a elif o in ("-f", "--from"): efrom = a elif o in ("-t", "--to"): eto = a elif o in ("-a", "--attach"): attach_files.append(a) elif o in ("-s", "--subject"): subject = a elif o in ("-m", "--message"): message = a else: assert False, "unhandled option" sg = sendgrid.SendGridAPIClient(api_key=key) from_email = Email(efrom) to_email = To(eto) content = Content("text/html", message) mail = Mail(from_email, to_email, subject, content) file_types = { '.log': 'text/plain', '.txt': 'text/plain', '.tar': 'application/x-tar' } if (len(attach_files) > 0): for fn in attach_files: with open(fn, 'rb') as f: data = f.read() f.close()
def land(logname, lastrow, nrows, platform='Unknown', sender='*****@*****.**', recipient=None): """ Sends summary report to land via email. Args: logname (str): directory name under which log results are saved. lastrow (int): Last row of data delivered in past email. nrows (int): Number of rows to sent in current email. platform (str): Name of platform, the "callsign" for ships. """ # Get dataframe from CSV log file path = os.path.join(os.path.dirname(__file__), '..', 'log', logname, '') csv = path + logname + '.csv' df = pd.read_csv(csv) # Return last row sent and exit if dataframe has less than n new rows if len(df[lastrow:]) < nrows: return lastrow # Proceed with new delivery otherwise else: delivery = df[lastrow:lastrow + nrows] # Set sender, recipient, and subject sender = Email(sender) if recipient is None: raise Exception('No recipient email address') recipient = Email(recipient) subject = 'RapidKrill report: %s_%s' % ( platform, delivery.Time.tail(1).values[0]) # Prepare text content text = io.StringIO() text.write('Attachment header: %s, %s, %s, %s, %s, %s, %s, %s\n' % tuple(delivery.columns)) text = text.getvalue() # Prepare attachment data data = io.StringIO() for i, row in delivery.iterrows(): data.write( '%s, %10.5f, %9.5f, %4.0f, %5.1f, %6.1f, %10.2f, %5.1f\n' % tuple(row)) data = data.getvalue() # Build email and send logger.info('Sending report to land') config = os.path.join(os.path.dirname(__file__), 'config.toml') if not toml.load(config)['sendgrid']['key'].strip(): raise Exception('No sendgrid key in config.file. Report not sent.') apikey = toml.load(config)['sendgrid']['key'] sg = sendgrid.SendGridAPIClient(apikey=apikey) content = Content('text/plain', text) attachment = Attachment() encoded = base64.b64encode(str.encode(data)).decode() attachment.content = encoded attachment.type = 'application/csv' attachment.filename = 'data.csv' mail = Mail(sender, subject, recipient, content) mail.add_attachment(attachment) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code is 202: logger.info('Report sent') else: logger.warning('Sending report failed') # Return new last row sent lastrow = lastrow + nrows return lastrow
def __init__(self, api_key): self.sender = sendgrid.SendGridAPIClient(apikey=api_key)
def sendEmail(key, a, b, c, d): return sendgrid.SendGridAPIClient( apikey=key).client.mail.send.post(request_body=Mail( Email(a), b, Email(c), Content('text/plain', d)).get())
import os import sendgrid from sendgrid.helpers.mail import Email, Content, Mail # Email Infrastructure # -------------------- API_KEY = os.environ['SENDGRID_API_KEY'] sg = sendgrid.SendGridAPIClient(apikey=API_KEY) TEMPLATE = """{} --{} ========= This note of thanks was brought to you by SayThanks.io. A KennethReitz project, now maintained by KGiSL Edu ([email protected]). """ def notify(note, email_address): # Say 'someone' if the byline is empty. try: who = note.byline or 'someone' subject = 'saythanks.io: {} sent a note!'.format(who) message = TEMPLATE.format(note.body, note.byline)
def send_email(body): flask_app.logger.fatal("Sending email from Celery...") sg_api = sendgrid.SendGridAPIClient(apikey=constants.SENDGRID_API_KEY) sg_api.client.mail.send.post(request_body=body)
def index(request): if request.user.is_authenticated(): user = request.user cafe = Cafe.objects.get(user=user) return render(request, 'cafe/home.html', {'cafe':cafe, }) if request.method == 'POST': # data = request.POST # recaptcha_response = data['g-recaptcha-response'] # data_1 = { # 'secret' : recaptcha_key, # 'response' : recaptcha_response # } # r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data_1) # result = r.json() # if not result['success']: # return JsonResponse({'status':0, 'message':'Invalid Recaptcha. Try Again'}) email = data['email'] if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): return JsonResponse({'status':0, 'message':'Please enter a valid email address.'}) try: Cafe.objects.get(email=data['email']) return JsonResponse({'status':0, 'message':'Email already registered.'}) except: pass else: cafe = Cafe() cafe.name = str(data['name']) cafe.city = str(data['city']) cafe.state = str(data['state']) cafe.email = str(data['email']) cafe.phone_no = int(data['phone']) username = data['username'] password = data['password'] user = User.objects.create_user(username=username, password=password) user.is_active = False user.save() send_to = str(request.POST["email"]) name = str(request.POST["name"]) body = ''' Hello %s! Thank you for registering! <a href='%s'>Click Here</a> to verify your email. </pre> '''%(name, str(request.build_absolute_uri(reverse("cafe:index"))) + 'email_confirm/' + generate_email_token(cafe) + '/') # email = EmailMultiAlternatives("Registration for BOSM '17", 'Click '+ str(request.build_absolute_uri(reverse("registrations:email_confirm", kwargs={'token':generate_email_token(GroupLeader.objects.get(email=send_to))}))) + '/' + ' to confirm.', # '*****@*****.**', [send_to.strip()] # ) # email.attach_alternative(body, "text/html") sg = sendgrid.SendGridAPIClient(apikey=API_KEY) from_email = Email('*****@*****.**') to_email = Email(send_to) subject = "Registration for StarConnect" content = Content('text/html', body) try: mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) except : cafe.delete() return JsonResponse({'status':0, 'message':'Error sending email. Please try again.'}) message = "A confirmation link has been sent to %s. Kindly click on it to verify your email address." %(send_to) return JsonResponse({'status':1, 'message':message}) else: return render(request, 'cafe/signup.html',)
data = json.load(f) """ UNCOMMENT THIS ONLY IF YOU ARE SURE TO SEND 950 mail with open('team_mail.json') as f: data = json.load(f) """ count_success = 0 for d in data: team = d['name'] mails = d['emails'] #print (team,mails) for m in mails: try: sg = sendgrid.SendGridAPIClient(api_key="{XXX_REDACTED_XXX}") from_email = Email("*****@*****.**") to_email = To(m) mail = Mail(from_email, to_email) mail.dynamic_template_data = {'team': team} mail.template_id = "d-9669ed3cda7042acac1c701f00531de1" with open("/home/kooli/Documents/Certs/Certs/" + team + ".png", 'rb') as sigf: sig = sigf.read() encoded = base64.b64encode(sig).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('image/png') attachment.file_name = FileName(team + ".png") attachment.disposition = Disposition('attachment')
def __init__(self): self.sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) self.from_email = Email(os.environ.get('BAK_EMAIL'))
import sendgrid import json import os sg = sendgrid.SendGridAPIClient(apikey='YOUR_SENDGRID_API_KEY') # You can also store your API key an .env variable 'SENDGRID_API_KEY' ################################################## # Retrieve global email statistics # # GET /stats # params = { 'aggregated_by': 'day', 'limit': 1, 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 1 } response = sg.client.stats.get(query_params=params) print(response.status_code) print(response.response_body) print(response.response_headers)
import sendgrid import json import os sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) ################################################## # Retrieve all IP addresses # # GET /ips # params = { 'subuser': '******', 'ip': 'test_string', 'limit': 1, 'exclude_whitelabels': 'true', 'offset': 1 } response = sg.client.ips.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve all assigned IPs # # GET /ips/assigned # response = sg.client.ips.assigned.get() print(response.status_code) print(response.body) print(response.headers)
def add_heart_rate(): """ adds a new heart rate reading to the patient's info and updates the tachcardia status flag :return: json returns the information stored for the new patient """ # try: r = request.get_json() check = new_heart_rate_validation(r) s1 = r.get("patient_id") s1_int = int(s1) s2 = r.get("heart_rate") s2_float = float(s2) if check: user = users[s1_int] id = user.get("patient_id") if id is not None: user_heartrate = user.get("heart_rate") user_heartrate.append(s2_float) user["heart_rate"] = user_heartrate user_timestamps = user.get("timestamps") user_timestamps.append(datetime.now()) user["timestamps"] = user_timestamps if s2_float > 159 and (float(user.get("age")) * 365) <= 2: user["tach"] = True elif s2_float > 166 and (float(user.get("age"))*365) > 2 \ and (float(user.get("age"))*365) <= 6: user["tach"] = True elif s2_float > 182 and (float(user.get("age"))*365) > 6 \ and (float(user.get("age"))*365) <= 21: user["tach"] = True elif s2_float > 179 and (float(user.get("age"))*365) > 21 \ and (float(user.get("age"))*365) <= 62: user["tach"] = True elif s2_float > 186 and (float(user.get("age"))*365) > 62 \ and (float(user.get("age"))*365) <= 155: user["tach"] = True elif s2_float > 169 and (float(user.get("age"))*365) > 155 \ and (float(user.get("age"))*365) <= 341: user["tach"] = True elif s2_float > 151 and float(user.get("age")) >= 1 \ and float(user.get("age")) <= 2: user["tach"] = True elif s2_float > 137 and float(user.get("age")) > 2 \ and float(user.get("age")) <= 4: user["tach"] = True elif s2_float > 133 and float(user.get("age")) > 4 \ and float(user.get("age")) <= 7: user["tach"] = True elif s2_float > 130 and float(user.get("age")) > 7 \ and float(user.get("age")) <= 11: user["tach"] = True elif s2_float > 119 and float(user.get("age")) > 11 \ and float(user.get("age")) <= 15: user["tach"] = True elif s2_float > 100 and float(user.get("age")) > 15: user["tach"] = True users[s1_int] = user sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("*****@*****.**") to_email = Email(user.get("attending_email")) subject = "ALERT: Tachycardic" content = Content("text/plain", "Patient" + s1 + " is Tachycardic") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return jsonify(user) return jsonify({"message": "Error occurred, check your inputs"}), 500