Python sendgrid.SendGridAPIClient() Examples
The following are 25
code examples of sendgrid.SendGridAPIClient().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sendgrid
, or try the search function
.
Example #1
Source File: emailer.py From impactstory-tng with MIT License | 7 votes |
def send(address, subject, template_name, context, for_real=False): templateLoader = jinja2.FileSystemLoader(searchpath="templates") templateEnv = jinja2.Environment(loader=templateLoader) html_template = templateEnv.get_template(template_name + ".html") html_to_send = html_template.render(context) sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("team@impactstory.org", "Impactstory team") to_email = Email(address) content = Content("text/html", html_to_send) mail = Mail(from_email, subject, to_email, content) if for_real: response = sg.client.mail.send.post(request_body=mail.get()) print u"Sent an email to {}".format(address) else: print u"Didn't really send"
Example #2
Source File: report.py From gophish-cli with MIT License | 6 votes |
def get_sendgrid_stats(self): sg = sendgrid.SendGridAPIClient(apikey=config.SENDGRID_API_KEY) start_date = self.get_first_event_ts().strftime('%Y-%m-%d') params = {'aggregated_by': 'day', 'limit': 1, 'start_date': start_date, 'end_date': start_date, 'offset': 1} response = sg.client.stats.get(query_params=params) if response.status_code == 200: self.sendgrid_stats = json.loads(response.body.decode('utf-8'))[0]['stats'][0]['metrics'] else: self.sendgrid_stats = []
Example #3
Source File: sendgrid_connector.py From forseti-security with Apache License 2.0 | 6 votes |
def __init__(self, sender, recipient, auth, custom=None): """Initialize the email util. Args: sender (str): The email sender. recipient (str): The email recipient. auth (dict): A set of authentication attributes corresponding to the selected connector. custom (dict): A set of custom attributes. """ self.sender = sender self.recipient = recipient if auth.get('api_key'): api_key = auth.get('api_key') # else block below is for backward compatibility else: api_key = auth.get('sendgrid_api_key') self.sendgrid = sendgrid.SendGridAPIClient(apikey=api_key) if custom: LOGGER.warning('Unable to process custom attributes: %s', custom)
Example #4
Source File: sendgrid_email_adapter.py From Flask-User with MIT License | 6 votes |
def __init__(self, app): """Check config settings and setup SendGrid Web API v3. Args: app(Flask): The Flask application instance. """ super(SendgridEmailAdapter, self).__init__(app) sendgrid_api_key = app.config.get('SENDGRID_API_KEY') if not sendgrid_api_key: raise ConfigError( "The SENDGRID_API_KEY setting is missing. Set SENDGRID_API_KEY in your app config.") # Setup sendgrid-python try: from sendgrid import SendGridAPIClient self.sg = SendGridAPIClient(apikey=sendgrid_api_key) except ImportError: raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
Example #5
Source File: main.py From python-docs-samples with Apache License 2.0 | 6 votes |
def send_email(): recipient = request.form.get('to') if not recipient: return ('Please provide an email address in the "to" query string ' 'parameter.'), 400 message = Mail( from_email=SENDGRID_SENDER, to_emails='{},'.format(recipient), subject='This is a test email', html_content='<strong>Example</strong> message.') sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) if response.status_code != 202: return 'An error occurred: {}'.format(response.body), 500 return 'Email sent.' # [END gae_flex_sendgrid]
Example #6
Source File: send_email.py From beans with MIT License | 5 votes |
def load_secrets(): if secrets is not None: return global secrets, send_grid_client, SENDGRID_SENDER secrets = json.loads(open("client_secrets.json").read()) # TODO (rkwills) switch to a yelp sendgrid account send_grid_client = SendGridAPIClient(apikey=secrets["SENDGRID_API_KEY"]) SENDGRID_SENDER = secrets["SENDGRID_SENDER"]
Example #7
Source File: sendgrid_mail.py From docassemble with MIT License | 5 votes |
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() 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.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) #sys.stderr.write("SendGrid status code: " + str(response.status_code) + "\n") #sys.stderr.write(str(response.body) + "\n") #sys.stderr.write("SendGrid response headers: " + str(response.headers) + "\n") if response.status_code >= 400: raise Exception("Failed to send e-mail message to SendGrid") email_dispatched.send(message, app=current_app._get_current_object())
Example #8
Source File: mail.py From sendgrid-django with MIT License | 5 votes |
def __init__(self, fail_silently=False, **kwargs): super(SendGridBackend, self).__init__( fail_silently=fail_silently, **kwargs) if 'api_key' in kwargs: self.api_key = kwargs['api_key'] else: self.api_key = getattr(settings, "SENDGRID_API_KEY", None) if not self.api_key: raise ImproperlyConfigured(''' SENDGRID_API_KEY must be declared in settings.py''') self.sg = sendgrid.SendGridAPIClient(apikey=self.api_key) self.version = 'sendgrid/{0};django'.format(__version__) self.sg.client.request_headers['User-agent'] = self.version
Example #9
Source File: sendgrid.py From diffengine with MIT License | 5 votes |
def mailer(self, api_token): return SendGridAPIClient(api_token)
Example #10
Source File: utils.py From ok with Apache License 2.0 | 5 votes |
def _get_sendgrid_api_client(): if constants.SENDGRID_KEY: return sendgrid.SendGridAPIClient(apikey=constants.SENDGRID_KEY) raise ValueError('no sendgrid credentials available')
Example #11
Source File: services.py From pets with MIT License | 5 votes |
def send_email(subject, to, template_name, context): sendgrid_client = sendgrid.SendGridAPIClient(settings.SENDGRID_API_KEY) from_email = settings.DEFAULT_FROM_EMAIL to_emails = to content = render_to_string(template_name, context) mail = Mail(from_email, to_emails, subject, content) return sendgrid_client.send(mail)
Example #12
Source File: email.py From love with MIT License | 5 votes |
def send_sendgrid_email(sender, recipient, subject, body_html, body_text): key = logic.secret.get_secret('SENDGRID_API_KEY') sg = sendgrid.SendGridAPIClient(apikey=key) from_ = sendgrid.helpers.mail.Email(*get_name_and_email(sender)) to = sendgrid.helpers.mail.Email(*get_name_and_email(recipient)) content_html = sendgrid.helpers.mail.Content('text/html', body_html) content_text = sendgrid.helpers.mail.Content('text/plain', body_text) # text/plain needs to be before text/html or sendgrid gets mad message = sendgrid.helpers.mail.Mail(from_, subject, to, content_text) message.add_content(content_html) sg.client.mail.send.post(request_body=message.get())
Example #13
Source File: flask_sendgrid.py From flask-sendgrid with MIT License | 5 votes |
def init_app(self, app): self.app = app self.api_key = app.config['SENDGRID_API_KEY'] self.default_from = app.config['SENDGRID_DEFAULT_FROM'] self.client = SendGridAPIClient(self.api_key).client
Example #14
Source File: fundamentus.py From bovespaStockRatings with MIT License | 5 votes |
def send_email(message): try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) except Exception as e: print("Deu erro na hora de enviar o email", str(e))
Example #15
Source File: main.py From python-docs-samples with Apache License 2.0 | 5 votes |
def send_simple_message(recipient): # [START sendgrid-send] message = Mail( from_email=SENDGRID_SENDER, to_emails='{},'.format(recipient), subject='This is a test email', html_content='<strong>Example</strong> message.') sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) return response # [END sendgrid-send]
Example #16
Source File: SendGrid.py From Cortex-Analyzers with GNU Affero General Public License v3.0 | 5 votes |
def run(self): Responder.run(self) subject = self.get_param('data.title', None, 'title is missing') # format and dump the data we received into them email for content. # it's 2020, human operators should be able to parse JSON content = Content("text/plain", json.dumps(self.get_param('data', None, 'no data to work with'), indent=2)) content = Content("text/html", '<pre>' + json.dumps(self.get_param('data', None, 'no data to work with'), indent=2) + '</pre>') to_emails = [] if self.data_type == 'thehive:case': # pull recipient addresses from tags where prefixed with mail: # if multiple tags exist multiple deliveries will occur tags = self.get_param('data.tags', None, 'recipient address not found in tags') for t in tags: if t.startswith('mail:'): to_emails.append(To(t[5:])) if to_emails == []: self.error('recipient address not found in case tags') elif self.data_type == 'thehive:alert': # pull recipient address to email from artifacts? # NOTE: this is an artifact from the original "Mailer" responder, WTF would we email any old observable address???? # have adjusted from Mailer behaviour, observable email address must be prefixed with "mail:" in the same way as case tags artifacts = self.get_param('data.artifacts', None, 'recipient address not found in observables') mail_artifacts = [a['data'] for a in artifacts if a.get('dataType') == 'mail' and 'data' in a] for t in mail_artifacts: if t.startswith('mail:'): to_emails.append(To(t[5:])) if to_emails == []: self.error('recipient address not found in alert observables') else: self.error('Invalid data type %' % self.data_type) if to_emails != []: # build the message content that we'll deliver message = Mail(Email(self.from_email), to_emails, subject, content) try: sg = SendGridAPIClient(self.api_key) response = sg.send(message) self.report({'message': 'message sent'}) except Exception as e: self.report({'message': 'exception raised'}) else: self.report({'message': 'no destination email addresses found'})
Example #17
Source File: sendgrid_email.py From open-source-library-data-collector with MIT License | 5 votes |
def __init__(self): # Check if we are not in heroku sendgrid_api_key = os.environ.get('SENDGRID_APY_KEY') if \ os.environ.get('ENV') != 'prod' else os.environ['SENDGRID_API_KEY'] self.sendgrid = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key)
Example #18
Source File: manage.py From awslimits with Apache License 2.0 | 5 votes |
def send_alerts(): limits_for_alert = get_limits_for_alert() if limits_for_alert: content = alert_email_body(limits_for_alert) recipients = [{'email': email} for email in settings.EMAIL_RECIPIENTS.split(',')] sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY) data = { 'content': [ { 'type': 'text/html', 'value': '<html>{}</html>'.format(content) } ], 'from': { 'email': settings.FROM_EMAIL_ADDRESS, 'name': settings.FROM_EMAIL_NAME }, 'personalizations': [ { 'to': recipients } ], 'subject': "AWS Limit Alerts for ID {}".format(settings.ACCOUNT_ID), } sg.client.mail.send.post(request_body=data) save_sent_alerts(limits_for_alert)
Example #19
Source File: emailer.py From airflow with Apache License 2.0 | 5 votes |
def _post_sendgrid_mail(mail_data): sendgrid_client = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) response = sendgrid_client.client.mail.send.post(request_body=mail_data) # 2xx status code. if 200 <= response.status_code < 300: log.info('Email with subject %s is successfully sent to recipients: %s', mail_data['subject'], mail_data['personalizations']) else: log.error('Failed to send out email with subject %s, status code: %s', mail_data['subject'], response.status_code)
Example #20
Source File: sendgrid_mail.py From WeixinBot with Apache License 2.0 | 5 votes |
def __init__(self, apikey, from_email, to_email): self.sg = sendgrid.SendGridAPIClient(apikey=apikey) self.from_email = Email(from_email) self.to_email = Email(to_email)
Example #21
Source File: mail.py From clusterfuzz with Apache License 2.0 | 5 votes |
def send(to_email, subject, html_content): """Send email.""" sendgrid_api_key = db_config.get_value('sendgrid_api_key') if not sendgrid_api_key: logs.log_warn('Skipping email as SendGrid API key is not set in config.') return from_email = db_config.get_value('sendgrid_sender') if not from_email: logs.log_warn('Skipping email as SendGrid sender is not set in config.') return message = Mail( from_email=From(str(from_email)), to_emails=To(str(to_email)), subject=Subject(subject), html_content=HtmlContent(str(html_content))) try: sg = SendGridAPIClient(sendgrid_api_key) response = sg.send(message) logs.log( 'Sent email to %s.' % to_email, status_code=response.status_code, body=response.body, headers=response.headers) except Exception: logs.log_error('Failed to send email to %s.' % to_email)
Example #22
Source File: scrape_regression_test.py From oadoi with MIT License | 5 votes |
def _send_report(subject, report, to_address): content = Content("text/plain", report) from_email = Email("dev@ourresearch.org", "Unpaywall Team") to_email = Email(to_address) email = Mail(from_email, subject, to_email, content) tracking_settings = TrackingSettings() tracking_settings.click_tracking = ClickTracking(False, False) email.tracking_settings = tracking_settings sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) sg.client.mail.send.post(request_body=email.get()) logger.info(u'sent "{}" report to {}'.format(subject, to_address))
Example #23
Source File: emailer.py From oadoi with MIT License | 5 votes |
def send(email, for_real=False): if for_real: sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) email_get = email.get() response = sg.client.mail.send.post(request_body=email_get) print u"Sent an email" else: print u"Didn't really send"
Example #24
Source File: email.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, message: EmailMessage): self.mailer = SendGridAPIClient(api_key=os.environ['SENDGRID_API_KEY']) self.message = message
Example #25
Source File: mail.py From django-sendgrid-v5 with MIT License | 4 votes |
def __init__(self, *args, **kwargs): super(SendgridBackend, self).__init__(*args, **kwargs) if "api_key" in kwargs: self.sg = sendgrid.SendGridAPIClient(api_key=kwargs["api_key"]) elif hasattr(settings, "SENDGRID_API_KEY") and settings.SENDGRID_API_KEY: self.sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY) else: raise ImproperlyConfigured("settings.py must contain a value for SENDGRID_API_KEY. " + "You may also pass a value to the api_key argument (optional).") sandbox_mode_in_debug = True if hasattr(settings, "SENDGRID_SANDBOX_MODE_IN_DEBUG"): sandbox_mode_in_debug = settings.SENDGRID_SANDBOX_MODE_IN_DEBUG self.sandbox_mode = bool(settings.DEBUG) and bool(sandbox_mode_in_debug) if self.sandbox_mode: warnings.warn("Sendgrid email backend is in sandbox mode! Emails will not be delivered.") track_email = True if hasattr(settings, "SENDGRID_TRACK_EMAIL_OPENS"): track_email = settings.SENDGRID_TRACK_EMAIL_OPENS self.track_email = track_email track_clicks_html = True if hasattr(settings, "SENDGRID_TRACK_CLICKS_HTML"): track_clicks_html = settings.SENDGRID_TRACK_CLICKS_HTML self.track_clicks_html = track_clicks_html track_clicks_plain = True if hasattr(settings, "SENDGRID_TRACK_CLICKS_PLAIN"): track_clicks_plain = settings.SENDGRID_TRACK_CLICKS_PLAIN self.track_clicks_plain = track_clicks_plain if hasattr(settings, "SENDGRID_ECHO_TO_STDOUT") and settings.SENDGRID_ECHO_TO_STDOUT: self._lock = threading.RLock() self.stream = kwargs.pop('stream', sys.stdout) else: self._lock = None self.stream = None