Python sendgrid.helpers.mail.Mail() Examples
The following are 15
code examples of sendgrid.helpers.mail.Mail().
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.helpers.mail
, or try the search function
.
Example #1
Source File: email.py From selene-backend with GNU Affero General Public License v3.0 | 6 votes |
def send(self, using_jinja=False): message = Mail( from_email=self.message.sender, to_emails=[self.message.recipient], subject=self.message.subject, html_content=self._build_content(using_jinja) ) response = self.mailer.client.mail.send.post(request_body=message.get()) if response.status_code < 300: _log.info('Email sent successfully') else: _log.error( 'Email failed to send. Status code: {} ' 'Status message: {}'.format(response.status_code, response.body) )
Example #2
Source File: sendgrid_email.py From open-source-library-data-collector with MIT License | 6 votes |
def send_email(self, to_email, from_email, subject, body): """Send the email :param to_email: who the email is going to (e.g. 'First Last <email@example.com>') :param from_email: who the email is coming from (e.g. 'First Last <email@example.com>') :param subject: the email subject line :param body: the email body in HTML format :type to_email: string :type from_email: string :type subject: string :type body: string :returns: HTML status code and JSON message from SendGrid's API :rtype: Integer, JSON """ from_email = Email(from_email) subject = subject to_email = Email(to_email) soup = BeautifulSoup(body, "html.parser") content = Content("text/plain", soup.get_text()) mail = Mail(from_email, subject, to_email, content) response = self.sendgrid.client.mail.send.post(request_body=mail.get()) return response.status_code, response.body
Example #3
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 #4
Source File: send_email.py From beans with MIT License | 6 votes |
def send_single_email(email, subject, template, template_arguments): """ Send an email using the SendGrid API Args: - email :string => the user's work email (ie username@company.com) - subject :string => the subject line for the email - template :string => the template file, corresponding to the email sent. - template_arguments :dictionary => keyword arguments to specify to render_template Returns: - SendGrid response """ load_secrets() env = Environment(loader=PackageLoader('yelp_beans', 'templates')) template = env.get_template(template) rendered_template = template.render(template_arguments) message = mail.Mail( from_email=mail.Email(SENDGRID_SENDER), subject=subject, to_email=mail.Email(email), content=Content("text/html", rendered_template) ) return send_grid_client.client.mail.send.post(request_body=message.get())
Example #5
Source File: flask_sendgrid.py From flask-sendgrid with MIT License | 6 votes |
def __init__(self, app=None, **opts): if app: self.init_app(app) super(SGMail, self).__init__() self.from_email = None self.subject = None self._personalizations = None self._contents = None self._attachments = None self._template_id = None self._sections = None self._headers = None self._categories = None self._custom_args = None self._send_at = None self._batch_id = None self._asm = None self._ip_pool_name = None self._mail_settings = None self._tracking_settings = None self._reply_to = None
Example #6
Source File: sendgrid_connector_test.py From forseti-security with Apache License 2.0 | 6 votes |
def test_can_send_email_to_single_recipient(self): """Test can send email to single recipient.""" new_email = mail.Mail() email_recipient = 'foo@company.com' email_sender = 'bar@company.com' email_connector_config = { 'fake_sendgrid_key': 'xyz010' } email_util = sendgrid_connector.SendgridConnector( email_sender, email_recipient, email_connector_config) new_email = email_util._add_recipients(new_email, email_recipient) self.assertEqual(1, len(new_email.personalizations)) added_recipients = new_email.personalizations[0].tos self.assertEqual(1, len(added_recipients)) self.assertEqual('foo@company.com', added_recipients[0].get('email'))
Example #7
Source File: sendgrid_connector_test.py From forseti-security with Apache License 2.0 | 6 votes |
def test_can_send_email_to_multiple_recipients(self): """Test can send email to multiple recipients.""" new_email = mail.Mail() email_recipient = 'foo@company.com,bar@company.com' email_sender = 'xyz@company.com' email_connector_config = { 'fake_sendgrid_key': 'xyz010' } email_util = sendgrid_connector.SendgridConnector( email_sender, email_recipient, email_connector_config) new_email = email_util._add_recipients(new_email, email_recipient) self.assertEqual(1, len(new_email.personalizations)) added_recipients = new_email.personalizations[0].tos self.assertEqual(2, len(added_recipients)) self.assertEqual('foo@company.com', added_recipients[0].get('email')) self.assertEqual('bar@company.com', added_recipients[1].get('email'))
Example #8
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 #9
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 #10
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 #11
Source File: sendgrid_email_adapter.py From Flask-User with MIT License | 5 votes |
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via sendgrid-python. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in HTML. text_message: The message body in plain text. """ if not current_app.testing: # pragma: no cover try: # Prepare Sendgrid helper objects from sendgrid.helpers.mail import Email, Content, Substitution, Mail from_email = Email(sender_email, sender_name) to_email = Email(recipient) text_content = Content('text/plain', text_message) html_content = Content('text/html', html_message) # Prepare Sendgrid Mail object # Note: RFC 1341: text must be first, followed by html mail = Mail(from_email, subject, to_email, text_content) mail.add_content(html_content) # Send mail via the Sendgrid API response = self.sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) except ImportError: raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE) except Exception as e: print(e) print(e.body) raise
Example #12
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 #13
Source File: email.py From PROTON with BSD 3-Clause "New" or "Revised" License | 5 votes |
def send_email(cls, to_email, subject, html_content, from_email='proton_framework@apricity.co.in'): """ PROTONs postman. :param to_email: valid email to which email needs to be sent to. :param subject: Email subject :param html_content: Email content.(Can include HTML markups) :param from_email: valid email from which email has to be sent from. (default: proton_framework@apricity.co.in) :return: A dictionary containing email status code, email body and email headers. """ try: message = Mail( from_email=from_email, to_emails=to_email, subject=subject, html_content=ProtonEmail.__email_decorator(html_content)) response = cls.__sg.send(message) return { 'email_status_code': response.status_code, 'email_body': response.body, 'email_headers': response.headers } except Exception as e: cls.email_logger.exception('[Email]: Unable to send email. Details to follow.') cls.email_logger.exception(str(e))
Example #14
Source File: sendgrid_connector.py From forseti-security with Apache License 2.0 | 4 votes |
def send(self, email_sender=None, email_recipient=None, email_subject=None, email_content=None, content_type=None, attachment=None): """Send an email. This uses the SendGrid API. https://github.com/sendgrid/sendgrid-python The minimum required info to send email are: sender, recipient, subject, and content (the body) Args: email_sender (str): The email sender. email_recipient (str): The email recipient. email_subject (str): The email subject. email_content (str): The email content (aka, body). content_type (str): The email content type. attachment (Attachment): A SendGrid Attachment. Raises: EmailSendError: An error with sending email has occurred. """ if not email_sender or not email_recipient: LOGGER.warning('Unable to send email: sender=%s, recipient=%s', email_sender, email_recipient) raise util_errors.EmailSendError email = mail.Mail() email.from_email = mail.Email(email_sender) email.subject = email_subject email.add_content(mail.Content(content_type, email_content)) email = self._add_recipients(email, email_recipient) if attachment: email.add_attachment(attachment) try: response = self._execute_send(email) except urllib.error.HTTPError as e: LOGGER.exception('Unable to send email: %s %s', e.code, e.reason) raise util_errors.EmailSendError if response.status_code == 202: LOGGER.info('Email accepted for delivery:\n%s', email_subject) else: LOGGER.error('Unable to send email:\n%s\n%s\n%s\n%s', email_subject, response.status_code, response.body, response.headers) raise util_errors.EmailSendError
Example #15
Source File: utils.py From ok with Apache License 2.0 | 4 votes |
def send_email(to, subject, body, cc=(), from_name='Ok', link=None, link_text="Sign in", template='email/notification.html', reply_to=None, **kwargs): """ Send an email using sendgrid. Usage: send_email('student@okpy.org', 'Hey from OK', 'hi', cc=['test@example.com'], reply_to='ta@cs61a.org') """ try: sg = _get_sendgrid_api_client() except ValueError as ex: logger.error('Unable to get sendgrid client: %s', ex) return False if not link: link = url_for('student.index', _external=True) html = render_template(template, subject=subject, body=body, link=link, link_text=link_text, **kwargs) mail = sg_helpers.Mail() mail.set_from(sg_helpers.Email('no-reply@okpy.org', from_name)) mail.set_subject(subject) mail.add_content(sg_helpers.Content("text/html", emailFormat(html))) if reply_to: mail.set_reply_to(sg_helpers.Email(reply_to)) personalization = sg_helpers.Personalization() personalization.add_to(sg_helpers.Email(to)) for recipient in cc: personalization.add_cc(sg_helpers.Email(recipient)) mail.add_personalization(personalization) try: response = sg.client.mail.send.post(request_body=mail.get()) except HTTPError: logger.error("Could not send the email", exc_info=True) return False if response.status_code != 202: logger.error("Could not send email: {} - {}" .format(response.status_code, response.body)) return False return True